id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_good_1536_0 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* lib/krb5/krb/bld_princ.c - Build a principal from a list of strings */
/*
* Copyright 1991 by the Massachusetts Institute of Technology.
* All Rights Reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*/
#include "k5-int.h"
static krb5_error_code
build_principal_va(krb5_context context, krb5_principal princ,
unsigned int rlen, const char *realm, va_list ap)
{
krb5_error_code retval = 0;
char *r = NULL;
krb5_data *data = NULL;
krb5_int32 count = 0;
krb5_int32 size = 2; /* initial guess at needed space */
char *component = NULL;
data = malloc(size * sizeof(krb5_data));
if (!data) { retval = ENOMEM; }
if (!retval)
r = k5memdup0(realm, rlen, &retval);
while (!retval && (component = va_arg(ap, char *))) {
if (count == size) {
krb5_data *new_data = NULL;
size *= 2;
new_data = realloc(data, size * sizeof(krb5_data));
if (new_data) {
data = new_data;
} else {
retval = ENOMEM;
}
}
if (!retval) {
data[count].length = strlen(component);
data[count].data = strdup(component);
if (!data[count].data) { retval = ENOMEM; }
count++;
}
}
if (!retval) {
princ->type = KRB5_NT_UNKNOWN;
princ->magic = KV5M_PRINCIPAL;
princ->realm = make_data(r, rlen);
princ->data = data;
princ->length = count;
r = NULL; /* take ownership */
data = NULL; /* take ownership */
}
if (data) {
while (--count >= 0) {
free(data[count].data);
}
free(data);
}
free(r);
return retval;
}
krb5_error_code KRB5_CALLCONV
krb5_build_principal_va(krb5_context context,
krb5_principal princ,
unsigned int rlen,
const char *realm,
va_list ap)
{
return build_principal_va(context, princ, rlen, realm, ap);
}
krb5_error_code KRB5_CALLCONV
krb5_build_principal_alloc_va(krb5_context context,
krb5_principal *princ,
unsigned int rlen,
const char *realm,
va_list ap)
{
krb5_error_code retval = 0;
krb5_principal p;
p = malloc(sizeof(krb5_principal_data));
if (p == NULL)
return ENOMEM;
retval = build_principal_va(context, p, rlen, realm, ap);
if (retval) {
free(p);
return retval;
}
*princ = p;
return 0;
}
krb5_error_code KRB5_CALLCONV_C
krb5_build_principal(krb5_context context,
krb5_principal * princ,
unsigned int rlen,
const char * realm, ...)
{
krb5_error_code retval = 0;
va_list ap;
va_start(ap, realm);
retval = krb5_build_principal_alloc_va(context, princ, rlen, realm, ap);
va_end(ap);
return retval;
}
/*Anonymous and well known principals*/
static const char anon_realm_str[] = KRB5_ANONYMOUS_REALMSTR;
static const krb5_data anon_realm_data = {
KV5M_DATA, sizeof(anon_realm_str) - 1, (char *) anon_realm_str
};
static const char wellknown_str[] = KRB5_WELLKNOWN_NAMESTR;
static const char anon_str[] = KRB5_ANONYMOUS_PRINCSTR;
static const krb5_data anon_princ_data[] = {
{ KV5M_DATA, sizeof(wellknown_str) - 1, (char *) wellknown_str },
{ KV5M_DATA, sizeof(anon_str) - 1, (char *) anon_str }
};
const krb5_principal_data anon_princ = {
KV5M_PRINCIPAL,
{ KV5M_DATA, sizeof(anon_realm_str) - 1, (char *) anon_realm_str },
(krb5_data *) anon_princ_data, 2, KRB5_NT_WELLKNOWN
};
const krb5_data * KRB5_CALLCONV
krb5_anonymous_realm()
{
return &anon_realm_data;
}
krb5_const_principal KRB5_CALLCONV
krb5_anonymous_principal()
{
return &anon_princ;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_1536_0 |
crossvul-cpp_data_good_339_8 | /*
* cryptoflex-tool.c: Tool for doing various Cryptoflex related stuff
*
* Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include "libopensc/sc-ossl-compat.h"
#include "libopensc/internal.h"
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include "libopensc/pkcs15.h"
#include "common/compat_strlcpy.h"
#include "common/compat_strlcat.h"
#include "util.h"
static const char *app_name = "cryptoflex-tool";
static char * opt_reader = NULL;
static int opt_wait = 0;
static int opt_key_num = 1, opt_pin_num = -1;
static int verbose = 0;
static int opt_exponent = 3;
static int opt_mod_length = 1024;
static int opt_key_count = 1;
static int opt_pin_attempts = 10;
static int opt_puk_attempts = 10;
static const char *opt_appdf = NULL, *opt_prkeyf = NULL, *opt_pubkeyf = NULL;
static u8 *pincode = NULL;
static const struct option options[] = {
{ "list-keys", 0, NULL, 'l' },
{ "create-key-files", 1, NULL, 'c' },
{ "create-pin-file", 1, NULL, 'P' },
{ "generate-key", 0, NULL, 'g' },
{ "read-key", 0, NULL, 'R' },
{ "verify-pin", 0, NULL, 'V' },
{ "key-num", 1, NULL, 'k' },
{ "app-df", 1, NULL, 'a' },
{ "prkey-file", 1, NULL, 'p' },
{ "pubkey-file", 1, NULL, 'u' },
{ "exponent", 1, NULL, 'e' },
{ "modulus-length", 1, NULL, 'm' },
{ "reader", 1, NULL, 'r' },
{ "wait", 0, NULL, 'w' },
{ "verbose", 0, NULL, 'v' },
{ NULL, 0, NULL, 0 }
};
static const char *option_help[] = {
"Lists all keys in a public key file",
"Creates new RSA key files for <arg> keys",
"Creates a new CHV<arg> file",
"Generates a new RSA key pair",
"Reads a public key from the card",
"Verifies CHV1 before issuing commands",
"Selects which key number to operate on [1]",
"Selects the DF to operate in",
"Private key file",
"Public key file",
"The RSA exponent to use in key generation [3]",
"Modulus length to use in key generation [1024]",
"Uses reader <arg>",
"Wait for card insertion",
"Verbose operation. Use several times to enable debug output.",
};
static sc_context_t *ctx = NULL;
static sc_card_t *card = NULL;
static char *getpin(const char *prompt)
{
char *buf, pass[20];
int i;
printf("%s", prompt);
fflush(stdout);
if (fgets(pass, 20, stdin) == NULL)
return NULL;
for (i = 0; i < 20; i++)
if (pass[i] == '\n')
pass[i] = 0;
if (strlen(pass) == 0)
return NULL;
buf = malloc(8);
if (buf == NULL)
return NULL;
if (strlen(pass) > 8) {
fprintf(stderr, "PIN code too long.\n");
free(buf);
return NULL;
}
memset(buf, 0, 8);
strlcpy(buf, pass, 8);
return buf;
}
static int verify_pin(int pin)
{
char prompt[50];
int r, tries_left = -1;
if (pincode == NULL) {
sprintf(prompt, "Please enter CHV%d: ", pin);
pincode = (u8 *) getpin(prompt);
if (pincode == NULL || strlen((char *) pincode) == 0)
return -1;
}
if (pin != 1 && pin != 2)
return -3;
r = sc_verify(card, SC_AC_CHV, pin, pincode, 8, &tries_left);
if (r) {
memset(pincode, 0, 8);
free(pincode);
pincode = NULL;
fprintf(stderr, "PIN code verification failed: %s\n", sc_strerror(r));
return -1;
}
return 0;
}
static int select_app_df(void)
{
sc_path_t path;
sc_file_t *file;
char str[80];
int r;
strcpy(str, "3F00");
if (opt_appdf != NULL)
strlcat(str, opt_appdf, sizeof str);
sc_format_path(str, &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select application DF: %s\n", sc_strerror(r));
return -1;
}
if (file->type != SC_FILE_TYPE_DF) {
fprintf(stderr, "Selected application DF is not a DF.\n");
return -1;
}
sc_file_free(file);
if (opt_pin_num >= 0)
return verify_pin(opt_pin_num);
else
return 0;
}
static void invert_buf(u8 *dest, const u8 *src, size_t c)
{
size_t i;
for (i = 0; i < c; i++)
dest[i] = src[c-1-i];
}
static BIGNUM * cf2bn(const u8 *buf, size_t bufsize, BIGNUM *num)
{
u8 tmp[512];
invert_buf(tmp, buf, bufsize);
return BN_bin2bn(tmp, bufsize, num);
}
static int bn2cf(const BIGNUM *num, u8 *buf)
{
u8 tmp[512];
int r;
r = BN_bn2bin(num, tmp);
if (r <= 0)
return r;
invert_buf(buf, tmp, r);
return r;
}
static int parse_public_key(const u8 *key, size_t keysize, RSA *rsa)
{
const u8 *p = key;
BIGNUM *n, *e;
int base;
base = (keysize - 7) / 5;
if (base != 32 && base != 48 && base != 64 && base != 128) {
fprintf(stderr, "Invalid public key.\n");
return -1;
}
p += 3;
n = BN_new();
if (n == NULL)
return -1;
cf2bn(p, 2 * base, n);
p += 2 * base;
p += base;
p += 2 * base;
e = BN_new();
if (e == NULL)
return -1;
cf2bn(p, 4, e);
if (RSA_set0_key(rsa, n, e, NULL) != 1)
return -1;
return 0;
}
static int gen_d(RSA *rsa)
{
BN_CTX *bnctx;
BIGNUM *r0, *r1, *r2;
const BIGNUM *rsa_p, *rsa_q, *rsa_n, *rsa_e, *rsa_d;
BIGNUM *rsa_n_new, *rsa_e_new, *rsa_d_new;
bnctx = BN_CTX_new();
if (bnctx == NULL)
return -1;
BN_CTX_start(bnctx);
r0 = BN_CTX_get(bnctx);
r1 = BN_CTX_get(bnctx);
r2 = BN_CTX_get(bnctx);
RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d);
RSA_get0_factors(rsa, &rsa_p, &rsa_q);
BN_sub(r1, rsa_p, BN_value_one());
BN_sub(r2, rsa_q, BN_value_one());
BN_mul(r0, r1, r2, bnctx);
if ((rsa_d_new = BN_mod_inverse(NULL, rsa_e, r0, bnctx)) == NULL) {
fprintf(stderr, "BN_mod_inverse() failed.\n");
return -1;
}
/* RSA_set0_key will free previous value, and replace with new value
* Thus the need to copy the contents of rsa_n and rsa_e
*/
rsa_n_new = BN_dup(rsa_n);
rsa_e_new = BN_dup(rsa_e);
if (RSA_set0_key(rsa, rsa_n_new, rsa_e_new, rsa_d_new) != 1)
return -1;
BN_CTX_end(bnctx);
BN_CTX_free(bnctx);
return 0;
}
static int parse_private_key(const u8 *key, size_t keysize, RSA *rsa)
{
const u8 *p = key;
BIGNUM *bn_p, *q, *dmp1, *dmq1, *iqmp;
int base;
base = (keysize - 3) / 5;
if (base != 32 && base != 48 && base != 64 && base != 128) {
fprintf(stderr, "Invalid private key.\n");
return -1;
}
p += 3;
bn_p = BN_new();
if (bn_p == NULL)
return -1;
cf2bn(p, base, bn_p);
p += base;
q = BN_new();
if (q == NULL)
return -1;
cf2bn(p, base, q);
p += base;
iqmp = BN_new();
if (iqmp == NULL)
return -1;
cf2bn(p, base, iqmp);
p += base;
dmp1 = BN_new();
if (dmp1 == NULL)
return -1;
cf2bn(p, base, dmp1);
p += base;
dmq1 = BN_new();
if (dmq1 == NULL)
return -1;
cf2bn(p, base, dmq1);
p += base;
if (RSA_set0_factors(rsa, bn_p, q) != 1)
return -1;
if (RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp) != 1)
return -1;
if (gen_d(rsa))
return -1;
return 0;
}
static int read_public_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = MIN(file->size, sizeof buf);
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_public_key(p, keysize, rsa);
}
static int read_private_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
const sc_acl_entry_t *e;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I0012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r));
return 2;
}
e = sc_file_get_acl_entry(file, SC_AC_OP_READ);
if (e == NULL || e->method == SC_AC_NEVER)
return 10;
bufsize = MIN(file->size, sizeof buf);
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_private_key(p, keysize, rsa);
}
static int read_key(void)
{
RSA *rsa = RSA_new();
u8 buf[1024], *p = buf;
u8 b64buf[2048];
int r;
if (rsa == NULL)
return -1;
r = read_public_key(rsa);
if (r)
return r;
r = i2d_RSA_PUBKEY(rsa, &p);
if (r <= 0) {
fprintf(stderr, "Error encoding public key.\n");
return -1;
}
r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64);
if (r < 0) {
fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r));
return -1;
}
printf("-----BEGIN PUBLIC KEY-----\n%s-----END PUBLIC KEY-----\n", b64buf);
r = read_private_key(rsa);
if (r == 10)
return 0;
else if (r)
return r;
p = buf;
r = i2d_RSAPrivateKey(rsa, &p);
if (r <= 0) {
fprintf(stderr, "Error encoding private key.\n");
return -1;
}
r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64);
if (r < 0) {
fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r));
return -1;
}
printf("-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n", b64buf);
return 0;
}
static int list_keys(void)
{
int r, idx = 0;
sc_path_t path;
u8 buf[2048], *p = buf;
size_t keysize, i;
int mod_lens[] = { 512, 768, 1024, 2048 };
size_t sizes[] = { 167, 247, 327, 647 };
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
do {
int mod_len = -1;
r = sc_read_binary(card, idx, buf, 3, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
idx += keysize;
for (i = 0; i < sizeof(sizes)/sizeof(sizes[ 0]); i++)
if (sizes[i] == keysize)
mod_len = mod_lens[i];
if (mod_len < 0)
printf("Key %d -- unknown modulus length\n", p[2] & 0x0F);
else
printf("Key %d -- Modulus length %d\n", p[2] & 0x0F, mod_len);
} while (1);
return 0;
}
static int generate_key(void)
{
sc_apdu_t apdu;
u8 sbuf[4];
u8 p2;
int r;
switch (opt_mod_length) {
case 512:
p2 = 0x40;
break;
case 768:
p2 = 0x60;
break;
case 1024:
p2 = 0x80;
break;
case 2048:
p2 = 0x00;
break;
default:
fprintf(stderr, "Invalid modulus length.\n");
return 2;
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, (u8) opt_key_num-1, p2);
apdu.cla = 0xF0;
apdu.lc = 4;
apdu.datalen = 4;
apdu.data = sbuf;
sbuf[0] = opt_exponent & 0xFF;
sbuf[1] = (opt_exponent >> 8) & 0xFF;
sbuf[2] = (opt_exponent >> 16) & 0xFF;
sbuf[3] = (opt_exponent >> 24) & 0xFF;
r = select_app_df();
if (r)
return 1;
if (verbose)
printf("Generating key...\n");
r = sc_transmit_apdu(card, &apdu);
if (r) {
fprintf(stderr, "APDU transmit failed: %s\n", sc_strerror(r));
if (r == SC_ERROR_TRANSMIT_FAILED)
fprintf(stderr, "Reader has timed out. It is still possible that the key generation has\n"
"succeeded.\n");
return 1;
}
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) {
printf("Key generation successful.\n");
return 0;
}
if (apdu.sw1 == 0x69 && apdu.sw2 == 0x82)
fprintf(stderr, "CHV1 not verified or invalid exponent value.\n");
else
fprintf(stderr, "Card returned SW1=%02X, SW2=%02X.\n", apdu.sw1, apdu.sw2);
return 1;
}
static int create_key_files(void)
{
sc_file_t *file;
int mod_lens[] = { 512, 768, 1024, 2048 };
int sizes[] = { 163, 243, 323, 643 };
int size = -1;
int r;
size_t i;
for (i = 0; i < sizeof(mod_lens) / sizeof(int); i++)
if (mod_lens[i] == opt_mod_length) {
size = sizes[i];
break;
}
if (size == -1) {
fprintf(stderr, "Invalid modulus length.\n");
return 1;
}
if (verbose)
printf("Creating key files for %d keys.\n", opt_key_count);
file = sc_file_new();
if (!file) {
fprintf(stderr, "out of memory.\n");
return 1;
}
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
file->id = 0x0012;
file->size = opt_key_count * size + 3;
sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1);
if (select_app_df()) {
sc_file_free(file);
return 1;
}
r = sc_create_file(card, file);
sc_file_free(file);
if (r) {
fprintf(stderr, "Unable to create private key file: %s\n", sc_strerror(r));
return 1;
}
file = sc_file_new();
if (!file) {
fprintf(stderr, "out of memory.\n");
return 1;
}
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
file->id = 0x1012;
file->size = opt_key_count * (size + 4) + 3;
sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1);
if (select_app_df()) {
sc_file_free(file);
return 1;
}
r = sc_create_file(card, file);
sc_file_free(file);
if (r) {
fprintf(stderr, "Unable to create public key file: %s\n", sc_strerror(r));
return 1;
}
if (verbose)
printf("Key files generated successfully.\n");
return 0;
}
static int read_rsa_privkey(RSA **rsa_out)
{
RSA *rsa = NULL;
BIO *in = NULL;
int r;
in = BIO_new(BIO_s_file());
if (opt_prkeyf == NULL) {
fprintf(stderr, "Private key file must be set.\n");
return 2;
}
r = BIO_read_filename(in, opt_prkeyf);
if (r <= 0) {
perror(opt_prkeyf);
return 2;
}
rsa = PEM_read_bio_RSAPrivateKey(in, NULL, NULL, NULL);
if (rsa == NULL) {
fprintf(stderr, "Unable to load private key.\n");
return 2;
}
BIO_free(in);
*rsa_out = rsa;
return 0;
}
static int encode_private_key(RSA *rsa, u8 *key, size_t *keysize)
{
u8 buf[1024], *p = buf;
u8 bnbuf[256];
int base = 0;
int r;
const BIGNUM *rsa_p, *rsa_q, *rsa_dmp1, *rsa_dmq1, *rsa_iqmp;
switch (RSA_bits(rsa)) {
case 512:
base = 32;
break;
case 768:
base = 48;
break;
case 1024:
base = 64;
break;
case 2048:
base = 128;
break;
}
if (base == 0) {
fprintf(stderr, "Key length invalid.\n");
return 2;
}
*p++ = (5 * base + 3) >> 8;
*p++ = (5 * base + 3) & 0xFF;
*p++ = opt_key_num;
RSA_get0_factors(rsa, &rsa_p, &rsa_q);
r = bn2cf(rsa_p, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
r = bn2cf(rsa_q, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
RSA_get0_crt_params(rsa, &rsa_dmp1, &rsa_dmq1, &rsa_iqmp);
r = bn2cf(rsa_iqmp, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
r = bn2cf(rsa_dmp1, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
r = bn2cf(rsa_dmq1, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
memcpy(key, buf, p - buf);
*keysize = p - buf;
return 0;
}
static int encode_public_key(RSA *rsa, u8 *key, size_t *keysize)
{
u8 buf[1024], *p = buf;
u8 bnbuf[256];
int base = 0;
int r;
const BIGNUM *rsa_n, *rsa_e;
switch (RSA_bits(rsa)) {
case 512:
base = 32;
break;
case 768:
base = 48;
break;
case 1024:
base = 64;
break;
case 2048:
base = 128;
break;
}
if (base == 0) {
fprintf(stderr, "Key length invalid.\n");
return 2;
}
*p++ = (5 * base + 7) >> 8;
*p++ = (5 * base + 7) & 0xFF;
*p++ = opt_key_num;
RSA_get0_key(rsa, &rsa_n, &rsa_e, NULL);
r = bn2cf(rsa_n, bnbuf);
if (r != 2*base) {
fprintf(stderr, "Invalid public key.\n");
return 2;
}
memcpy(p, bnbuf, 2*base);
p += 2*base;
memset(p, 0, base);
p += base;
memset(bnbuf, 0, 2*base);
memcpy(p, bnbuf, 2*base);
p += 2*base;
r = bn2cf(rsa_e, bnbuf);
memcpy(p, bnbuf, 4);
p += 4;
memcpy(key, buf, p - buf);
*keysize = p - buf;
return 0;
}
static int update_public_key(const u8 *key, size_t keysize)
{
int r, idx = 0;
sc_path_t path;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
idx = keysize * (opt_key_num-1);
r = sc_update_binary(card, idx, key, keysize, 0);
if (r < 0) {
fprintf(stderr, "Unable to write public key: %s\n", sc_strerror(r));
return 2;
}
return 0;
}
static int update_private_key(const u8 *key, size_t keysize)
{
int r, idx = 0;
sc_path_t path;
r = select_app_df();
if (r)
return 1;
sc_format_path("I0012", &path);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r));
return 2;
}
idx = keysize * (opt_key_num-1);
r = sc_update_binary(card, idx, key, keysize, 0);
if (r < 0) {
fprintf(stderr, "Unable to write private key: %s\n", sc_strerror(r));
return 2;
}
return 0;
}
static int store_key(void)
{
u8 prv[1024], pub[1024];
size_t prvsize, pubsize;
int r;
RSA *rsa;
r = read_rsa_privkey(&rsa);
if (r)
return r;
r = encode_private_key(rsa, prv, &prvsize);
if (r)
return r;
r = encode_public_key(rsa, pub, &pubsize);
if (r)
return r;
if (verbose)
printf("Storing private key...\n");
r = select_app_df();
if (r)
return r;
r = update_private_key(prv, prvsize);
if (r)
return r;
if (verbose)
printf("Storing public key...\n");
r = select_app_df();
if (r)
return r;
r = update_public_key(pub, pubsize);
if (r)
return r;
return 0;
}
static int create_pin_file(const sc_path_t *inpath, int chv, const char *key_id)
{
char prompt[40], *pin, *puk;
char buf[30], *p = buf;
sc_path_t file_id, path;
sc_file_t *file;
size_t len;
int r;
file_id = *inpath;
if (file_id.len < 2)
return -1;
if (chv == 1)
sc_format_path("I0000", &file_id);
else if (chv == 2)
sc_format_path("I0100", &file_id);
else
return -1;
r = sc_select_file(card, inpath, NULL);
if (r)
return -1;
r = sc_select_file(card, &file_id, NULL);
if (r == 0)
return 0;
sprintf(prompt, "Please enter CHV%d%s: ", chv, key_id);
pin = getpin(prompt);
if (pin == NULL)
return -1;
sprintf(prompt, "Please enter PUK for CHV%d%s: ", chv, key_id);
puk = getpin(prompt);
if (puk == NULL) {
free(pin);
return -1;
}
memset(p, 0xFF, 3);
p += 3;
memcpy(p, pin, 8);
p += 8;
*p++ = opt_pin_attempts;
*p++ = opt_pin_attempts;
memcpy(p, puk, 8);
p += 8;
*p++ = opt_puk_attempts;
*p++ = opt_puk_attempts;
len = p - buf;
free(pin);
free(puk);
file = sc_file_new();
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE);
if (inpath->len == 2 && inpath->value[0] == 0x3F &&
inpath->value[1] == 0x00)
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_AUT, 1);
else
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 2);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_AUT, 1);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_AUT, 1);
file->size = len;
file->id = (file_id.value[0] << 8) | file_id.value[1];
r = sc_create_file(card, file);
sc_file_free(file);
if (r) {
fprintf(stderr, "PIN file creation failed: %s\n", sc_strerror(r));
return r;
}
path = *inpath;
sc_append_path(&path, &file_id);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select created PIN file: %s\n", sc_strerror(r));
return r;
}
r = sc_update_binary(card, 0, (const u8 *) buf, len, 0);
if (r < 0) {
fprintf(stderr, "Unable to update created PIN file: %s\n", sc_strerror(r));
return r;
}
return 0;
}
static int create_pin(void)
{
sc_path_t path;
char buf[80];
if (opt_pin_num != 1 && opt_pin_num != 2) {
fprintf(stderr, "Invalid PIN number. Possible values: 1, 2.\n");
return 2;
}
strcpy(buf, "3F00");
if (opt_appdf != NULL)
strlcat(buf, opt_appdf, sizeof buf);
sc_format_path(buf, &path);
return create_pin_file(&path, opt_pin_num, "");
}
int main(int argc, char *argv[])
{
int err = 0, r, c, long_optind = 0;
int action_count = 0;
int do_read_key = 0;
int do_generate_key = 0;
int do_create_key_files = 0;
int do_list_keys = 0;
int do_store_key = 0;
int do_create_pin_file = 0;
sc_context_param_t ctx_param;
while (1) {
c = getopt_long(argc, argv, "P:Vslgc:Rk:r:p:u:e:m:vwa:", options, &long_optind);
if (c == -1)
break;
if (c == '?')
util_print_usage_and_die(app_name, options, option_help, NULL);
switch (c) {
case 'l':
do_list_keys = 1;
action_count++;
break;
case 'P':
do_create_pin_file = 1;
opt_pin_num = atoi(optarg);
action_count++;
break;
case 'R':
do_read_key = 1;
action_count++;
break;
case 'g':
do_generate_key = 1;
action_count++;
break;
case 'c':
do_create_key_files = 1;
opt_key_count = atoi(optarg);
action_count++;
break;
case 's':
do_store_key = 1;
action_count++;
break;
case 'k':
opt_key_num = atoi(optarg);
if (opt_key_num < 1 || opt_key_num > 15) {
fprintf(stderr, "Key number invalid.\n");
exit(2);
}
break;
case 'V':
opt_pin_num = 1;
break;
case 'e':
opt_exponent = atoi(optarg);
break;
case 'm':
opt_mod_length = atoi(optarg);
break;
case 'p':
opt_prkeyf = optarg;
break;
case 'u':
opt_pubkeyf = optarg;
break;
case 'r':
opt_reader = optarg;
break;
case 'v':
verbose++;
break;
case 'w':
opt_wait = 1;
break;
case 'a':
opt_appdf = optarg;
break;
}
}
if (action_count == 0)
util_print_usage_and_die(app_name, options, option_help, NULL);
memset(&ctx_param, 0, sizeof(ctx_param));
ctx_param.ver = 0;
ctx_param.app_name = app_name;
r = sc_context_create(&ctx, &ctx_param);
if (r) {
fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r));
return 1;
}
if (verbose > 1) {
ctx->debug = verbose;
sc_ctx_log_to_file(ctx, "stderr");
}
err = util_connect_card(ctx, &card, opt_reader, opt_wait, verbose);
printf("Using card driver: %s\n", card->driver->name);
if (do_create_pin_file) {
if ((err = create_pin()) != 0)
goto end;
action_count--;
}
if (do_create_key_files) {
if ((err = create_key_files()) != 0)
goto end;
action_count--;
}
if (do_generate_key) {
if ((err = generate_key()) != 0)
goto end;
action_count--;
}
if (do_store_key) {
if ((err = store_key()) != 0)
goto end;
action_count--;
}
if (do_list_keys) {
if ((err = list_keys()) != 0)
goto end;
action_count--;
}
if (do_read_key) {
if ((err = read_key()) != 0)
goto end;
action_count--;
}
if (pincode != NULL) {
memset(pincode, 0, 8);
free(pincode);
}
end:
if (card) {
sc_unlock(card);
sc_disconnect_card(card);
}
if (ctx)
sc_release_context(ctx);
return err;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_339_8 |
crossvul-cpp_data_bad_896_0 | #include "mongoose.h"
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_internal.h"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#ifndef CS_MONGOOSE_SRC_INTERNAL_H_
#define CS_MONGOOSE_SRC_INTERNAL_H_
/* Amalgamated: #include "common/mg_mem.h" */
#ifndef MBUF_REALLOC
#define MBUF_REALLOC MG_REALLOC
#endif
#ifndef MBUF_FREE
#define MBUF_FREE MG_FREE
#endif
#define MG_SET_PTRPTR(_ptr, _v) \
do { \
if (_ptr) *(_ptr) = _v; \
} while (0)
#ifndef MG_INTERNAL
#define MG_INTERNAL static
#endif
#ifdef PICOTCP
#define NO_LIBC
#define MG_DISABLE_PFS
#endif
/* Amalgamated: #include "common/cs_dbg.h" */
/* Amalgamated: #include "mg_http.h" */
/* Amalgamated: #include "mg_net.h" */
#ifndef MG_CTL_MSG_MESSAGE_SIZE
#define MG_CTL_MSG_MESSAGE_SIZE 8192
#endif
/* internals that need to be accessible in unit tests */
MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
int proto,
union socket_address *sa);
MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
int *proto, char *host, size_t host_len);
MG_INTERNAL void mg_call(struct mg_connection *nc,
mg_event_handler_t ev_handler, void *user_data, int ev,
void *ev_data);
void mg_forward(struct mg_connection *from, struct mg_connection *to);
MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c);
MG_INTERNAL void mg_remove_conn(struct mg_connection *c);
MG_INTERNAL struct mg_connection *mg_create_connection(
struct mg_mgr *mgr, mg_event_handler_t callback,
struct mg_add_sock_opts opts);
#ifdef _WIN32
/* Retur value is the same as for MultiByteToWideChar. */
int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len);
#endif
struct ctl_msg {
mg_event_handler_t callback;
char message[MG_CTL_MSG_MESSAGE_SIZE];
};
#if MG_ENABLE_MQTT
struct mg_mqtt_message;
#define MG_MQTT_ERROR_INCOMPLETE_MSG -1
#define MG_MQTT_ERROR_MALFORMED_MSG -2
MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm);
#endif
/* Forward declarations for testing. */
extern void *(*test_malloc)(size_t size);
extern void *(*test_calloc)(size_t count, size_t size);
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
#if MG_ENABLE_HTTP
struct mg_serve_http_opts;
MG_INTERNAL struct mg_http_proto_data *mg_http_create_proto_data(
struct mg_connection *c);
/*
* Reassemble the content of the buffer (buf, blen) which should be
* in the HTTP chunked encoding, by collapsing data chunks to the
* beginning of the buffer.
*
* If chunks get reassembled, modify hm->body to point to the reassembled
* body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK
* in nc->flags, delete reassembled body from the mbuf.
*
* Return reassembled body size.
*/
MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
struct http_message *hm, char *buf,
size_t blen);
#if MG_ENABLE_FILESYSTEM
MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
const struct mg_serve_http_opts *opts,
char **local_path,
struct mg_str *remainder);
MG_INTERNAL time_t mg_parse_date_string(const char *datetime);
MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st);
#endif
#if MG_ENABLE_HTTP_CGI
MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
const struct mg_str *path_info,
const struct http_message *hm,
const struct mg_serve_http_opts *opts);
struct mg_http_proto_data_cgi;
MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d);
#endif
#if MG_ENABLE_HTTP_SSI
MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
struct http_message *hm,
const char *path,
const struct mg_serve_http_opts *opts);
#endif
#if MG_ENABLE_HTTP_WEBDAV
MG_INTERNAL int mg_is_dav_request(const struct mg_str *s);
MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
cs_stat_t *stp, struct http_message *hm,
struct mg_serve_http_opts *opts);
MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path);
MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
struct http_message *hm);
MG_INTERNAL void mg_handle_move(struct mg_connection *c,
const struct mg_serve_http_opts *opts,
const char *path, struct http_message *hm);
MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
const struct mg_serve_http_opts *opts,
const char *path);
MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
struct http_message *hm);
#endif
#if MG_ENABLE_HTTP_WEBSOCKET
MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data));
MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
const struct mg_str *key,
struct http_message *);
#endif
#endif /* MG_ENABLE_HTTP */
MG_INTERNAL int mg_get_errno(void);
MG_INTERNAL void mg_close_conn(struct mg_connection *conn);
#if MG_ENABLE_SNTP
MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
struct mg_sntp_message *msg);
#endif
#endif /* CS_MONGOOSE_SRC_INTERNAL_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/mg_mem.h"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CS_COMMON_MG_MEM_H_
#define CS_COMMON_MG_MEM_H_
#ifdef __cplusplus
extern "C" {
#endif
#ifndef MG_MALLOC
#define MG_MALLOC malloc
#endif
#ifndef MG_CALLOC
#define MG_CALLOC calloc
#endif
#ifndef MG_REALLOC
#define MG_REALLOC realloc
#endif
#ifndef MG_FREE
#define MG_FREE free
#endif
#ifdef __cplusplus
}
#endif
#endif /* CS_COMMON_MG_MEM_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/cs_base64.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef EXCLUDE_COMMON
/* Amalgamated: #include "common/cs_base64.h" */
#include <string.h>
/* Amalgamated: #include "common/cs_dbg.h" */
/* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */
#define NUM_UPPERCASES ('Z' - 'A' + 1)
#define NUM_LETTERS (NUM_UPPERCASES * 2)
#define NUM_DIGITS ('9' - '0' + 1)
/*
* Emit a base64 code char.
*
* Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps
*/
static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) {
if (v < NUM_UPPERCASES) {
ctx->b64_putc(v + 'A', ctx->user_data);
} else if (v < (NUM_LETTERS)) {
ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data);
} else if (v < (NUM_LETTERS + NUM_DIGITS)) {
ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data);
} else {
ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/',
ctx->user_data);
}
}
static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) {
int a, b, c;
a = ctx->chunk[0];
b = ctx->chunk[1];
c = ctx->chunk[2];
cs_base64_emit_code(ctx, a >> 2);
cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4));
if (ctx->chunk_size > 1) {
cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6));
}
if (ctx->chunk_size > 2) {
cs_base64_emit_code(ctx, c & 63);
}
}
void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc,
void *user_data) {
ctx->chunk_size = 0;
ctx->b64_putc = b64_putc;
ctx->user_data = user_data;
}
void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) {
const unsigned char *src = (const unsigned char *) str;
size_t i;
for (i = 0; i < len; i++) {
ctx->chunk[ctx->chunk_size++] = src[i];
if (ctx->chunk_size == 3) {
cs_base64_emit_chunk(ctx);
ctx->chunk_size = 0;
}
}
}
void cs_base64_finish(struct cs_base64_ctx *ctx) {
if (ctx->chunk_size > 0) {
int i;
memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size);
cs_base64_emit_chunk(ctx);
for (i = 0; i < (3 - ctx->chunk_size); i++) {
ctx->b64_putc('=', ctx->user_data);
}
}
}
#define BASE64_ENCODE_BODY \
static const char *b64 = \
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \
int i, j, a, b, c; \
\
for (i = j = 0; i < src_len; i += 3) { \
a = src[i]; \
b = i + 1 >= src_len ? 0 : src[i + 1]; \
c = i + 2 >= src_len ? 0 : src[i + 2]; \
\
BASE64_OUT(b64[a >> 2]); \
BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \
if (i + 1 < src_len) { \
BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \
} \
if (i + 2 < src_len) { \
BASE64_OUT(b64[c & 63]); \
} \
} \
\
while (j % 4 != 0) { \
BASE64_OUT('='); \
} \
BASE64_FLUSH()
#define BASE64_OUT(ch) \
do { \
dst[j++] = (ch); \
} while (0)
#define BASE64_FLUSH() \
do { \
dst[j++] = '\0'; \
} while (0)
void cs_base64_encode(const unsigned char *src, int src_len, char *dst) {
BASE64_ENCODE_BODY;
}
#undef BASE64_OUT
#undef BASE64_FLUSH
#if CS_ENABLE_STDIO
#define BASE64_OUT(ch) \
do { \
fprintf(f, "%c", (ch)); \
j++; \
} while (0)
#define BASE64_FLUSH()
void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) {
BASE64_ENCODE_BODY;
}
#undef BASE64_OUT
#undef BASE64_FLUSH
#endif /* CS_ENABLE_STDIO */
/* Convert one byte of encoded base64 input stream to 6-bit chunk */
static unsigned char from_b64(unsigned char ch) {
/* Inverse lookup map */
static const unsigned char tab[128] = {
255, 255, 255, 255,
255, 255, 255, 255, /* 0 */
255, 255, 255, 255,
255, 255, 255, 255, /* 8 */
255, 255, 255, 255,
255, 255, 255, 255, /* 16 */
255, 255, 255, 255,
255, 255, 255, 255, /* 24 */
255, 255, 255, 255,
255, 255, 255, 255, /* 32 */
255, 255, 255, 62,
255, 255, 255, 63, /* 40 */
52, 53, 54, 55,
56, 57, 58, 59, /* 48 */
60, 61, 255, 255,
255, 200, 255, 255, /* 56 '=' is 200, on index 61 */
255, 0, 1, 2,
3, 4, 5, 6, /* 64 */
7, 8, 9, 10,
11, 12, 13, 14, /* 72 */
15, 16, 17, 18,
19, 20, 21, 22, /* 80 */
23, 24, 25, 255,
255, 255, 255, 255, /* 88 */
255, 26, 27, 28,
29, 30, 31, 32, /* 96 */
33, 34, 35, 36,
37, 38, 39, 40, /* 104 */
41, 42, 43, 44,
45, 46, 47, 48, /* 112 */
49, 50, 51, 255,
255, 255, 255, 255, /* 120 */
};
return tab[ch & 127];
}
int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len) {
unsigned char a, b, c, d;
int orig_len = len;
char *orig_dst = dst;
while (len >= 4 && (a = from_b64(s[0])) != 255 &&
(b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 &&
(d = from_b64(s[3])) != 255) {
s += 4;
len -= 4;
if (a == 200 || b == 200) break; /* '=' can't be there */
*dst++ = a << 2 | b >> 4;
if (c == 200) break;
*dst++ = b << 4 | c >> 2;
if (d == 200) break;
*dst++ = c << 6 | d;
}
*dst = 0;
if (dec_len != NULL) *dec_len = (dst - orig_dst);
return orig_len - len;
}
#endif /* EXCLUDE_COMMON */
#ifdef MG_MODULE_LINES
#line 1 "common/cs_dbg.h"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CS_COMMON_CS_DBG_H_
#define CS_COMMON_CS_DBG_H_
/* Amalgamated: #include "common/platform.h" */
#if CS_ENABLE_STDIO
#include <stdio.h>
#endif
#ifndef CS_ENABLE_DEBUG
#define CS_ENABLE_DEBUG 0
#endif
#ifndef CS_LOG_PREFIX_LEN
#define CS_LOG_PREFIX_LEN 24
#endif
#ifndef CS_LOG_ENABLE_TS_DIFF
#define CS_LOG_ENABLE_TS_DIFF 0
#endif
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*
* Log level; `LL_INFO` is the default. Use `cs_log_set_level()` to change it.
*/
enum cs_log_level {
LL_NONE = -1,
LL_ERROR = 0,
LL_WARN = 1,
LL_INFO = 2,
LL_DEBUG = 3,
LL_VERBOSE_DEBUG = 4,
_LL_MIN = -2,
_LL_MAX = 5,
};
/*
* Set max log level to print; messages with the level above the given one will
* not be printed.
*/
void cs_log_set_level(enum cs_log_level level);
/*
* A comma-separated set of prefix=level.
* prefix is matched against the log prefix exactly as printed, including line
* number, but partial match is ok. Check stops on first matching entry.
* If nothing matches, default level is used.
*
* Examples:
* main.c:=4 - everything from main C at verbose debug level.
* mongoose.c=1,mjs.c=1,=4 - everything at verbose debug except mg_* and mjs_*
*
*/
void cs_log_set_file_level(const char *file_level);
/*
* Helper function which prints message prefix with the given `level`.
* If message should be printed (according to the current log level
* and filter), prints the prefix and returns 1, otherwise returns 0.
*
* Clients should typically just use `LOG()` macro.
*/
int cs_log_print_prefix(enum cs_log_level level, const char *fname, int line);
extern enum cs_log_level cs_log_level;
#if CS_ENABLE_STDIO
/*
* Set file to write logs into. If `NULL`, logs go to `stderr`.
*/
void cs_log_set_file(FILE *file);
/*
* Prints log to the current log file, appends "\n" in the end and flushes the
* stream.
*/
void cs_log_printf(const char *fmt, ...) PRINTF_LIKE(1, 2);
#if CS_ENABLE_STDIO
/*
* Format and print message `x` with the given level `l`. Example:
*
* ```c
* LOG(LL_INFO, ("my info message: %d", 123));
* LOG(LL_DEBUG, ("my debug message: %d", 123));
* ```
*/
#define LOG(l, x) \
do { \
if (cs_log_print_prefix(l, __FILE__, __LINE__)) { \
cs_log_printf x; \
} \
} while (0)
#else
#define LOG(l, x) ((void) l)
#endif
#ifndef CS_NDEBUG
/*
* Shortcut for `LOG(LL_VERBOSE_DEBUG, (...))`
*/
#define DBG(x) LOG(LL_VERBOSE_DEBUG, x)
#else /* NDEBUG */
#define DBG(x)
#endif
#else /* CS_ENABLE_STDIO */
#define LOG(l, x)
#define DBG(x)
#endif
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_COMMON_CS_DBG_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/cs_dbg.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Amalgamated: #include "common/cs_dbg.h" */
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
/* Amalgamated: #include "common/cs_time.h" */
/* Amalgamated: #include "common/str_util.h" */
enum cs_log_level cs_log_level WEAK =
#if CS_ENABLE_DEBUG
LL_VERBOSE_DEBUG;
#else
LL_ERROR;
#endif
#if CS_ENABLE_STDIO
static char *s_file_level = NULL;
void cs_log_set_file_level(const char *file_level) WEAK;
FILE *cs_log_file WEAK = NULL;
#if CS_LOG_ENABLE_TS_DIFF
double cs_log_ts WEAK;
#endif
enum cs_log_level cs_log_cur_msg_level WEAK = LL_NONE;
void cs_log_set_file_level(const char *file_level) {
char *fl = s_file_level;
if (file_level != NULL) {
s_file_level = strdup(file_level);
} else {
s_file_level = NULL;
}
free(fl);
}
int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) WEAK;
int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) {
char prefix[CS_LOG_PREFIX_LEN], *q;
const char *p;
size_t fl = 0, ll = 0, pl = 0;
if (level > cs_log_level && s_file_level == NULL) return 0;
p = file + strlen(file);
while (p != file) {
const char c = *(p - 1);
if (c == '/' || c == '\\') break;
p--;
fl++;
}
ll = (ln < 10000 ? (ln < 1000 ? (ln < 100 ? (ln < 10 ? 1 : 2) : 3) : 4) : 5);
if (fl > (sizeof(prefix) - ll - 2)) fl = (sizeof(prefix) - ll - 2);
pl = fl + 1 + ll;
memcpy(prefix, p, fl);
q = prefix + pl;
memset(q, ' ', sizeof(prefix) - pl);
do {
*(--q) = '0' + (ln % 10);
ln /= 10;
} while (ln > 0);
*(--q) = ':';
if (s_file_level != NULL) {
enum cs_log_level pll = cs_log_level;
struct mg_str fl = mg_mk_str(s_file_level), ps = MG_MK_STR_N(prefix, pl);
struct mg_str k, v;
while ((fl = mg_next_comma_list_entry_n(fl, &k, &v)).p != NULL) {
bool yes = !(!mg_str_starts_with(ps, k) || v.len == 0);
if (!yes) continue;
pll = (enum cs_log_level)(*v.p - '0');
break;
}
if (level > pll) return 0;
}
if (cs_log_file == NULL) cs_log_file = stderr;
cs_log_cur_msg_level = level;
fwrite(prefix, 1, sizeof(prefix), cs_log_file);
#if CS_LOG_ENABLE_TS_DIFF
{
double now = cs_time();
fprintf(cs_log_file, "%7u ", (unsigned int) ((now - cs_log_ts) * 1000000));
cs_log_ts = now;
}
#endif
return 1;
}
void cs_log_printf(const char *fmt, ...) WEAK;
void cs_log_printf(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(cs_log_file, fmt, ap);
va_end(ap);
fputc('\n', cs_log_file);
fflush(cs_log_file);
cs_log_cur_msg_level = LL_NONE;
}
void cs_log_set_file(FILE *file) WEAK;
void cs_log_set_file(FILE *file) {
cs_log_file = file;
}
#else
void cs_log_set_file_level(const char *file_level) {
(void) file_level;
}
#endif /* CS_ENABLE_STDIO */
void cs_log_set_level(enum cs_log_level level) WEAK;
void cs_log_set_level(enum cs_log_level level) {
cs_log_level = level;
#if CS_LOG_ENABLE_TS_DIFF && CS_ENABLE_STDIO
cs_log_ts = cs_time();
#endif
}
#ifdef MG_MODULE_LINES
#line 1 "common/cs_dirent.h"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CS_COMMON_CS_DIRENT_H_
#define CS_COMMON_CS_DIRENT_H_
#include <limits.h>
/* Amalgamated: #include "common/platform.h" */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifdef CS_DEFINE_DIRENT
typedef struct { int dummy; } DIR;
struct dirent {
int d_ino;
#ifdef _WIN32
char d_name[MAX_PATH];
#else
/* TODO(rojer): Use PATH_MAX but make sure it's sane on every platform */
char d_name[256];
#endif
};
DIR *opendir(const char *dir_name);
int closedir(DIR *dir);
struct dirent *readdir(DIR *dir);
#endif /* CS_DEFINE_DIRENT */
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_COMMON_CS_DIRENT_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/cs_dirent.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef EXCLUDE_COMMON
/* Amalgamated: #include "common/mg_mem.h" */
/* Amalgamated: #include "common/cs_dirent.h" */
/*
* This file contains POSIX opendir/closedir/readdir API implementation
* for systems which do not natively support it (e.g. Windows).
*/
#ifdef _WIN32
struct win32_dir {
DIR d;
HANDLE handle;
WIN32_FIND_DATAW info;
struct dirent result;
};
DIR *opendir(const char *name) {
struct win32_dir *dir = NULL;
wchar_t wpath[MAX_PATH];
DWORD attrs;
if (name == NULL) {
SetLastError(ERROR_BAD_ARGUMENTS);
} else if ((dir = (struct win32_dir *) MG_MALLOC(sizeof(*dir))) == NULL) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
} else {
to_wchar(name, wpath, ARRAY_SIZE(wpath));
attrs = GetFileAttributesW(wpath);
if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
(void) wcscat(wpath, L"\\*");
dir->handle = FindFirstFileW(wpath, &dir->info);
dir->result.d_name[0] = '\0';
} else {
MG_FREE(dir);
dir = NULL;
}
}
return (DIR *) dir;
}
int closedir(DIR *d) {
struct win32_dir *dir = (struct win32_dir *) d;
int result = 0;
if (dir != NULL) {
if (dir->handle != INVALID_HANDLE_VALUE)
result = FindClose(dir->handle) ? 0 : -1;
MG_FREE(dir);
} else {
result = -1;
SetLastError(ERROR_BAD_ARGUMENTS);
}
return result;
}
struct dirent *readdir(DIR *d) {
struct win32_dir *dir = (struct win32_dir *) d;
struct dirent *result = NULL;
if (dir) {
memset(&dir->result, 0, sizeof(dir->result));
if (dir->handle != INVALID_HANDLE_VALUE) {
result = &dir->result;
(void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
result->d_name, sizeof(result->d_name), NULL,
NULL);
if (!FindNextFileW(dir->handle, &dir->info)) {
(void) FindClose(dir->handle);
dir->handle = INVALID_HANDLE_VALUE;
}
} else {
SetLastError(ERROR_FILE_NOT_FOUND);
}
} else {
SetLastError(ERROR_BAD_ARGUMENTS);
}
return result;
}
#endif
#endif /* EXCLUDE_COMMON */
/* ISO C requires a translation unit to contain at least one declaration */
typedef int cs_dirent_dummy;
#ifdef MG_MODULE_LINES
#line 1 "common/cs_time.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Amalgamated: #include "common/cs_time.h" */
#ifndef _WIN32
#include <stddef.h>
/*
* There is no sys/time.h on ARMCC.
*/
#if !(defined(__ARMCC_VERSION) || defined(__ICCARM__)) && \
!defined(__TI_COMPILER_VERSION__) && \
(!defined(CS_PLATFORM) || CS_PLATFORM != CS_P_NXP_LPC)
#include <sys/time.h>
#endif
#else
#include <windows.h>
#endif
double cs_time(void) WEAK;
double cs_time(void) {
double now;
#ifndef _WIN32
struct timeval tv;
if (gettimeofday(&tv, NULL /* tz */) != 0) return 0;
now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0);
#else
SYSTEMTIME sysnow;
FILETIME ftime;
GetLocalTime(&sysnow);
SystemTimeToFileTime(&sysnow, &ftime);
/*
* 1. VC 6.0 doesn't support conversion uint64 -> double, so, using int64
* This should not cause a problems in this (21th) century
* 2. Windows FILETIME is a number of 100-nanosecond intervals since January
* 1, 1601 while time_t is a number of _seconds_ since January 1, 1970 UTC,
* thus, we need to convert to seconds and adjust amount (subtract 11644473600
* seconds)
*/
now = (double) (((int64_t) ftime.dwLowDateTime +
((int64_t) ftime.dwHighDateTime << 32)) /
10000000.0) -
11644473600;
#endif /* _WIN32 */
return now;
}
double cs_timegm(const struct tm *tm) {
/* Month-to-day offset for non-leap-years. */
static const int month_day[12] = {0, 31, 59, 90, 120, 151,
181, 212, 243, 273, 304, 334};
/* Most of the calculation is easy; leap years are the main difficulty. */
int month = tm->tm_mon % 12;
int year = tm->tm_year + tm->tm_mon / 12;
int year_for_leap;
int64_t rt;
if (month < 0) { /* Negative values % 12 are still negative. */
month += 12;
--year;
}
/* This is the number of Februaries since 1900. */
year_for_leap = (month > 1) ? year + 1 : year;
rt =
tm->tm_sec /* Seconds */
+
60 *
(tm->tm_min /* Minute = 60 seconds */
+
60 * (tm->tm_hour /* Hour = 60 minutes */
+
24 * (month_day[month] + tm->tm_mday - 1 /* Day = 24 hours */
+ 365 * (year - 70) /* Year = 365 days */
+ (year_for_leap - 69) / 4 /* Every 4 years is leap... */
- (year_for_leap - 1) / 100 /* Except centuries... */
+ (year_for_leap + 299) / 400))); /* Except 400s. */
return rt < 0 ? -1 : (double) rt;
}
#ifdef MG_MODULE_LINES
#line 1 "common/cs_endian.h"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CS_COMMON_CS_ENDIAN_H_
#define CS_COMMON_CS_ENDIAN_H_
#ifdef __cplusplus
extern "C" {
#endif
/*
* clang with std=-c99 uses __LITTLE_ENDIAN, by default
* while for ex, RTOS gcc - LITTLE_ENDIAN, by default
* it depends on __USE_BSD, but let's have everything
*/
#if !defined(BYTE_ORDER) && defined(__BYTE_ORDER)
#define BYTE_ORDER __BYTE_ORDER
#ifndef LITTLE_ENDIAN
#define LITTLE_ENDIAN __LITTLE_ENDIAN
#endif /* LITTLE_ENDIAN */
#ifndef BIG_ENDIAN
#define BIG_ENDIAN __LITTLE_ENDIAN
#endif /* BIG_ENDIAN */
#endif /* BYTE_ORDER */
#ifdef __cplusplus
}
#endif
#endif /* CS_COMMON_CS_ENDIAN_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/cs_md5.c"
#endif
/*
* This code implements the MD5 message-digest algorithm.
* The algorithm is due to Ron Rivest. This code was
* written by Colin Plumb in 1993, no copyright is claimed.
* This code is in the public domain; do with it what you wish.
*
* Equivalent code is available from RSA Data Security, Inc.
* This code has been tested against that, and is equivalent,
* except that you don't need to include two pages of legalese
* with every copy.
*
* To compute the message digest of a chunk of bytes, declare an
* MD5Context structure, pass it to MD5Init, call MD5Update as
* needed on buffers full of bytes, and then call MD5Final, which
* will fill a supplied 16-byte array with the digest.
*/
/* Amalgamated: #include "common/cs_md5.h" */
/* Amalgamated: #include "common/str_util.h" */
#if !defined(EXCLUDE_COMMON)
#if !CS_DISABLE_MD5
/* Amalgamated: #include "common/cs_endian.h" */
static void byteReverse(unsigned char *buf, unsigned longs) {
/* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */
#if BYTE_ORDER == BIG_ENDIAN
do {
uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 |
((unsigned) buf[1] << 8 | buf[0]);
*(uint32_t *) buf = t;
buf += 4;
} while (--longs);
#else
(void) buf;
(void) longs;
#endif
}
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))
#define MD5STEP(f, w, x, y, z, data, s) \
(w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
/*
* Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
* initialization constants.
*/
void cs_md5_init(cs_md5_ctx *ctx) {
ctx->buf[0] = 0x67452301;
ctx->buf[1] = 0xefcdab89;
ctx->buf[2] = 0x98badcfe;
ctx->buf[3] = 0x10325476;
ctx->bits[0] = 0;
ctx->bits[1] = 0;
}
static void cs_md5_transform(uint32_t buf[4], uint32_t const in[16]) {
register uint32_t a, b, c, d;
a = buf[0];
b = buf[1];
c = buf[2];
d = buf[3];
MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
buf[0] += a;
buf[1] += b;
buf[2] += c;
buf[3] += d;
}
void cs_md5_update(cs_md5_ctx *ctx, const unsigned char *buf, size_t len) {
uint32_t t;
t = ctx->bits[0];
if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
ctx->bits[1] += (uint32_t) len >> 29;
t = (t >> 3) & 0x3f;
if (t) {
unsigned char *p = (unsigned char *) ctx->in + t;
t = 64 - t;
if (len < t) {
memcpy(p, buf, len);
return;
}
memcpy(p, buf, t);
byteReverse(ctx->in, 16);
cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
buf += t;
len -= t;
}
while (len >= 64) {
memcpy(ctx->in, buf, 64);
byteReverse(ctx->in, 16);
cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
buf += 64;
len -= 64;
}
memcpy(ctx->in, buf, len);
}
void cs_md5_final(unsigned char digest[16], cs_md5_ctx *ctx) {
unsigned count;
unsigned char *p;
uint32_t *a;
count = (ctx->bits[0] >> 3) & 0x3F;
p = ctx->in + count;
*p++ = 0x80;
count = 64 - 1 - count;
if (count < 8) {
memset(p, 0, count);
byteReverse(ctx->in, 16);
cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
memset(ctx->in, 0, 56);
} else {
memset(p, 0, count - 8);
}
byteReverse(ctx->in, 14);
a = (uint32_t *) ctx->in;
a[14] = ctx->bits[0];
a[15] = ctx->bits[1];
cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
byteReverse((unsigned char *) ctx->buf, 4);
memcpy(digest, ctx->buf, 16);
memset((char *) ctx, 0, sizeof(*ctx));
}
#endif /* CS_DISABLE_MD5 */
#endif /* EXCLUDE_COMMON */
#ifdef MG_MODULE_LINES
#line 1 "common/cs_sha1.c"
#endif
/* Copyright(c) By Steve Reid <steve@edmweb.com> */
/* 100% Public Domain */
/* Amalgamated: #include "common/cs_sha1.h" */
#if !CS_DISABLE_SHA1 && !defined(EXCLUDE_COMMON)
/* Amalgamated: #include "common/cs_endian.h" */
#define SHA1HANDSOFF
#if defined(__sun)
/* Amalgamated: #include "common/solarisfixes.h" */
#endif
union char64long16 {
unsigned char c[64];
uint32_t l[16];
};
#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
static uint32_t blk0(union char64long16 *block, int i) {
/* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
#if BYTE_ORDER == LITTLE_ENDIAN
block->l[i] =
(rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF);
#endif
return block->l[i];
}
/* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
#undef blk
#undef R0
#undef R1
#undef R2
#undef R3
#undef R4
#define blk(i) \
(block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
block->l[(i + 2) & 15] ^ block->l[i & 15], \
1))
#define R0(v, w, x, y, z, i) \
z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
w = rol(w, 30);
#define R1(v, w, x, y, z, i) \
z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
w = rol(w, 30);
#define R2(v, w, x, y, z, i) \
z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
w = rol(w, 30);
#define R3(v, w, x, y, z, i) \
z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
w = rol(w, 30);
#define R4(v, w, x, y, z, i) \
z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
w = rol(w, 30);
void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) {
uint32_t a, b, c, d, e;
union char64long16 block[1];
memcpy(block, buffer, 64);
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
R0(a, b, c, d, e, 0);
R0(e, a, b, c, d, 1);
R0(d, e, a, b, c, 2);
R0(c, d, e, a, b, 3);
R0(b, c, d, e, a, 4);
R0(a, b, c, d, e, 5);
R0(e, a, b, c, d, 6);
R0(d, e, a, b, c, 7);
R0(c, d, e, a, b, 8);
R0(b, c, d, e, a, 9);
R0(a, b, c, d, e, 10);
R0(e, a, b, c, d, 11);
R0(d, e, a, b, c, 12);
R0(c, d, e, a, b, 13);
R0(b, c, d, e, a, 14);
R0(a, b, c, d, e, 15);
R1(e, a, b, c, d, 16);
R1(d, e, a, b, c, 17);
R1(c, d, e, a, b, 18);
R1(b, c, d, e, a, 19);
R2(a, b, c, d, e, 20);
R2(e, a, b, c, d, 21);
R2(d, e, a, b, c, 22);
R2(c, d, e, a, b, 23);
R2(b, c, d, e, a, 24);
R2(a, b, c, d, e, 25);
R2(e, a, b, c, d, 26);
R2(d, e, a, b, c, 27);
R2(c, d, e, a, b, 28);
R2(b, c, d, e, a, 29);
R2(a, b, c, d, e, 30);
R2(e, a, b, c, d, 31);
R2(d, e, a, b, c, 32);
R2(c, d, e, a, b, 33);
R2(b, c, d, e, a, 34);
R2(a, b, c, d, e, 35);
R2(e, a, b, c, d, 36);
R2(d, e, a, b, c, 37);
R2(c, d, e, a, b, 38);
R2(b, c, d, e, a, 39);
R3(a, b, c, d, e, 40);
R3(e, a, b, c, d, 41);
R3(d, e, a, b, c, 42);
R3(c, d, e, a, b, 43);
R3(b, c, d, e, a, 44);
R3(a, b, c, d, e, 45);
R3(e, a, b, c, d, 46);
R3(d, e, a, b, c, 47);
R3(c, d, e, a, b, 48);
R3(b, c, d, e, a, 49);
R3(a, b, c, d, e, 50);
R3(e, a, b, c, d, 51);
R3(d, e, a, b, c, 52);
R3(c, d, e, a, b, 53);
R3(b, c, d, e, a, 54);
R3(a, b, c, d, e, 55);
R3(e, a, b, c, d, 56);
R3(d, e, a, b, c, 57);
R3(c, d, e, a, b, 58);
R3(b, c, d, e, a, 59);
R4(a, b, c, d, e, 60);
R4(e, a, b, c, d, 61);
R4(d, e, a, b, c, 62);
R4(c, d, e, a, b, 63);
R4(b, c, d, e, a, 64);
R4(a, b, c, d, e, 65);
R4(e, a, b, c, d, 66);
R4(d, e, a, b, c, 67);
R4(c, d, e, a, b, 68);
R4(b, c, d, e, a, 69);
R4(a, b, c, d, e, 70);
R4(e, a, b, c, d, 71);
R4(d, e, a, b, c, 72);
R4(c, d, e, a, b, 73);
R4(b, c, d, e, a, 74);
R4(a, b, c, d, e, 75);
R4(e, a, b, c, d, 76);
R4(d, e, a, b, c, 77);
R4(c, d, e, a, b, 78);
R4(b, c, d, e, a, 79);
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
/* Erase working structures. The order of operations is important,
* used to ensure that compiler doesn't optimize those out. */
memset(block, 0, sizeof(block));
a = b = c = d = e = 0;
(void) a;
(void) b;
(void) c;
(void) d;
(void) e;
}
void cs_sha1_init(cs_sha1_ctx *context) {
context->state[0] = 0x67452301;
context->state[1] = 0xEFCDAB89;
context->state[2] = 0x98BADCFE;
context->state[3] = 0x10325476;
context->state[4] = 0xC3D2E1F0;
context->count[0] = context->count[1] = 0;
}
void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data,
uint32_t len) {
uint32_t i, j;
j = context->count[0];
if ((context->count[0] += len << 3) < j) context->count[1]++;
context->count[1] += (len >> 29);
j = (j >> 3) & 63;
if ((j + len) > 63) {
memcpy(&context->buffer[j], data, (i = 64 - j));
cs_sha1_transform(context->state, context->buffer);
for (; i + 63 < len; i += 64) {
cs_sha1_transform(context->state, &data[i]);
}
j = 0;
} else
i = 0;
memcpy(&context->buffer[j], &data[i], len - i);
}
void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) {
unsigned i;
unsigned char finalcount[8], c;
for (i = 0; i < 8; i++) {
finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
((3 - (i & 3)) * 8)) &
255);
}
c = 0200;
cs_sha1_update(context, &c, 1);
while ((context->count[0] & 504) != 448) {
c = 0000;
cs_sha1_update(context, &c, 1);
}
cs_sha1_update(context, finalcount, 8);
for (i = 0; i < 20; i++) {
digest[i] =
(unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
}
memset(context, '\0', sizeof(*context));
memset(&finalcount, '\0', sizeof(finalcount));
}
void cs_hmac_sha1(const unsigned char *key, size_t keylen,
const unsigned char *data, size_t datalen,
unsigned char out[20]) {
cs_sha1_ctx ctx;
unsigned char buf1[64], buf2[64], tmp_key[20], i;
if (keylen > sizeof(buf1)) {
cs_sha1_init(&ctx);
cs_sha1_update(&ctx, key, keylen);
cs_sha1_final(tmp_key, &ctx);
key = tmp_key;
keylen = sizeof(tmp_key);
}
memset(buf1, 0, sizeof(buf1));
memset(buf2, 0, sizeof(buf2));
memcpy(buf1, key, keylen);
memcpy(buf2, key, keylen);
for (i = 0; i < sizeof(buf1); i++) {
buf1[i] ^= 0x36;
buf2[i] ^= 0x5c;
}
cs_sha1_init(&ctx);
cs_sha1_update(&ctx, buf1, sizeof(buf1));
cs_sha1_update(&ctx, data, datalen);
cs_sha1_final(out, &ctx);
cs_sha1_init(&ctx);
cs_sha1_update(&ctx, buf2, sizeof(buf2));
cs_sha1_update(&ctx, out, 20);
cs_sha1_final(out, &ctx);
}
#endif /* EXCLUDE_COMMON */
#ifdef MG_MODULE_LINES
#line 1 "common/mbuf.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef EXCLUDE_COMMON
#include <assert.h>
#include <string.h>
/* Amalgamated: #include "common/mbuf.h" */
#ifndef MBUF_REALLOC
#define MBUF_REALLOC realloc
#endif
#ifndef MBUF_FREE
#define MBUF_FREE free
#endif
void mbuf_init(struct mbuf *mbuf, size_t initial_size) WEAK;
void mbuf_init(struct mbuf *mbuf, size_t initial_size) {
mbuf->len = mbuf->size = 0;
mbuf->buf = NULL;
mbuf_resize(mbuf, initial_size);
}
void mbuf_free(struct mbuf *mbuf) WEAK;
void mbuf_free(struct mbuf *mbuf) {
if (mbuf->buf != NULL) {
MBUF_FREE(mbuf->buf);
mbuf_init(mbuf, 0);
}
}
void mbuf_resize(struct mbuf *a, size_t new_size) WEAK;
void mbuf_resize(struct mbuf *a, size_t new_size) {
if (new_size > a->size || (new_size < a->size && new_size >= a->len)) {
char *buf = (char *) MBUF_REALLOC(a->buf, new_size);
/*
* In case realloc fails, there's not much we can do, except keep things as
* they are. Note that NULL is a valid return value from realloc when
* size == 0, but that is covered too.
*/
if (buf == NULL && new_size != 0) return;
a->buf = buf;
a->size = new_size;
}
}
void mbuf_trim(struct mbuf *mbuf) WEAK;
void mbuf_trim(struct mbuf *mbuf) {
mbuf_resize(mbuf, mbuf->len);
}
size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t) WEAK;
size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) {
char *p = NULL;
assert(a != NULL);
assert(a->len <= a->size);
assert(off <= a->len);
/* check overflow */
if (~(size_t) 0 - (size_t) a->buf < len) return 0;
if (a->len + len <= a->size) {
memmove(a->buf + off + len, a->buf + off, a->len - off);
if (buf != NULL) {
memcpy(a->buf + off, buf, len);
}
a->len += len;
} else {
size_t min_size = (a->len + len);
size_t new_size = (size_t)(min_size * MBUF_SIZE_MULTIPLIER);
if (new_size - min_size > MBUF_SIZE_MAX_HEADROOM) {
new_size = min_size + MBUF_SIZE_MAX_HEADROOM;
}
p = (char *) MBUF_REALLOC(a->buf, new_size);
if (p == NULL && new_size != min_size) {
new_size = min_size;
p = (char *) MBUF_REALLOC(a->buf, new_size);
}
if (p != NULL) {
a->buf = p;
if (off != a->len) {
memmove(a->buf + off + len, a->buf + off, a->len - off);
}
if (buf != NULL) memcpy(a->buf + off, buf, len);
a->len += len;
a->size = new_size;
} else {
len = 0;
}
}
return len;
}
size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) WEAK;
size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) {
return mbuf_insert(a, a->len, buf, len);
}
size_t mbuf_append_and_free(struct mbuf *a, void *buf, size_t len) WEAK;
size_t mbuf_append_and_free(struct mbuf *a, void *data, size_t len) {
size_t ret;
/* Optimization: if the buffer is currently empty,
* take over the user-provided buffer. */
if (a->len == 0) {
if (a->buf != NULL) free(a->buf);
a->buf = (char *) data;
a->len = a->size = len;
return len;
}
ret = mbuf_insert(a, a->len, data, len);
free(data);
return ret;
}
void mbuf_remove(struct mbuf *mb, size_t n) WEAK;
void mbuf_remove(struct mbuf *mb, size_t n) {
if (n > 0 && n <= mb->len) {
memmove(mb->buf, mb->buf + n, mb->len - n);
mb->len -= n;
}
}
void mbuf_clear(struct mbuf *mb) WEAK;
void mbuf_clear(struct mbuf *mb) {
mb->len = 0;
}
void mbuf_move(struct mbuf *from, struct mbuf *to) WEAK;
void mbuf_move(struct mbuf *from, struct mbuf *to) {
memcpy(to, from, sizeof(*to));
memset(from, 0, sizeof(*from));
}
#endif /* EXCLUDE_COMMON */
#ifdef MG_MODULE_LINES
#line 1 "common/mg_str.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Amalgamated: #include "common/mg_mem.h" */
/* Amalgamated: #include "common/mg_str.h" */
/* Amalgamated: #include "common/platform.h" */
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK;
struct mg_str mg_mk_str(const char *s) WEAK;
struct mg_str mg_mk_str(const char *s) {
struct mg_str ret = {s, 0};
if (s != NULL) ret.len = strlen(s);
return ret;
}
struct mg_str mg_mk_str_n(const char *s, size_t len) WEAK;
struct mg_str mg_mk_str_n(const char *s, size_t len) {
struct mg_str ret = {s, len};
return ret;
}
int mg_vcmp(const struct mg_str *str1, const char *str2) WEAK;
int mg_vcmp(const struct mg_str *str1, const char *str2) {
size_t n2 = strlen(str2), n1 = str1->len;
int r = strncmp(str1->p, str2, (n1 < n2) ? n1 : n2);
if (r == 0) {
return n1 - n2;
}
return r;
}
int mg_vcasecmp(const struct mg_str *str1, const char *str2) WEAK;
int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
size_t n2 = strlen(str2), n1 = str1->len;
int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2);
if (r == 0) {
return n1 - n2;
}
return r;
}
static struct mg_str mg_strdup_common(const struct mg_str s,
int nul_terminate) {
struct mg_str r = {NULL, 0};
if (s.len > 0 && s.p != NULL) {
char *sc = (char *) MG_MALLOC(s.len + (nul_terminate ? 1 : 0));
if (sc != NULL) {
memcpy(sc, s.p, s.len);
if (nul_terminate) sc[s.len] = '\0';
r.p = sc;
r.len = s.len;
}
}
return r;
}
struct mg_str mg_strdup(const struct mg_str s) WEAK;
struct mg_str mg_strdup(const struct mg_str s) {
return mg_strdup_common(s, 0 /* NUL-terminate */);
}
struct mg_str mg_strdup_nul(const struct mg_str s) WEAK;
struct mg_str mg_strdup_nul(const struct mg_str s) {
return mg_strdup_common(s, 1 /* NUL-terminate */);
}
const char *mg_strchr(const struct mg_str s, int c) WEAK;
const char *mg_strchr(const struct mg_str s, int c) {
size_t i;
for (i = 0; i < s.len; i++) {
if (s.p[i] == c) return &s.p[i];
}
return NULL;
}
int mg_strcmp(const struct mg_str str1, const struct mg_str str2) WEAK;
int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
size_t i = 0;
while (i < str1.len && i < str2.len) {
if (str1.p[i] < str2.p[i]) return -1;
if (str1.p[i] > str2.p[i]) return 1;
i++;
}
if (i < str1.len) return 1;
if (i < str2.len) return -1;
return 0;
}
int mg_strncmp(const struct mg_str, const struct mg_str, size_t n) WEAK;
int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n) {
struct mg_str s1 = str1;
struct mg_str s2 = str2;
if (s1.len > n) {
s1.len = n;
}
if (s2.len > n) {
s2.len = n;
}
return mg_strcmp(s1, s2);
}
void mg_strfree(struct mg_str *s) WEAK;
void mg_strfree(struct mg_str *s) {
char *sp = (char *) s->p;
s->p = NULL;
s->len = 0;
if (sp != NULL) free(sp);
}
const char *mg_strstr(const struct mg_str haystack,
const struct mg_str needle) WEAK;
const char *mg_strstr(const struct mg_str haystack,
const struct mg_str needle) {
size_t i;
if (needle.len > haystack.len) return NULL;
for (i = 0; i <= haystack.len - needle.len; i++) {
if (memcmp(haystack.p + i, needle.p, needle.len) == 0) {
return haystack.p + i;
}
}
return NULL;
}
struct mg_str mg_strstrip(struct mg_str s) WEAK;
struct mg_str mg_strstrip(struct mg_str s) {
while (s.len > 0 && isspace((int) *s.p)) {
s.p++;
s.len--;
}
while (s.len > 0 && isspace((int) *(s.p + s.len - 1))) {
s.len--;
}
return s;
}
int mg_str_starts_with(struct mg_str s, struct mg_str prefix) WEAK;
int mg_str_starts_with(struct mg_str s, struct mg_str prefix) {
const struct mg_str sp = MG_MK_STR_N(s.p, prefix.len);
if (s.len < prefix.len) return 0;
return (mg_strcmp(sp, prefix) == 0);
}
#ifdef MG_MODULE_LINES
#line 1 "common/str_util.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef EXCLUDE_COMMON
/* Amalgamated: #include "common/str_util.h" */
/* Amalgamated: #include "common/mg_mem.h" */
/* Amalgamated: #include "common/platform.h" */
#ifndef C_DISABLE_BUILTIN_SNPRINTF
#define C_DISABLE_BUILTIN_SNPRINTF 0
#endif
/* Amalgamated: #include "common/mg_mem.h" */
size_t c_strnlen(const char *s, size_t maxlen) WEAK;
size_t c_strnlen(const char *s, size_t maxlen) {
size_t l = 0;
for (; l < maxlen && s[l] != '\0'; l++) {
}
return l;
}
#define C_SNPRINTF_APPEND_CHAR(ch) \
do { \
if (i < (int) buf_size) buf[i] = ch; \
i++; \
} while (0)
#define C_SNPRINTF_FLAG_ZERO 1
#if C_DISABLE_BUILTIN_SNPRINTF
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK;
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
return vsnprintf(buf, buf_size, fmt, ap);
}
#else
static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags,
int field_width) {
char tmp[40];
int i = 0, k = 0, neg = 0;
if (num < 0) {
neg++;
num = -num;
}
/* Print into temporary buffer - in reverse order */
do {
int rem = num % base;
if (rem < 10) {
tmp[k++] = '0' + rem;
} else {
tmp[k++] = 'a' + (rem - 10);
}
num /= base;
} while (num > 0);
/* Zero padding */
if (flags && C_SNPRINTF_FLAG_ZERO) {
while (k < field_width && k < (int) sizeof(tmp) - 1) {
tmp[k++] = '0';
}
}
/* And sign */
if (neg) {
tmp[k++] = '-';
}
/* Now output */
while (--k >= 0) {
C_SNPRINTF_APPEND_CHAR(tmp[k]);
}
return i;
}
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK;
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
int ch, i = 0, len_mod, flags, precision, field_width;
while ((ch = *fmt++) != '\0') {
if (ch != '%') {
C_SNPRINTF_APPEND_CHAR(ch);
} else {
/*
* Conversion specification:
* zero or more flags (one of: # 0 - <space> + ')
* an optional minimum field width (digits)
* an optional precision (. followed by digits, or *)
* an optional length modifier (one of: hh h l ll L q j z t)
* conversion specifier (one of: d i o u x X e E f F g G a A c s p n)
*/
flags = field_width = precision = len_mod = 0;
/* Flags. only zero-pad flag is supported. */
if (*fmt == '0') {
flags |= C_SNPRINTF_FLAG_ZERO;
}
/* Field width */
while (*fmt >= '0' && *fmt <= '9') {
field_width *= 10;
field_width += *fmt++ - '0';
}
/* Dynamic field width */
if (*fmt == '*') {
field_width = va_arg(ap, int);
fmt++;
}
/* Precision */
if (*fmt == '.') {
fmt++;
if (*fmt == '*') {
precision = va_arg(ap, int);
fmt++;
} else {
while (*fmt >= '0' && *fmt <= '9') {
precision *= 10;
precision += *fmt++ - '0';
}
}
}
/* Length modifier */
switch (*fmt) {
case 'h':
case 'l':
case 'L':
case 'I':
case 'q':
case 'j':
case 'z':
case 't':
len_mod = *fmt++;
if (*fmt == 'h') {
len_mod = 'H';
fmt++;
}
if (*fmt == 'l') {
len_mod = 'q';
fmt++;
}
break;
}
ch = *fmt++;
if (ch == 's') {
const char *s = va_arg(ap, const char *); /* Always fetch parameter */
int j;
int pad = field_width - (precision >= 0 ? c_strnlen(s, precision) : 0);
for (j = 0; j < pad; j++) {
C_SNPRINTF_APPEND_CHAR(' ');
}
/* `s` may be NULL in case of %.*s */
if (s != NULL) {
/* Ignore negative and 0 precisions */
for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) {
C_SNPRINTF_APPEND_CHAR(s[j]);
}
}
} else if (ch == 'c') {
ch = va_arg(ap, int); /* Always fetch parameter */
C_SNPRINTF_APPEND_CHAR(ch);
} else if (ch == 'd' && len_mod == 0) {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags,
field_width);
} else if (ch == 'd' && len_mod == 'l') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags,
field_width);
#ifdef SSIZE_MAX
} else if (ch == 'd' && len_mod == 'z') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, ssize_t), 10, flags,
field_width);
#endif
} else if (ch == 'd' && len_mod == 'q') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags,
field_width);
} else if ((ch == 'x' || ch == 'u') && len_mod == 0) {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned),
ch == 'x' ? 16 : 10, flags, field_width);
} else if ((ch == 'x' || ch == 'u') && len_mod == 'l') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long),
ch == 'x' ? 16 : 10, flags, field_width);
} else if ((ch == 'x' || ch == 'u') && len_mod == 'z') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, size_t),
ch == 'x' ? 16 : 10, flags, field_width);
} else if (ch == 'p') {
unsigned long num = (unsigned long) (uintptr_t) va_arg(ap, void *);
C_SNPRINTF_APPEND_CHAR('0');
C_SNPRINTF_APPEND_CHAR('x');
i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0);
} else {
#ifndef NO_LIBC
/*
* TODO(lsm): abort is not nice in a library, remove it
* Also, ESP8266 SDK doesn't have it
*/
abort();
#endif
}
}
}
/* Zero-terminate the result */
if (buf_size > 0) {
buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0';
}
return i;
}
#endif
int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) WEAK;
int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) {
int result;
va_list ap;
va_start(ap, fmt);
result = c_vsnprintf(buf, buf_size, fmt, ap);
va_end(ap);
return result;
}
#ifdef _WIN32
int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
int ret;
char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
strncpy(buf, path, sizeof(buf));
buf[sizeof(buf) - 1] = '\0';
/* Trim trailing slashes. Leave backslash for paths like "X:\" */
p = buf + strlen(buf) - 1;
while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
/*
* Convert back to Unicode. If doubly-converted string does not match the
* original, something is fishy, reject.
*/
WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
NULL, NULL);
if (strcmp(buf, buf2) != 0) {
wbuf[0] = L'\0';
ret = 0;
}
return ret;
}
#endif /* _WIN32 */
/* The simplest O(mn) algorithm. Better implementation are GPLed */
const char *c_strnstr(const char *s, const char *find, size_t slen) WEAK;
const char *c_strnstr(const char *s, const char *find, size_t slen) {
size_t find_length = strlen(find);
size_t i;
for (i = 0; i < slen; i++) {
if (i + find_length > slen) {
return NULL;
}
if (strncmp(&s[i], find, find_length) == 0) {
return &s[i];
}
}
return NULL;
}
#if CS_ENABLE_STRDUP
char *strdup(const char *src) WEAK;
char *strdup(const char *src) {
size_t len = strlen(src) + 1;
char *ret = MG_MALLOC(len);
if (ret != NULL) {
strcpy(ret, src);
}
return ret;
}
#endif
void cs_to_hex(char *to, const unsigned char *p, size_t len) WEAK;
void cs_to_hex(char *to, const unsigned char *p, size_t len) {
static const char *hex = "0123456789abcdef";
for (; len--; p++) {
*to++ = hex[p[0] >> 4];
*to++ = hex[p[0] & 0x0f];
}
*to = '\0';
}
static int fourbit(int ch) {
if (ch >= '0' && ch <= '9') {
return ch - '0';
} else if (ch >= 'a' && ch <= 'f') {
return ch - 'a' + 10;
} else if (ch >= 'A' && ch <= 'F') {
return ch - 'A' + 10;
}
return 0;
}
void cs_from_hex(char *to, const char *p, size_t len) WEAK;
void cs_from_hex(char *to, const char *p, size_t len) {
size_t i;
for (i = 0; i < len; i += 2) {
*to++ = (fourbit(p[i]) << 4) + fourbit(p[i + 1]);
}
*to = '\0';
}
#if CS_ENABLE_TO64
int64_t cs_to64(const char *s) WEAK;
int64_t cs_to64(const char *s) {
int64_t result = 0;
int64_t neg = 1;
while (*s && isspace((unsigned char) *s)) s++;
if (*s == '-') {
neg = -1;
s++;
}
while (isdigit((unsigned char) *s)) {
result *= 10;
result += (*s - '0');
s++;
}
return result * neg;
}
#endif
static int str_util_lowercase(const char *s) {
return tolower(*(const unsigned char *) s);
}
int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK;
int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
int diff = 0;
if (len > 0) do {
diff = str_util_lowercase(s1++) - str_util_lowercase(s2++);
} while (diff == 0 && s1[-1] != '\0' && --len > 0);
return diff;
}
int mg_casecmp(const char *s1, const char *s2) WEAK;
int mg_casecmp(const char *s1, const char *s2) {
return mg_ncasecmp(s1, s2, (size_t) ~0);
}
int mg_asprintf(char **buf, size_t size, const char *fmt, ...) WEAK;
int mg_asprintf(char **buf, size_t size, const char *fmt, ...) {
int ret;
va_list ap;
va_start(ap, fmt);
ret = mg_avprintf(buf, size, fmt, ap);
va_end(ap);
return ret;
}
int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) WEAK;
int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
va_list ap_copy;
int len;
va_copy(ap_copy, ap);
len = vsnprintf(*buf, size, fmt, ap_copy);
va_end(ap_copy);
if (len < 0) {
/* eCos and Windows are not standard-compliant and return -1 when
* the buffer is too small. Keep allocating larger buffers until we
* succeed or out of memory. */
*buf = NULL; /* LCOV_EXCL_START */
while (len < 0) {
MG_FREE(*buf);
if (size == 0) {
size = 5;
}
size *= 2;
if ((*buf = (char *) MG_MALLOC(size)) == NULL) {
len = -1;
break;
}
va_copy(ap_copy, ap);
len = vsnprintf(*buf, size - 1, fmt, ap_copy);
va_end(ap_copy);
}
/*
* Microsoft version of vsnprintf() is not always null-terminated, so put
* the terminator manually
*/
(*buf)[len] = 0;
/* LCOV_EXCL_STOP */
} else if (len >= (int) size) {
/* Standard-compliant code path. Allocate a buffer that is large enough. */
if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) {
len = -1; /* LCOV_EXCL_LINE */
} else { /* LCOV_EXCL_LINE */
va_copy(ap_copy, ap);
len = vsnprintf(*buf, len + 1, fmt, ap_copy);
va_end(ap_copy);
}
}
return len;
}
const char *mg_next_comma_list_entry(const char *, struct mg_str *,
struct mg_str *) WEAK;
const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
struct mg_str *eq_val) {
struct mg_str ret = mg_next_comma_list_entry_n(mg_mk_str(list), val, eq_val);
return ret.p;
}
struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val,
struct mg_str *eq_val) WEAK;
struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val,
struct mg_str *eq_val) {
if (list.len == 0) {
/* End of the list */
list = mg_mk_str(NULL);
} else {
const char *chr = NULL;
*val = list;
if ((chr = mg_strchr(*val, ',')) != NULL) {
/* Comma found. Store length and shift the list ptr */
val->len = chr - val->p;
chr++;
list.len -= (chr - list.p);
list.p = chr;
} else {
/* This value is the last one */
list = mg_mk_str_n(list.p + list.len, 0);
}
if (eq_val != NULL) {
/* Value has form "x=y", adjust pointers and lengths */
/* so that val points to "x", and eq_val points to "y". */
eq_val->len = 0;
eq_val->p = (const char *) memchr(val->p, '=', val->len);
if (eq_val->p != NULL) {
eq_val->p++; /* Skip over '=' character */
eq_val->len = val->p + val->len - eq_val->p;
val->len = (eq_val->p - val->p) - 1;
}
}
}
return list;
}
size_t mg_match_prefix_n(const struct mg_str, const struct mg_str) WEAK;
size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) {
const char *or_str;
size_t res = 0, len = 0, i = 0, j = 0;
if ((or_str = (const char *) memchr(pattern.p, '|', pattern.len)) != NULL ||
(or_str = (const char *) memchr(pattern.p, ',', pattern.len)) != NULL) {
struct mg_str pstr = {pattern.p, (size_t)(or_str - pattern.p)};
res = mg_match_prefix_n(pstr, str);
if (res > 0) return res;
pstr.p = or_str + 1;
pstr.len = (pattern.p + pattern.len) - (or_str + 1);
return mg_match_prefix_n(pstr, str);
}
for (; i < pattern.len && j < str.len; i++, j++) {
if (pattern.p[i] == '?') {
continue;
} else if (pattern.p[i] == '*') {
i++;
if (i < pattern.len && pattern.p[i] == '*') {
i++;
len = str.len - j;
} else {
len = 0;
while (j + len < str.len && str.p[j + len] != '/') len++;
}
if (i == pattern.len || (pattern.p[i] == '$' && i == pattern.len - 1))
return j + len;
do {
const struct mg_str pstr = {pattern.p + i, pattern.len - i};
const struct mg_str sstr = {str.p + j + len, str.len - j - len};
res = mg_match_prefix_n(pstr, sstr);
} while (res == 0 && len != 0 && len-- > 0);
return res == 0 ? 0 : j + res + len;
} else if (str_util_lowercase(&pattern.p[i]) !=
str_util_lowercase(&str.p[j])) {
break;
}
}
if (i < pattern.len && pattern.p[i] == '$') {
return j == str.len ? str.len : 0;
}
return i == pattern.len ? j : 0;
}
size_t mg_match_prefix(const char *, int, const char *) WEAK;
size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
const struct mg_str pstr = {pattern, (size_t) pattern_len};
struct mg_str s = {str, 0};
if (str != NULL) s.len = strlen(str);
return mg_match_prefix_n(pstr, s);
}
#endif /* EXCLUDE_COMMON */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_net.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*
* This software is dual-licensed: 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. For the terms of this
* license, see <http://www.gnu.org/licenses/>.
*
* You are free to use this software under the terms of the GNU General
* Public License, 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.
*
* Alternatively, you can license this software under a commercial
* license, as set out in <https://www.cesanta.com/license>.
*/
/* Amalgamated: #include "common/cs_time.h" */
/* Amalgamated: #include "mg_dns.h" */
/* Amalgamated: #include "mg_internal.h" */
/* Amalgamated: #include "mg_resolv.h" */
/* Amalgamated: #include "mg_util.h" */
#define MG_MAX_HOST_LEN 200
#ifndef MG_TCP_IO_SIZE
#define MG_TCP_IO_SIZE 1460
#endif
#ifndef MG_UDP_IO_SIZE
#define MG_UDP_IO_SIZE 1460
#endif
#define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \
memcpy(dst, src, sizeof(*dst));
/* Which flags can be pre-set by the user at connection creation time. */
#define _MG_ALLOWED_CONNECT_FLAGS_MASK \
(MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_ENABLE_BROADCAST)
/* Which flags should be modifiable by user's callbacks. */
#define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK \
(MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE | \
MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK)
#ifndef intptr_t
#define intptr_t long
#endif
MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) {
DBG(("%p %p", mgr, c));
c->mgr = mgr;
c->next = mgr->active_connections;
mgr->active_connections = c;
c->prev = NULL;
if (c->next != NULL) c->next->prev = c;
if (c->sock != INVALID_SOCKET) {
c->iface->vtable->add_conn(c);
}
}
MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) {
if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
if (conn->prev) conn->prev->next = conn->next;
if (conn->next) conn->next->prev = conn->prev;
conn->prev = conn->next = NULL;
conn->iface->vtable->remove_conn(conn);
}
MG_INTERNAL void mg_call(struct mg_connection *nc,
mg_event_handler_t ev_handler, void *user_data, int ev,
void *ev_data) {
if (ev_handler == NULL) {
/*
* If protocol handler is specified, call it. Otherwise, call user-specified
* event handler.
*/
ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler;
}
if (ev != MG_EV_POLL) {
DBG(("%p %s ev=%d ev_data=%p flags=0x%lx rmbl=%d smbl=%d", nc,
ev_handler == nc->handler ? "user" : "proto", ev, ev_data, nc->flags,
(int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
}
#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL && ev != MG_EV_RECV &&
ev != MG_EV_SEND /* handled separately */) {
mg_hexdump_connection(nc, nc->mgr->hexdump_file, NULL, 0, ev);
}
#endif
if (ev_handler != NULL) {
unsigned long flags_before = nc->flags;
ev_handler(nc, ev, ev_data MG_UD_ARG(user_data));
/* Prevent user handler from fiddling with system flags. */
if (ev_handler == nc->handler && nc->flags != flags_before) {
nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) |
(nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK);
}
}
if (ev != MG_EV_POLL) nc->mgr->num_calls++;
if (ev != MG_EV_POLL) {
DBG(("%p after %s flags=0x%lx rmbl=%d smbl=%d", nc,
ev_handler == nc->handler ? "user" : "proto", nc->flags,
(int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
}
#if !MG_ENABLE_CALLBACK_USERDATA
(void) user_data;
#endif
}
MG_INTERNAL void mg_timer(struct mg_connection *c, double now) {
if (c->ev_timer_time > 0 && now >= c->ev_timer_time) {
double old_value = c->ev_timer_time;
c->ev_timer_time = 0;
mg_call(c, NULL, c->user_data, MG_EV_TIMER, &old_value);
}
}
MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
size_t avail;
if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
return avail > max ? max : avail;
}
static int mg_do_recv(struct mg_connection *nc);
int mg_if_poll(struct mg_connection *nc, double now) {
if (nc->flags & MG_F_CLOSE_IMMEDIATELY) {
mg_close_conn(nc);
return 0;
} else if (nc->flags & MG_F_SEND_AND_CLOSE) {
if (nc->send_mbuf.len == 0) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
mg_close_conn(nc);
return 0;
}
} else if (nc->flags & MG_F_RECV_AND_CLOSE) {
mg_close_conn(nc);
return 0;
}
#if MG_ENABLE_SSL
if ((nc->flags & (MG_F_SSL | MG_F_LISTENING | MG_F_CONNECTING)) == MG_F_SSL) {
/* SSL library may have data to be delivered to the app in its buffers,
* drain them. */
int recved = 0;
do {
if (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE)) break;
if (recv_avail_size(nc, MG_TCP_IO_SIZE) <= 0) break;
recved = mg_do_recv(nc);
} while (recved > 0);
}
#endif /* MG_ENABLE_SSL */
mg_timer(nc, now);
{
time_t now_t = (time_t) now;
mg_call(nc, NULL, nc->user_data, MG_EV_POLL, &now_t);
}
return 1;
}
void mg_destroy_conn(struct mg_connection *conn, int destroy_if) {
if (conn->sock != INVALID_SOCKET) { /* Don't print timer-only conns */
LOG(LL_DEBUG, ("%p 0x%lx %d", conn, conn->flags, destroy_if));
}
if (destroy_if) conn->iface->vtable->destroy_conn(conn);
if (conn->proto_data != NULL && conn->proto_data_destructor != NULL) {
conn->proto_data_destructor(conn->proto_data);
}
#if MG_ENABLE_SSL
mg_ssl_if_conn_free(conn);
#endif
mbuf_free(&conn->recv_mbuf);
mbuf_free(&conn->send_mbuf);
memset(conn, 0, sizeof(*conn));
MG_FREE(conn);
}
void mg_close_conn(struct mg_connection *conn) {
/* See if there's any remaining data to deliver. Skip if user completely
* throttled the connection there will be no progress anyway. */
if (conn->sock != INVALID_SOCKET && mg_do_recv(conn) == -2) {
/* Receive is throttled, wait. */
conn->flags |= MG_F_RECV_AND_CLOSE;
return;
}
#if MG_ENABLE_SSL
if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
mg_ssl_if_conn_close_notify(conn);
}
#endif
/*
* Clearly mark the connection as going away (if not already).
* Some net_if impls (LwIP) need this for cleanly handling half-dead conns.
*/
conn->flags |= MG_F_CLOSE_IMMEDIATELY;
mg_remove_conn(conn);
conn->iface->vtable->destroy_conn(conn);
mg_call(conn, NULL, conn->user_data, MG_EV_CLOSE, NULL);
mg_destroy_conn(conn, 0 /* destroy_if */);
}
void mg_mgr_init(struct mg_mgr *m, void *user_data) {
struct mg_mgr_init_opts opts;
memset(&opts, 0, sizeof(opts));
mg_mgr_init_opt(m, user_data, opts);
}
void mg_mgr_init_opt(struct mg_mgr *m, void *user_data,
struct mg_mgr_init_opts opts) {
memset(m, 0, sizeof(*m));
#if MG_ENABLE_BROADCAST
m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
#endif
m->user_data = user_data;
#ifdef _WIN32
{
WSADATA data;
WSAStartup(MAKEWORD(2, 2), &data);
}
#elif defined(__unix__)
/* Ignore SIGPIPE signal, so if client cancels the request, it
* won't kill the whole process. */
signal(SIGPIPE, SIG_IGN);
#endif
{
int i;
if (opts.num_ifaces == 0) {
opts.num_ifaces = mg_num_ifaces;
opts.ifaces = mg_ifaces;
}
if (opts.main_iface != NULL) {
opts.ifaces[MG_MAIN_IFACE] = opts.main_iface;
}
m->num_ifaces = opts.num_ifaces;
m->ifaces =
(struct mg_iface **) MG_MALLOC(sizeof(*m->ifaces) * opts.num_ifaces);
for (i = 0; i < opts.num_ifaces; i++) {
m->ifaces[i] = mg_if_create_iface(opts.ifaces[i], m);
m->ifaces[i]->vtable->init(m->ifaces[i]);
}
}
if (opts.nameserver != NULL) {
m->nameserver = strdup(opts.nameserver);
}
DBG(("=================================="));
DBG(("init mgr=%p", m));
#if MG_ENABLE_SSL
{
static int init_done;
if (!init_done) {
mg_ssl_if_init();
init_done++;
}
}
#endif
}
void mg_mgr_free(struct mg_mgr *m) {
struct mg_connection *conn, *tmp_conn;
DBG(("%p", m));
if (m == NULL) return;
/* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */
mg_mgr_poll(m, 0);
#if MG_ENABLE_BROADCAST
if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]);
if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]);
m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
#endif
for (conn = m->active_connections; conn != NULL; conn = tmp_conn) {
tmp_conn = conn->next;
conn->flags |= MG_F_CLOSE_IMMEDIATELY;
mg_close_conn(conn);
}
{
int i;
for (i = 0; i < m->num_ifaces; i++) {
m->ifaces[i]->vtable->free(m->ifaces[i]);
MG_FREE(m->ifaces[i]);
}
MG_FREE(m->ifaces);
}
MG_FREE((char *) m->nameserver);
}
int mg_mgr_poll(struct mg_mgr *m, int timeout_ms) {
int i, num_calls_before = m->num_calls;
for (i = 0; i < m->num_ifaces; i++) {
m->ifaces[i]->vtable->poll(m->ifaces[i], timeout_ms);
}
return (m->num_calls - num_calls_before);
}
int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) {
char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
int len;
if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
mg_send(nc, buf, len);
}
if (buf != mem && buf != NULL) {
MG_FREE(buf); /* LCOV_EXCL_LINE */
} /* LCOV_EXCL_LINE */
return len;
}
int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
int len;
va_list ap;
va_start(ap, fmt);
len = mg_vprintf(conn, fmt, ap);
va_end(ap);
return len;
}
#if MG_ENABLE_SYNC_RESOLVER
/* TODO(lsm): use non-blocking resolver */
static int mg_resolve2(const char *host, struct in_addr *ina) {
#if MG_ENABLE_GETADDRINFO
int rv = 0;
struct addrinfo hints, *servinfo, *p;
struct sockaddr_in *h = NULL;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) {
DBG(("getaddrinfo(%s) failed: %s", host, strerror(mg_get_errno())));
return 0;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
memcpy(&h, &p->ai_addr, sizeof(h));
memcpy(ina, &h->sin_addr, sizeof(*ina));
}
freeaddrinfo(servinfo);
return 1;
#else
struct hostent *he;
if ((he = gethostbyname(host)) == NULL) {
DBG(("gethostbyname(%s) failed: %s", host, strerror(mg_get_errno())));
} else {
memcpy(ina, he->h_addr_list[0], sizeof(*ina));
return 1;
}
return 0;
#endif /* MG_ENABLE_GETADDRINFO */
}
int mg_resolve(const char *host, char *buf, size_t n) {
struct in_addr ad;
return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
}
#endif /* MG_ENABLE_SYNC_RESOLVER */
MG_INTERNAL struct mg_connection *mg_create_connection_base(
struct mg_mgr *mgr, mg_event_handler_t callback,
struct mg_add_sock_opts opts) {
struct mg_connection *conn;
if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) {
conn->sock = INVALID_SOCKET;
conn->handler = callback;
conn->mgr = mgr;
conn->last_io_time = (time_t) mg_time();
conn->iface =
(opts.iface != NULL ? opts.iface : mgr->ifaces[MG_MAIN_IFACE]);
conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
conn->user_data = opts.user_data;
/*
* SIZE_MAX is defined as a long long constant in
* system headers on some platforms and so it
* doesn't compile with pedantic ansi flags.
*/
conn->recv_mbuf_limit = ~0;
} else {
MG_SET_PTRPTR(opts.error_string, "failed to create connection");
}
return conn;
}
MG_INTERNAL struct mg_connection *mg_create_connection(
struct mg_mgr *mgr, mg_event_handler_t callback,
struct mg_add_sock_opts opts) {
struct mg_connection *conn = mg_create_connection_base(mgr, callback, opts);
if (conn != NULL && !conn->iface->vtable->create_conn(conn)) {
MG_FREE(conn);
conn = NULL;
}
if (conn == NULL) {
MG_SET_PTRPTR(opts.error_string, "failed to init connection");
}
return conn;
}
/*
* Address format: [PROTO://][HOST]:PORT
*
* HOST could be IPv4/IPv6 address or a host name.
* `host` is a destination buffer to hold parsed HOST part. Should be at least
* MG_MAX_HOST_LEN bytes long.
* `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM
*
* Return:
* -1 on parse error
* 0 if HOST needs DNS lookup
* >0 length of the address string
*/
MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
int *proto, char *host, size_t host_len) {
unsigned int a, b, c, d, port = 0;
int ch, len = 0;
#if MG_ENABLE_IPV6
char buf[100];
#endif
/*
* MacOS needs that. If we do not zero it, subsequent bind() will fail.
* Also, all-zeroes in the socket address means binding to all addresses
* for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
*/
memset(sa, 0, sizeof(*sa));
sa->sin.sin_family = AF_INET;
*proto = SOCK_STREAM;
if (strncmp(str, "udp://", 6) == 0) {
str += 6;
*proto = SOCK_DGRAM;
} else if (strncmp(str, "tcp://", 6) == 0) {
str += 6;
}
if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
/* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
sa->sin.sin_addr.s_addr =
htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d);
sa->sin.sin_port = htons((uint16_t) port);
#if MG_ENABLE_IPV6
} else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
/* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
sa->sin6.sin6_family = AF_INET6;
sa->sin.sin_port = htons((uint16_t) port);
#endif
#if MG_ENABLE_ASYNC_RESOLVER
} else if (strlen(str) < host_len &&
sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) {
sa->sin.sin_port = htons((uint16_t) port);
if (mg_resolve_from_hosts_file(host, sa) != 0) {
/*
* if resolving from hosts file failed and the host
* we are trying to resolve is `localhost` - we should
* try to resolve it using `gethostbyname` and do not try
* to resolve it via DNS server if gethostbyname has failed too
*/
if (mg_ncasecmp(host, "localhost", 9) != 0) {
return 0;
}
#if MG_ENABLE_SYNC_RESOLVER
if (!mg_resolve2(host, &sa->sin.sin_addr)) {
return -1;
}
#else
return -1;
#endif
}
#endif
} else if (sscanf(str, ":%u%n", &port, &len) == 1 ||
sscanf(str, "%u%n", &port, &len) == 1) {
/* If only port is specified, bind to IPv4, INADDR_ANY */
sa->sin.sin_port = htons((uint16_t) port);
} else {
return -1;
}
/* Required for MG_ENABLE_ASYNC_RESOLVER=0 */
(void) host;
(void) host_len;
ch = str[len]; /* Character that follows the address */
return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1;
}
#if MG_ENABLE_SSL
MG_INTERNAL void mg_ssl_handshake(struct mg_connection *nc) {
int err = 0;
int server_side = (nc->listener != NULL);
enum mg_ssl_if_result res;
if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) return;
res = mg_ssl_if_handshake(nc);
if (res == MG_SSL_OK) {
nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
if (server_side) {
mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
} else {
mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err);
}
} else if (res == MG_SSL_WANT_READ) {
nc->flags |= MG_F_WANT_READ;
} else if (res == MG_SSL_WANT_WRITE) {
nc->flags |= MG_F_WANT_WRITE;
} else {
if (!server_side) {
err = res;
mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err);
}
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
}
#endif /* MG_ENABLE_SSL */
struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc) {
struct mg_add_sock_opts opts;
struct mg_connection *nc;
memset(&opts, 0, sizeof(opts));
nc = mg_create_connection(lc->mgr, lc->handler, opts);
if (nc == NULL) return NULL;
nc->listener = lc;
nc->proto_handler = lc->proto_handler;
nc->user_data = lc->user_data;
nc->recv_mbuf_limit = lc->recv_mbuf_limit;
nc->iface = lc->iface;
if (lc->flags & MG_F_SSL) nc->flags |= MG_F_SSL;
mg_add_conn(nc->mgr, nc);
LOG(LL_DEBUG, ("%p %p %d %d", lc, nc, nc->sock, (int) nc->flags));
return nc;
}
void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa,
size_t sa_len) {
LOG(LL_DEBUG, ("%p %s://%s:%hu", nc, (nc->flags & MG_F_UDP ? "udp" : "tcp"),
inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
nc->sa = *sa;
#if MG_ENABLE_SSL
if (nc->listener->flags & MG_F_SSL) {
nc->flags |= MG_F_SSL;
if (mg_ssl_if_conn_accept(nc, nc->listener) == MG_SSL_OK) {
mg_ssl_handshake(nc);
} else {
mg_close_conn(nc);
}
} else
#endif
{
mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
}
(void) sa_len;
}
void mg_send(struct mg_connection *nc, const void *buf, int len) {
nc->last_io_time = (time_t) mg_time();
mbuf_append(&nc->send_mbuf, buf, len);
}
static int mg_recv_tcp(struct mg_connection *nc, char *buf, size_t len);
static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len);
static int mg_do_recv(struct mg_connection *nc) {
int res = 0;
char *buf = NULL;
size_t len = (nc->flags & MG_F_UDP ? MG_UDP_IO_SIZE : MG_TCP_IO_SIZE);
if ((nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_CONNECTING)) ||
((nc->flags & MG_F_LISTENING) && !(nc->flags & MG_F_UDP))) {
return -1;
}
do {
len = recv_avail_size(nc, len);
if (len == 0) {
res = -2;
break;
}
if (nc->recv_mbuf.size < nc->recv_mbuf.len + len) {
mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.len + len);
}
buf = nc->recv_mbuf.buf + nc->recv_mbuf.len;
len = nc->recv_mbuf.size - nc->recv_mbuf.len;
if (nc->flags & MG_F_UDP) {
res = mg_recv_udp(nc, buf, len);
} else {
res = mg_recv_tcp(nc, buf, len);
}
} while (res > 0 && !(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_UDP)));
return res;
}
void mg_if_can_recv_cb(struct mg_connection *nc) {
mg_do_recv(nc);
}
static int mg_recv_tcp(struct mg_connection *nc, char *buf, size_t len) {
int n = 0;
#if MG_ENABLE_SSL
if (nc->flags & MG_F_SSL) {
if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
n = mg_ssl_if_read(nc, buf, len);
DBG(("%p <- %d bytes (SSL)", nc, n));
if (n < 0) {
if (n == MG_SSL_WANT_READ) {
nc->flags |= MG_F_WANT_READ;
n = 0;
} else {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
} else if (n > 0) {
nc->flags &= ~MG_F_WANT_READ;
}
} else {
mg_ssl_handshake(nc);
}
} else
#endif
{
n = nc->iface->vtable->tcp_recv(nc, buf, len);
DBG(("%p <- %d bytes", nc, n));
}
if (n > 0) {
nc->recv_mbuf.len += n;
nc->last_io_time = (time_t) mg_time();
#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
if (nc->mgr && nc->mgr->hexdump_file != NULL) {
mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV);
}
#endif
mbuf_trim(&nc->recv_mbuf);
mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n);
} else if (n < 0) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
mbuf_trim(&nc->recv_mbuf);
return n;
}
static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len) {
int n = 0;
struct mg_connection *lc = nc;
union socket_address sa;
size_t sa_len = sizeof(sa);
n = nc->iface->vtable->udp_recv(lc, buf, len, &sa, &sa_len);
if (n < 0) {
lc->flags |= MG_F_CLOSE_IMMEDIATELY;
goto out;
}
if (nc->flags & MG_F_LISTENING) {
/*
* Do we have an existing connection for this source?
* This is very inefficient for long connection lists.
*/
lc = nc;
for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) {
if (memcmp(&nc->sa.sa, &sa.sa, sa_len) == 0 && nc->listener == lc) {
break;
}
}
if (nc == NULL) {
struct mg_add_sock_opts opts;
memset(&opts, 0, sizeof(opts));
/* Create fake connection w/out sock initialization */
nc = mg_create_connection_base(lc->mgr, lc->handler, opts);
if (nc != NULL) {
nc->sock = lc->sock;
nc->listener = lc;
nc->sa = sa;
nc->proto_handler = lc->proto_handler;
nc->user_data = lc->user_data;
nc->recv_mbuf_limit = lc->recv_mbuf_limit;
nc->flags = MG_F_UDP;
/*
* Long-lived UDP "connections" i.e. interactions that involve more
* than one request and response are rare, most are transactional:
* response is sent and the "connection" is closed. Or - should be.
* But users (including ourselves) tend to forget about that part,
* because UDP is connectionless and one does not think about
* processing a UDP request as handling a connection that needs to be
* closed. Thus, we begin with SEND_AND_CLOSE flag set, which should
* be a reasonable default for most use cases, but it is possible to
* turn it off the connection should be kept alive after processing.
*/
nc->flags |= MG_F_SEND_AND_CLOSE;
mg_add_conn(lc->mgr, nc);
mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
}
}
}
if (nc != NULL) {
DBG(("%p <- %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
ntohs(nc->sa.sin.sin_port)));
if (nc == lc) {
nc->recv_mbuf.len += n;
} else {
mbuf_append(&nc->recv_mbuf, buf, n);
}
mbuf_trim(&lc->recv_mbuf);
lc->last_io_time = nc->last_io_time = (time_t) mg_time();
#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
if (nc->mgr && nc->mgr->hexdump_file != NULL) {
mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV);
}
#endif
if (n != 0) {
mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n);
}
}
out:
mbuf_free(&lc->recv_mbuf);
return n;
}
void mg_if_can_send_cb(struct mg_connection *nc) {
int n = 0;
const char *buf = nc->send_mbuf.buf;
size_t len = nc->send_mbuf.len;
if (nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_CONNECTING)) {
return;
}
if (!(nc->flags & MG_F_UDP)) {
if (nc->flags & MG_F_LISTENING) return;
if (len > MG_TCP_IO_SIZE) len = MG_TCP_IO_SIZE;
}
#if MG_ENABLE_SSL
if (nc->flags & MG_F_SSL) {
if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
if (len > 0) {
n = mg_ssl_if_write(nc, buf, len);
DBG(("%p -> %d bytes (SSL)", nc, n));
}
if (n < 0) {
if (n == MG_SSL_WANT_WRITE) {
nc->flags |= MG_F_WANT_WRITE;
n = 0;
} else {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
} else {
nc->flags &= ~MG_F_WANT_WRITE;
}
} else {
mg_ssl_handshake(nc);
}
} else
#endif
if (len > 0) {
if (nc->flags & MG_F_UDP) {
n = nc->iface->vtable->udp_send(nc, buf, len);
} else {
n = nc->iface->vtable->tcp_send(nc, buf, len);
}
DBG(("%p -> %d bytes", nc, n));
}
#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
if (n > 0 && nc->mgr && nc->mgr->hexdump_file != NULL) {
mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_SEND);
}
#endif
if (n < 0) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
} else if (n > 0) {
nc->last_io_time = (time_t) mg_time();
mbuf_remove(&nc->send_mbuf, n);
mbuf_trim(&nc->send_mbuf);
}
if (n != 0) mg_call(nc, NULL, nc->user_data, MG_EV_SEND, &n);
}
/*
* Schedules an async connect for a resolved address and proto.
* Called from two places: `mg_connect_opt()` and from async resolver.
* When called from the async resolver, it must trigger `MG_EV_CONNECT` event
* with a failure flag to indicate connection failure.
*/
MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
int proto,
union socket_address *sa) {
LOG(LL_DEBUG, ("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp",
inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
nc->flags |= MG_F_CONNECTING;
if (proto == SOCK_DGRAM) {
nc->iface->vtable->connect_udp(nc);
} else {
nc->iface->vtable->connect_tcp(nc, sa);
}
mg_add_conn(nc->mgr, nc);
return nc;
}
void mg_if_connect_cb(struct mg_connection *nc, int err) {
LOG(LL_DEBUG,
("%p %s://%s:%hu -> %d", nc, (nc->flags & MG_F_UDP ? "udp" : "tcp"),
inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port), err));
nc->flags &= ~MG_F_CONNECTING;
if (err != 0) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
#if MG_ENABLE_SSL
if (err == 0 && (nc->flags & MG_F_SSL)) {
mg_ssl_handshake(nc);
} else
#endif
{
mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err);
}
}
#if MG_ENABLE_ASYNC_RESOLVER
/*
* Callback for the async resolver on mg_connect_opt() call.
* Main task of this function is to trigger MG_EV_CONNECT event with
* either failure (and dealloc the connection)
* or success (and proceed with connect()
*/
static void resolve_cb(struct mg_dns_message *msg, void *data,
enum mg_resolve_err e) {
struct mg_connection *nc = (struct mg_connection *) data;
int i;
int failure = -1;
nc->flags &= ~MG_F_RESOLVING;
if (msg != NULL) {
/*
* Take the first DNS A answer and run...
*/
for (i = 0; i < msg->num_answers; i++) {
if (msg->answers[i].rtype == MG_DNS_A_RECORD) {
/*
* Async resolver guarantees that there is at least one answer.
* TODO(lsm): handle IPv6 answers too
*/
mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr,
4);
mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM,
&nc->sa);
return;
}
}
}
if (e == MG_RESOLVE_TIMEOUT) {
double now = mg_time();
mg_call(nc, NULL, nc->user_data, MG_EV_TIMER, &now);
}
/*
* If we get there was no MG_DNS_A_RECORD in the answer
*/
mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &failure);
mg_call(nc, NULL, nc->user_data, MG_EV_CLOSE, NULL);
mg_destroy_conn(nc, 1 /* destroy_if */);
}
#endif
struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
MG_CB(mg_event_handler_t callback,
void *user_data)) {
struct mg_connect_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_connect_opt(mgr, address, MG_CB(callback, user_data), opts);
}
void mg_ev_handler_empty(struct mg_connection *c, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
(void) c;
(void) ev;
(void) ev_data;
#if MG_ENABLE_CALLBACK_USERDATA
(void) user_data;
#endif
}
struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
MG_CB(mg_event_handler_t callback,
void *user_data),
struct mg_connect_opts opts) {
struct mg_connection *nc = NULL;
int proto, rc;
struct mg_add_sock_opts add_sock_opts;
char host[MG_MAX_HOST_LEN];
MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
if (callback == NULL) callback = mg_ev_handler_empty;
if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) {
return NULL;
}
if ((rc = mg_parse_address(address, &nc->sa, &proto, host, sizeof(host))) <
0) {
/* Address is malformed */
MG_SET_PTRPTR(opts.error_string, "cannot parse address");
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
}
nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0;
#if MG_ENABLE_CALLBACK_USERDATA
nc->user_data = user_data;
#else
nc->user_data = opts.user_data;
#endif
#if MG_ENABLE_SSL
LOG(LL_DEBUG,
("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
(opts.ssl_key ? opts.ssl_key : "-"),
(opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL ||
opts.ssl_psk_identity != NULL) {
const char *err_msg = NULL;
struct mg_ssl_if_conn_params params;
if (nc->flags & MG_F_UDP) {
MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
}
memset(¶ms, 0, sizeof(params));
params.cert = opts.ssl_cert;
params.key = opts.ssl_key;
params.ca_cert = opts.ssl_ca_cert;
params.cipher_suites = opts.ssl_cipher_suites;
params.psk_identity = opts.ssl_psk_identity;
params.psk_key = opts.ssl_psk_key;
if (opts.ssl_ca_cert != NULL) {
if (opts.ssl_server_name != NULL) {
if (strcmp(opts.ssl_server_name, "*") != 0) {
params.server_name = opts.ssl_server_name;
}
} else if (rc == 0) { /* If it's a DNS name, use host. */
params.server_name = host;
}
}
if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
MG_SET_PTRPTR(opts.error_string, err_msg);
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
}
nc->flags |= MG_F_SSL;
}
#endif /* MG_ENABLE_SSL */
if (rc == 0) {
#if MG_ENABLE_ASYNC_RESOLVER
/*
* DNS resolution is required for host.
* mg_parse_address() fills port in nc->sa, which we pass to resolve_cb()
*/
struct mg_connection *dns_conn = NULL;
struct mg_resolve_async_opts o;
memset(&o, 0, sizeof(o));
o.dns_conn = &dns_conn;
o.nameserver = opts.nameserver;
if (mg_resolve_async_opt(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc,
o) != 0) {
MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup");
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
}
nc->priv_2 = dns_conn;
nc->flags |= MG_F_RESOLVING;
return nc;
#else
MG_SET_PTRPTR(opts.error_string, "Resolver is disabled");
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
#endif
} else {
/* Address is parsed and resolved to IP. proceed with connect() */
return mg_do_connect(nc, proto, &nc->sa);
}
}
struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address,
MG_CB(mg_event_handler_t event_handler,
void *user_data)) {
struct mg_bind_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_bind_opt(srv, address, MG_CB(event_handler, user_data), opts);
}
struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
MG_CB(mg_event_handler_t callback,
void *user_data),
struct mg_bind_opts opts) {
union socket_address sa;
struct mg_connection *nc = NULL;
int proto, rc;
struct mg_add_sock_opts add_sock_opts;
char host[MG_MAX_HOST_LEN];
#if MG_ENABLE_CALLBACK_USERDATA
opts.user_data = user_data;
#endif
if (callback == NULL) callback = mg_ev_handler_empty;
MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) {
MG_SET_PTRPTR(opts.error_string, "cannot parse address");
return NULL;
}
nc = mg_create_connection(mgr, callback, add_sock_opts);
if (nc == NULL) {
return NULL;
}
nc->sa = sa;
nc->flags |= MG_F_LISTENING;
if (proto == SOCK_DGRAM) nc->flags |= MG_F_UDP;
#if MG_ENABLE_SSL
DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
(opts.ssl_key ? opts.ssl_key : "-"),
(opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) {
const char *err_msg = NULL;
struct mg_ssl_if_conn_params params;
if (nc->flags & MG_F_UDP) {
MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
}
memset(¶ms, 0, sizeof(params));
params.cert = opts.ssl_cert;
params.key = opts.ssl_key;
params.ca_cert = opts.ssl_ca_cert;
params.cipher_suites = opts.ssl_cipher_suites;
if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
MG_SET_PTRPTR(opts.error_string, err_msg);
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
}
nc->flags |= MG_F_SSL;
}
#endif /* MG_ENABLE_SSL */
if (nc->flags & MG_F_UDP) {
rc = nc->iface->vtable->listen_udp(nc, &nc->sa);
} else {
rc = nc->iface->vtable->listen_tcp(nc, &nc->sa);
}
if (rc != 0) {
DBG(("Failed to open listener: %d", rc));
MG_SET_PTRPTR(opts.error_string, "failed to open listener");
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
}
mg_add_conn(nc->mgr, nc);
return nc;
}
struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) {
return conn == NULL ? s->active_connections : conn->next;
}
#if MG_ENABLE_BROADCAST
void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data,
size_t len) {
struct ctl_msg ctl_msg;
/*
* Mongoose manager has a socketpair, `struct mg_mgr::ctl`,
* where `mg_broadcast()` pushes the message.
* `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls
* specified callback for each connection. Thus the callback function executes
* in event manager thread.
*/
if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
len < sizeof(ctl_msg.message)) {
size_t dummy;
ctl_msg.callback = cb;
memcpy(ctl_msg.message, data, len);
dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg,
offsetof(struct ctl_msg, message) + len, 0);
dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0);
(void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
}
}
#endif /* MG_ENABLE_BROADCAST */
static int isbyte(int n) {
return n >= 0 && n <= 255;
}
static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
int n, a, b, c, d, slash = 32, len = 0;
if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
slash < 33) {
len = n;
*net =
((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d;
*mask = slash ? 0xffffffffU << (32 - slash) : 0;
}
return len;
}
int mg_check_ip_acl(const char *acl, uint32_t remote_ip) {
int allowed, flag;
uint32_t net, mask;
struct mg_str vec;
/* If any ACL is set, deny by default */
allowed = (acl == NULL || *acl == '\0') ? '+' : '-';
while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) {
flag = vec.p[0];
if ((flag != '+' && flag != '-') ||
parse_net(&vec.p[1], &net, &mask) == 0) {
return -1;
}
if (net == (remote_ip & mask)) {
allowed = flag;
}
}
DBG(("%08x %c", (unsigned int) remote_ip, allowed));
return allowed == '+';
}
/* Move data from one connection to another */
void mg_forward(struct mg_connection *from, struct mg_connection *to) {
mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len);
mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len);
}
double mg_set_timer(struct mg_connection *c, double timestamp) {
double result = c->ev_timer_time;
c->ev_timer_time = timestamp;
/*
* If this connection is resolving, it's not in the list of active
* connections, so not processed yet. It has a DNS resolver connection
* linked to it. Set up a timer for the DNS connection.
*/
DBG(("%p %p %d -> %lu", c, c->priv_2, (c->flags & MG_F_RESOLVING ? 1 : 0),
(unsigned long) timestamp));
if ((c->flags & MG_F_RESOLVING) && c->priv_2 != NULL) {
mg_set_timer((struct mg_connection *) c->priv_2, timestamp);
}
return result;
}
void mg_sock_set(struct mg_connection *nc, sock_t sock) {
if (sock != INVALID_SOCKET) {
nc->iface->vtable->sock_set(nc, sock);
}
}
void mg_if_get_conn_addr(struct mg_connection *nc, int remote,
union socket_address *sa) {
nc->iface->vtable->get_conn_addr(nc, remote, sa);
}
struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock,
MG_CB(mg_event_handler_t callback,
void *user_data),
struct mg_add_sock_opts opts) {
#if MG_ENABLE_CALLBACK_USERDATA
opts.user_data = user_data;
#endif
struct mg_connection *nc = mg_create_connection_base(s, callback, opts);
if (nc != NULL) {
mg_sock_set(nc, sock);
mg_add_conn(nc->mgr, nc);
}
return nc;
}
struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock,
MG_CB(mg_event_handler_t callback,
void *user_data)) {
struct mg_add_sock_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_add_sock_opt(s, sock, MG_CB(callback, user_data), opts);
}
double mg_time(void) {
return cs_time();
}
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_net_if_socket.h"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#ifndef CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
#define CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
/* Amalgamated: #include "mg_net_if.h" */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifndef MG_ENABLE_NET_IF_SOCKET
#define MG_ENABLE_NET_IF_SOCKET MG_NET_IF == MG_NET_IF_SOCKET
#endif
extern const struct mg_iface_vtable mg_socket_iface_vtable;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_net_if_socks.h"
#endif
/*
* Copyright (c) 2014-2017 Cesanta Software Limited
* All rights reserved
*/
#ifndef CS_MONGOOSE_SRC_NET_IF_SOCKS_H_
#define CS_MONGOOSE_SRC_NET_IF_SOCKS_H_
#if MG_ENABLE_SOCKS
/* Amalgamated: #include "mg_net_if.h" */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
extern const struct mg_iface_vtable mg_socks_iface_vtable;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* MG_ENABLE_SOCKS */
#endif /* CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_net_if.c"
#endif
/* Amalgamated: #include "mg_net_if.h" */
/* Amalgamated: #include "mg_internal.h" */
/* Amalgamated: #include "mg_net_if_socket.h" */
extern const struct mg_iface_vtable mg_default_iface_vtable;
const struct mg_iface_vtable *mg_ifaces[] = {
&mg_default_iface_vtable,
};
int mg_num_ifaces = (int) (sizeof(mg_ifaces) / sizeof(mg_ifaces[0]));
struct mg_iface *mg_if_create_iface(const struct mg_iface_vtable *vtable,
struct mg_mgr *mgr) {
struct mg_iface *iface = (struct mg_iface *) MG_CALLOC(1, sizeof(*iface));
iface->mgr = mgr;
iface->data = NULL;
iface->vtable = vtable;
return iface;
}
struct mg_iface *mg_find_iface(struct mg_mgr *mgr,
const struct mg_iface_vtable *vtable,
struct mg_iface *from) {
int i = 0;
if (from != NULL) {
for (i = 0; i < mgr->num_ifaces; i++) {
if (mgr->ifaces[i] == from) {
i++;
break;
}
}
}
for (; i < mgr->num_ifaces; i++) {
if (mgr->ifaces[i]->vtable == vtable) {
return mgr->ifaces[i];
}
}
return NULL;
}
double mg_mgr_min_timer(const struct mg_mgr *mgr) {
double min_timer = 0;
struct mg_connection *nc;
for (nc = mgr->active_connections; nc != NULL; nc = nc->next) {
if (nc->ev_timer_time <= 0) continue;
if (min_timer == 0 || nc->ev_timer_time < min_timer) {
min_timer = nc->ev_timer_time;
}
}
return min_timer;
}
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_net_if_null.c"
#endif
/*
* Copyright (c) 2018 Cesanta Software Limited
* All rights reserved
*
* This software is dual-licensed: 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. For the terms of this
* license, see <http://www.gnu.org/licenses/>.
*
* You are free to use this software under the terms of the GNU General
* Public License, 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.
*
* Alternatively, you can license this software under a commercial
* license, as set out in <https://www.cesanta.com/license>.
*/
static void mg_null_if_connect_tcp(struct mg_connection *c,
const union socket_address *sa) {
c->flags |= MG_F_CLOSE_IMMEDIATELY;
(void) sa;
}
static void mg_null_if_connect_udp(struct mg_connection *c) {
c->flags |= MG_F_CLOSE_IMMEDIATELY;
}
static int mg_null_if_listen_tcp(struct mg_connection *c,
union socket_address *sa) {
(void) c;
(void) sa;
return -1;
}
static int mg_null_if_listen_udp(struct mg_connection *c,
union socket_address *sa) {
(void) c;
(void) sa;
return -1;
}
static int mg_null_if_tcp_send(struct mg_connection *c, const void *buf,
size_t len) {
(void) c;
(void) buf;
(void) len;
return -1;
}
static int mg_null_if_udp_send(struct mg_connection *c, const void *buf,
size_t len) {
(void) c;
(void) buf;
(void) len;
return -1;
}
int mg_null_if_tcp_recv(struct mg_connection *c, void *buf, size_t len) {
(void) c;
(void) buf;
(void) len;
return -1;
}
int mg_null_if_udp_recv(struct mg_connection *c, void *buf, size_t len,
union socket_address *sa, size_t *sa_len) {
(void) c;
(void) buf;
(void) len;
(void) sa;
(void) sa_len;
return -1;
}
static int mg_null_if_create_conn(struct mg_connection *c) {
(void) c;
return 1;
}
static void mg_null_if_destroy_conn(struct mg_connection *c) {
(void) c;
}
static void mg_null_if_sock_set(struct mg_connection *c, sock_t sock) {
(void) c;
(void) sock;
}
static void mg_null_if_init(struct mg_iface *iface) {
(void) iface;
}
static void mg_null_if_free(struct mg_iface *iface) {
(void) iface;
}
static void mg_null_if_add_conn(struct mg_connection *c) {
c->sock = INVALID_SOCKET;
c->flags |= MG_F_CLOSE_IMMEDIATELY;
}
static void mg_null_if_remove_conn(struct mg_connection *c) {
(void) c;
}
static time_t mg_null_if_poll(struct mg_iface *iface, int timeout_ms) {
struct mg_mgr *mgr = iface->mgr;
struct mg_connection *nc, *tmp;
double now = mg_time();
/* We basically just run timers and poll. */
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
tmp = nc->next;
mg_if_poll(nc, now);
}
(void) timeout_ms;
return (time_t) now;
}
static void mg_null_if_get_conn_addr(struct mg_connection *c, int remote,
union socket_address *sa) {
(void) c;
(void) remote;
(void) sa;
}
#define MG_NULL_IFACE_VTABLE \
{ \
mg_null_if_init, mg_null_if_free, mg_null_if_add_conn, \
mg_null_if_remove_conn, mg_null_if_poll, mg_null_if_listen_tcp, \
mg_null_if_listen_udp, mg_null_if_connect_tcp, mg_null_if_connect_udp, \
mg_null_if_tcp_send, mg_null_if_udp_send, mg_null_if_tcp_recv, \
mg_null_if_udp_recv, mg_null_if_create_conn, mg_null_if_destroy_conn, \
mg_null_if_sock_set, mg_null_if_get_conn_addr, \
}
const struct mg_iface_vtable mg_null_iface_vtable = MG_NULL_IFACE_VTABLE;
#if MG_NET_IF == MG_NET_IF_NULL
const struct mg_iface_vtable mg_default_iface_vtable = MG_NULL_IFACE_VTABLE;
#endif /* MG_NET_IF == MG_NET_IF_NULL */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_net_if_socket.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_NET_IF_SOCKET
/* Amalgamated: #include "mg_net_if_socket.h" */
/* Amalgamated: #include "mg_internal.h" */
/* Amalgamated: #include "mg_util.h" */
static sock_t mg_open_listening_socket(union socket_address *sa, int type,
int proto);
void mg_set_non_blocking_mode(sock_t sock) {
#ifdef _WIN32
unsigned long on = 1;
ioctlsocket(sock, FIONBIO, &on);
#else
int flags = fcntl(sock, F_GETFL, 0);
fcntl(sock, F_SETFL, flags | O_NONBLOCK);
#endif
}
static int mg_is_error(void) {
int err = mg_get_errno();
return err != EINPROGRESS && err != EWOULDBLOCK
#ifndef WINCE
&& err != EAGAIN && err != EINTR
#endif
#ifdef _WIN32
&& WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK
#endif
;
}
void mg_socket_if_connect_tcp(struct mg_connection *nc,
const union socket_address *sa) {
int rc, proto = 0;
nc->sock = socket(AF_INET, SOCK_STREAM, proto);
if (nc->sock == INVALID_SOCKET) {
nc->err = mg_get_errno() ? mg_get_errno() : 1;
return;
}
#if !defined(MG_ESP8266)
mg_set_non_blocking_mode(nc->sock);
#endif
rc = connect(nc->sock, &sa->sa, sizeof(sa->sin));
nc->err = rc < 0 && mg_is_error() ? mg_get_errno() : 0;
DBG(("%p sock %d rc %d errno %d err %d", nc, nc->sock, rc, mg_get_errno(),
nc->err));
}
void mg_socket_if_connect_udp(struct mg_connection *nc) {
nc->sock = socket(AF_INET, SOCK_DGRAM, 0);
if (nc->sock == INVALID_SOCKET) {
nc->err = mg_get_errno() ? mg_get_errno() : 1;
return;
}
if (nc->flags & MG_F_ENABLE_BROADCAST) {
int optval = 1;
if (setsockopt(nc->sock, SOL_SOCKET, SO_BROADCAST, (const char *) &optval,
sizeof(optval)) < 0) {
nc->err = mg_get_errno() ? mg_get_errno() : 1;
return;
}
}
nc->err = 0;
}
int mg_socket_if_listen_tcp(struct mg_connection *nc,
union socket_address *sa) {
int proto = 0;
sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM, proto);
if (sock == INVALID_SOCKET) {
return (mg_get_errno() ? mg_get_errno() : 1);
}
mg_sock_set(nc, sock);
return 0;
}
static int mg_socket_if_listen_udp(struct mg_connection *nc,
union socket_address *sa) {
sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET) return (mg_get_errno() ? mg_get_errno() : 1);
mg_sock_set(nc, sock);
return 0;
}
static int mg_socket_if_tcp_send(struct mg_connection *nc, const void *buf,
size_t len) {
int n = (int) MG_SEND_FUNC(nc->sock, buf, len, 0);
if (n < 0 && !mg_is_error()) n = 0;
return n;
}
static int mg_socket_if_udp_send(struct mg_connection *nc, const void *buf,
size_t len) {
int n = sendto(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
if (n < 0 && !mg_is_error()) n = 0;
return n;
}
static int mg_socket_if_tcp_recv(struct mg_connection *nc, void *buf,
size_t len) {
int n = (int) MG_RECV_FUNC(nc->sock, buf, len, 0);
if (n == 0) {
/* Orderly shutdown of the socket, try flushing output. */
nc->flags |= MG_F_SEND_AND_CLOSE;
} else if (n < 0 && !mg_is_error()) {
n = 0;
}
return n;
}
static int mg_socket_if_udp_recv(struct mg_connection *nc, void *buf,
size_t len, union socket_address *sa,
size_t *sa_len) {
socklen_t sa_len_st = *sa_len;
int n = recvfrom(nc->sock, buf, len, 0, &sa->sa, &sa_len_st);
*sa_len = sa_len_st;
if (n < 0 && !mg_is_error()) n = 0;
return n;
}
int mg_socket_if_create_conn(struct mg_connection *nc) {
(void) nc;
return 1;
}
void mg_socket_if_destroy_conn(struct mg_connection *nc) {
if (nc->sock == INVALID_SOCKET) return;
if (!(nc->flags & MG_F_UDP)) {
closesocket(nc->sock);
} else {
/* Only close outgoing UDP sockets or listeners. */
if (nc->listener == NULL) closesocket(nc->sock);
}
nc->sock = INVALID_SOCKET;
}
static int mg_accept_conn(struct mg_connection *lc) {
struct mg_connection *nc;
union socket_address sa;
socklen_t sa_len = sizeof(sa);
/* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */
sock_t sock = accept(lc->sock, &sa.sa, &sa_len);
if (sock == INVALID_SOCKET) {
if (mg_is_error()) {
DBG(("%p: failed to accept: %d", lc, mg_get_errno()));
}
return 0;
}
nc = mg_if_accept_new_conn(lc);
if (nc == NULL) {
closesocket(sock);
return 0;
}
DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
ntohs(sa.sin.sin_port)));
mg_sock_set(nc, sock);
mg_if_accept_tcp_cb(nc, &sa, sa_len);
return 1;
}
/* 'sa' must be an initialized address to bind to */
static sock_t mg_open_listening_socket(union socket_address *sa, int type,
int proto) {
socklen_t sa_len =
(sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
sock_t sock = INVALID_SOCKET;
#if !MG_LWIP
int on = 1;
#endif
if ((sock = socket(sa->sa.sa_family, type, proto)) != INVALID_SOCKET &&
#if !MG_LWIP /* LWIP doesn't support either */
#if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE) && !defined(WINCE)
/* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */
!setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on,
sizeof(on)) &&
#endif
#if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE)
/*
* SO_RESUSEADDR is not enabled on Windows because the semantics of
* SO_REUSEADDR on UNIX and Windows is different. On Windows,
* SO_REUSEADDR allows to bind a socket to a port without error even if
* the port is already open by another program. This is not the behavior
* SO_REUSEADDR was designed for, and leads to hard-to-track failure
* scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless
* SO_EXCLUSIVEADDRUSE is supported and set on a socket.
*/
!setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
#endif
#endif /* !MG_LWIP */
!bind(sock, &sa->sa, sa_len) &&
(type == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
#if !MG_LWIP
mg_set_non_blocking_mode(sock);
/* In case port was set to 0, get the real port number */
(void) getsockname(sock, &sa->sa, &sa_len);
#endif
} else if (sock != INVALID_SOCKET) {
closesocket(sock);
sock = INVALID_SOCKET;
}
return sock;
}
#define _MG_F_FD_CAN_READ 1
#define _MG_F_FD_CAN_WRITE 1 << 1
#define _MG_F_FD_ERROR 1 << 2
void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
int worth_logging =
fd_flags != 0 || (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE));
if (worth_logging) {
DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock,
fd_flags, nc->flags, (int) nc->recv_mbuf.len,
(int) nc->send_mbuf.len));
}
if (!mg_if_poll(nc, now)) return;
if (nc->flags & MG_F_CONNECTING) {
if (fd_flags != 0) {
int err = 0;
#if !defined(MG_ESP8266)
if (!(nc->flags & MG_F_UDP)) {
socklen_t len = sizeof(err);
int ret =
getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
if (ret != 0) {
err = 1;
} else if (err == EAGAIN || err == EWOULDBLOCK) {
err = 0;
}
}
#else
/*
* On ESP8266 we use blocking connect.
*/
err = nc->err;
#endif
mg_if_connect_cb(nc, err);
} else if (nc->err != 0) {
mg_if_connect_cb(nc, nc->err);
}
}
if (fd_flags & _MG_F_FD_CAN_READ) {
if (nc->flags & MG_F_UDP) {
mg_if_can_recv_cb(nc);
} else {
if (nc->flags & MG_F_LISTENING) {
/*
* We're not looping here, and accepting just one connection at
* a time. The reason is that eCos does not respect non-blocking
* flag on a listening socket and hangs in a loop.
*/
mg_accept_conn(nc);
} else {
mg_if_can_recv_cb(nc);
}
}
}
if (fd_flags & _MG_F_FD_CAN_WRITE) mg_if_can_send_cb(nc);
if (worth_logging) {
DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock,
nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
}
}
#if MG_ENABLE_BROADCAST
static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) {
struct ctl_msg ctl_msg;
int len =
(int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0);
DBG(("read %d from ctl socket", len));
(void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
struct mg_connection *nc;
for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
ctl_msg.callback(nc, MG_EV_POLL,
ctl_msg.message MG_UD_ARG(nc->user_data));
}
}
}
#endif
/* Associate a socket to a connection. */
void mg_socket_if_sock_set(struct mg_connection *nc, sock_t sock) {
mg_set_non_blocking_mode(sock);
mg_set_close_on_exec(sock);
nc->sock = sock;
DBG(("%p %d", nc, sock));
}
void mg_socket_if_init(struct mg_iface *iface) {
(void) iface;
DBG(("%p using select()", iface->mgr));
#if MG_ENABLE_BROADCAST
mg_socketpair(iface->mgr->ctl, SOCK_DGRAM);
#endif
}
void mg_socket_if_free(struct mg_iface *iface) {
(void) iface;
}
void mg_socket_if_add_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_socket_if_remove_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
if (sock != INVALID_SOCKET
#ifdef __unix__
&& sock < (sock_t) FD_SETSIZE
#endif
) {
FD_SET(sock, set);
if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
*max_fd = sock;
}
}
}
time_t mg_socket_if_poll(struct mg_iface *iface, int timeout_ms) {
struct mg_mgr *mgr = iface->mgr;
double now = mg_time();
double min_timer;
struct mg_connection *nc, *tmp;
struct timeval tv;
fd_set read_set, write_set, err_set;
sock_t max_fd = INVALID_SOCKET;
int num_fds, num_ev, num_timers = 0;
#ifdef __unix__
int try_dup = 1;
#endif
FD_ZERO(&read_set);
FD_ZERO(&write_set);
FD_ZERO(&err_set);
#if MG_ENABLE_BROADCAST
mg_add_to_set(mgr->ctl[1], &read_set, &max_fd);
#endif
/*
* Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
* e.g. timer-only "connections".
*/
min_timer = 0;
for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
tmp = nc->next;
if (nc->sock != INVALID_SOCKET) {
num_fds++;
#ifdef __unix__
/* A hack to make sure all our file descriptos fit into FD_SETSIZE. */
if (nc->sock >= (sock_t) FD_SETSIZE && try_dup) {
int new_sock = dup(nc->sock);
if (new_sock >= 0) {
if (new_sock < (sock_t) FD_SETSIZE) {
closesocket(nc->sock);
DBG(("new sock %d -> %d", nc->sock, new_sock));
nc->sock = new_sock;
} else {
closesocket(new_sock);
DBG(("new sock is still larger than FD_SETSIZE, disregard"));
try_dup = 0;
}
} else {
try_dup = 0;
}
}
#endif
if (nc->recv_mbuf.len < nc->recv_mbuf_limit &&
(!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
mg_add_to_set(nc->sock, &read_set, &max_fd);
}
if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
(nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
mg_add_to_set(nc->sock, &write_set, &max_fd);
mg_add_to_set(nc->sock, &err_set, &max_fd);
}
}
if (nc->ev_timer_time > 0) {
if (num_timers == 0 || nc->ev_timer_time < min_timer) {
min_timer = nc->ev_timer_time;
}
num_timers++;
}
}
/*
* If there is a timer to be fired earlier than the requested timeout,
* adjust the timeout.
*/
if (num_timers > 0) {
double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
if (timer_timeout_ms < timeout_ms) {
timeout_ms = (int) timer_timeout_ms;
}
}
if (timeout_ms < 0) timeout_ms = 0;
tv.tv_sec = timeout_ms / 1000;
tv.tv_usec = (timeout_ms % 1000) * 1000;
num_ev = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
now = mg_time();
#if 0
DBG(("select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds,
timeout_ms));
#endif
#if MG_ENABLE_BROADCAST
if (num_ev > 0 && mgr->ctl[1] != INVALID_SOCKET &&
FD_ISSET(mgr->ctl[1], &read_set)) {
mg_mgr_handle_ctl_sock(mgr);
}
#endif
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
int fd_flags = 0;
if (nc->sock != INVALID_SOCKET) {
if (num_ev > 0) {
fd_flags = (FD_ISSET(nc->sock, &read_set) &&
(!(nc->flags & MG_F_UDP) || nc->listener == NULL)
? _MG_F_FD_CAN_READ
: 0) |
(FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
(FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
}
#if MG_LWIP
/* With LWIP socket emulation layer, we don't get write events for UDP */
if ((nc->flags & MG_F_UDP) && nc->listener == NULL) {
fd_flags |= _MG_F_FD_CAN_WRITE;
}
#endif
}
tmp = nc->next;
mg_mgr_handle_conn(nc, fd_flags, now);
}
return (time_t) now;
}
#if MG_ENABLE_BROADCAST
MG_INTERNAL void mg_socketpair_close(sock_t *sock) {
while (1) {
if (closesocket(*sock) == -1 && errno == EINTR) continue;
break;
}
*sock = INVALID_SOCKET;
}
MG_INTERNAL sock_t
mg_socketpair_accept(sock_t sock, union socket_address *sa, socklen_t sa_len) {
sock_t rc;
while (1) {
if ((rc = accept(sock, &sa->sa, &sa_len)) == INVALID_SOCKET &&
errno == EINTR)
continue;
break;
}
return rc;
}
int mg_socketpair(sock_t sp[2], int sock_type) {
union socket_address sa, sa2;
sock_t sock;
socklen_t len = sizeof(sa.sin);
int ret = 0;
sock = sp[0] = sp[1] = INVALID_SOCKET;
(void) memset(&sa, 0, sizeof(sa));
sa.sin.sin_family = AF_INET;
sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
sa2 = sa;
if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
} else if (bind(sock, &sa.sa, len) != 0) {
} else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) {
} else if (getsockname(sock, &sa.sa, &len) != 0) {
} else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
} else if (sock_type == SOCK_STREAM && connect(sp[0], &sa.sa, len) != 0) {
} else if (sock_type == SOCK_DGRAM &&
(bind(sp[0], &sa2.sa, len) != 0 ||
getsockname(sp[0], &sa2.sa, &len) != 0 ||
connect(sp[0], &sa.sa, len) != 0 ||
connect(sock, &sa2.sa, len) != 0)) {
} else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock : mg_socketpair_accept(
sock, &sa, len))) ==
INVALID_SOCKET) {
} else {
mg_set_close_on_exec(sp[0]);
mg_set_close_on_exec(sp[1]);
if (sock_type == SOCK_STREAM) mg_socketpair_close(&sock);
ret = 1;
}
if (!ret) {
if (sp[0] != INVALID_SOCKET) mg_socketpair_close(&sp[0]);
if (sp[1] != INVALID_SOCKET) mg_socketpair_close(&sp[1]);
if (sock != INVALID_SOCKET) mg_socketpair_close(&sock);
}
return ret;
}
#endif /* MG_ENABLE_BROADCAST */
static void mg_sock_get_addr(sock_t sock, int remote,
union socket_address *sa) {
socklen_t slen = sizeof(*sa);
memset(sa, 0, slen);
if (remote) {
getpeername(sock, &sa->sa, &slen);
} else {
getsockname(sock, &sa->sa, &slen);
}
}
void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
union socket_address sa;
mg_sock_get_addr(sock, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
mg_sock_addr_to_str(&sa, buf, len, flags);
}
void mg_socket_if_get_conn_addr(struct mg_connection *nc, int remote,
union socket_address *sa) {
if ((nc->flags & MG_F_UDP) && remote) {
memcpy(sa, &nc->sa, sizeof(*sa));
return;
}
mg_sock_get_addr(nc->sock, remote, sa);
}
/* clang-format off */
#define MG_SOCKET_IFACE_VTABLE \
{ \
mg_socket_if_init, \
mg_socket_if_free, \
mg_socket_if_add_conn, \
mg_socket_if_remove_conn, \
mg_socket_if_poll, \
mg_socket_if_listen_tcp, \
mg_socket_if_listen_udp, \
mg_socket_if_connect_tcp, \
mg_socket_if_connect_udp, \
mg_socket_if_tcp_send, \
mg_socket_if_udp_send, \
mg_socket_if_tcp_recv, \
mg_socket_if_udp_recv, \
mg_socket_if_create_conn, \
mg_socket_if_destroy_conn, \
mg_socket_if_sock_set, \
mg_socket_if_get_conn_addr, \
}
/* clang-format on */
const struct mg_iface_vtable mg_socket_iface_vtable = MG_SOCKET_IFACE_VTABLE;
#if MG_NET_IF == MG_NET_IF_SOCKET
const struct mg_iface_vtable mg_default_iface_vtable = MG_SOCKET_IFACE_VTABLE;
#endif
#endif /* MG_ENABLE_NET_IF_SOCKET */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_net_if_socks.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_SOCKS
struct socksdata {
char *proxy_addr; /* HOST:PORT of the socks5 proxy server */
struct mg_connection *s; /* Respective connection to the server */
struct mg_connection *c; /* Connection to the client */
};
static void socks_if_disband(struct socksdata *d) {
LOG(LL_DEBUG, ("disbanding proxy %p %p", d->c, d->s));
if (d->c) {
d->c->flags |= MG_F_SEND_AND_CLOSE;
d->c->user_data = NULL;
d->c = NULL;
}
if (d->s) {
d->s->flags |= MG_F_SEND_AND_CLOSE;
d->s->user_data = NULL;
d->s = NULL;
}
}
static void socks_if_relay(struct mg_connection *s) {
struct socksdata *d = (struct socksdata *) s->user_data;
if (d == NULL || d->c == NULL || !(s->flags & MG_SOCKS_CONNECT_DONE) ||
d->s == NULL) {
return;
}
if (s->recv_mbuf.len > 0) mg_if_can_recv_cb(d->c);
if (d->c->send_mbuf.len > 0 && s->send_mbuf.len == 0) mg_if_can_send_cb(d->c);
}
static void socks_if_handler(struct mg_connection *c, int ev, void *ev_data) {
struct socksdata *d = (struct socksdata *) c->user_data;
if (d == NULL) return;
if (ev == MG_EV_CONNECT) {
int res = *(int *) ev_data;
if (res == 0) {
/* Send handshake to the proxy server */
unsigned char buf[] = {MG_SOCKS_VERSION, 1, MG_SOCKS_HANDSHAKE_NOAUTH};
mg_send(d->s, buf, sizeof(buf));
LOG(LL_DEBUG, ("Sent handshake to %s", d->proxy_addr));
} else {
LOG(LL_ERROR, ("Cannot connect to %s: %d", d->proxy_addr, res));
d->c->flags |= MG_F_CLOSE_IMMEDIATELY;
}
} else if (ev == MG_EV_CLOSE) {
socks_if_disband(d);
} else if (ev == MG_EV_RECV) {
/* Handle handshake reply */
if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) {
/* TODO(lsm): process IPv6 too */
unsigned char buf[10] = {MG_SOCKS_VERSION, MG_SOCKS_CMD_CONNECT, 0,
MG_SOCKS_ADDR_IPV4};
if (c->recv_mbuf.len < 2) return;
if ((unsigned char) c->recv_mbuf.buf[1] == MG_SOCKS_HANDSHAKE_FAILURE) {
LOG(LL_ERROR, ("Server kicked us out"));
socks_if_disband(d);
return;
}
mbuf_remove(&c->recv_mbuf, 2);
c->flags |= MG_SOCKS_HANDSHAKE_DONE;
/* Send connect request */
memcpy(buf + 4, &d->c->sa.sin.sin_addr, 4);
memcpy(buf + 8, &d->c->sa.sin.sin_port, 2);
mg_send(c, buf, sizeof(buf));
LOG(LL_DEBUG, ("%p Sent connect request", c));
}
/* Process connect request */
if ((c->flags & MG_SOCKS_HANDSHAKE_DONE) &&
!(c->flags & MG_SOCKS_CONNECT_DONE)) {
if (c->recv_mbuf.len < 10) return;
if (c->recv_mbuf.buf[1] != MG_SOCKS_SUCCESS) {
LOG(LL_ERROR, ("Socks connection error: %d", c->recv_mbuf.buf[1]));
socks_if_disband(d);
return;
}
mbuf_remove(&c->recv_mbuf, 10);
c->flags |= MG_SOCKS_CONNECT_DONE;
LOG(LL_DEBUG, ("%p Connect done %p", c, d->c));
mg_if_connect_cb(d->c, 0);
}
socks_if_relay(c);
} else if (ev == MG_EV_SEND || ev == MG_EV_POLL) {
socks_if_relay(c);
}
}
static void mg_socks_if_connect_tcp(struct mg_connection *c,
const union socket_address *sa) {
struct socksdata *d = (struct socksdata *) c->iface->data;
d->c = c;
d->s = mg_connect(c->mgr, d->proxy_addr, socks_if_handler);
d->s->user_data = d;
LOG(LL_DEBUG, ("%p %s %p %p", c, d->proxy_addr, d, d->s));
(void) sa;
}
static void mg_socks_if_connect_udp(struct mg_connection *c) {
(void) c;
}
static int mg_socks_if_listen_tcp(struct mg_connection *c,
union socket_address *sa) {
(void) c;
(void) sa;
return 0;
}
static int mg_socks_if_listen_udp(struct mg_connection *c,
union socket_address *sa) {
(void) c;
(void) sa;
return -1;
}
static int mg_socks_if_tcp_send(struct mg_connection *c, const void *buf,
size_t len) {
int res;
struct socksdata *d = (struct socksdata *) c->iface->data;
if (d->s == NULL) return -1;
res = (int) mbuf_append(&d->s->send_mbuf, buf, len);
DBG(("%p -> %d -> %p", c, res, d->s));
return res;
}
static int mg_socks_if_udp_send(struct mg_connection *c, const void *buf,
size_t len) {
(void) c;
(void) buf;
(void) len;
return -1;
}
int mg_socks_if_tcp_recv(struct mg_connection *c, void *buf, size_t len) {
struct socksdata *d = (struct socksdata *) c->iface->data;
if (d->s == NULL) return -1;
if (len > d->s->recv_mbuf.len) len = d->s->recv_mbuf.len;
if (len > 0) {
memcpy(buf, d->s->recv_mbuf.buf, len);
mbuf_remove(&d->s->recv_mbuf, len);
}
DBG(("%p <- %d <- %p", c, (int) len, d->s));
return len;
}
int mg_socks_if_udp_recv(struct mg_connection *c, void *buf, size_t len,
union socket_address *sa, size_t *sa_len) {
(void) c;
(void) buf;
(void) len;
(void) sa;
(void) sa_len;
return -1;
}
static int mg_socks_if_create_conn(struct mg_connection *c) {
(void) c;
return 1;
}
static void mg_socks_if_destroy_conn(struct mg_connection *c) {
c->iface->vtable->free(c->iface);
MG_FREE(c->iface);
c->iface = NULL;
LOG(LL_DEBUG, ("%p", c));
}
static void mg_socks_if_sock_set(struct mg_connection *c, sock_t sock) {
(void) c;
(void) sock;
}
static void mg_socks_if_init(struct mg_iface *iface) {
(void) iface;
}
static void mg_socks_if_free(struct mg_iface *iface) {
struct socksdata *d = (struct socksdata *) iface->data;
LOG(LL_DEBUG, ("%p", iface));
if (d != NULL) {
socks_if_disband(d);
MG_FREE(d->proxy_addr);
MG_FREE(d);
iface->data = NULL;
}
}
static void mg_socks_if_add_conn(struct mg_connection *c) {
c->sock = INVALID_SOCKET;
}
static void mg_socks_if_remove_conn(struct mg_connection *c) {
(void) c;
}
static time_t mg_socks_if_poll(struct mg_iface *iface, int timeout_ms) {
LOG(LL_DEBUG, ("%p", iface));
(void) iface;
(void) timeout_ms;
return (time_t) cs_time();
}
static void mg_socks_if_get_conn_addr(struct mg_connection *c, int remote,
union socket_address *sa) {
LOG(LL_DEBUG, ("%p", c));
(void) c;
(void) remote;
(void) sa;
}
const struct mg_iface_vtable mg_socks_iface_vtable = {
mg_socks_if_init, mg_socks_if_free,
mg_socks_if_add_conn, mg_socks_if_remove_conn,
mg_socks_if_poll, mg_socks_if_listen_tcp,
mg_socks_if_listen_udp, mg_socks_if_connect_tcp,
mg_socks_if_connect_udp, mg_socks_if_tcp_send,
mg_socks_if_udp_send, mg_socks_if_tcp_recv,
mg_socks_if_udp_recv, mg_socks_if_create_conn,
mg_socks_if_destroy_conn, mg_socks_if_sock_set,
mg_socks_if_get_conn_addr,
};
struct mg_iface *mg_socks_mk_iface(struct mg_mgr *mgr, const char *proxy_addr) {
struct mg_iface *iface = mg_if_create_iface(&mg_socks_iface_vtable, mgr);
iface->data = MG_CALLOC(1, sizeof(struct socksdata));
((struct socksdata *) iface->data)->proxy_addr = strdup(proxy_addr);
return iface;
}
#endif
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_ssl_if_openssl.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL
#ifdef __APPLE__
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#include <openssl/ssl.h>
#ifndef KR_VERSION
#include <openssl/tls1.h>
#endif
struct mg_ssl_if_ctx {
SSL *ssl;
SSL_CTX *ssl_ctx;
struct mbuf psk;
size_t identity_len;
};
void mg_ssl_if_init() {
SSL_library_init();
}
enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
struct mg_connection *lc) {
struct mg_ssl_if_ctx *ctx =
(struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
nc->ssl_if_data = ctx;
if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
ctx->ssl_ctx = lc_ctx->ssl_ctx;
if ((ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
return MG_SSL_ERROR;
}
return MG_SSL_OK;
}
static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
const char *key, const char **err_msg);
static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert);
static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl);
static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
const char *identity,
const char *key_str);
enum mg_ssl_if_result mg_ssl_if_conn_init(
struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
const char **err_msg) {
struct mg_ssl_if_ctx *ctx =
(struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""),
(params->key ? params->key : ""),
(params->ca_cert ? params->ca_cert : "")));
if (ctx == NULL) {
MG_SET_PTRPTR(err_msg, "Out of memory");
return MG_SSL_ERROR;
}
nc->ssl_if_data = ctx;
if (nc->flags & MG_F_LISTENING) {
ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
} else {
ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
}
if (ctx->ssl_ctx == NULL) {
MG_SET_PTRPTR(err_msg, "Failed to create SSL context");
return MG_SSL_ERROR;
}
#ifndef KR_VERSION
/* Disable deprecated protocols. */
SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2);
SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv3);
SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_TLSv1);
#ifdef MG_SSL_OPENSSL_NO_COMPRESSION
SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
#endif
#ifdef MG_SSL_OPENSSL_CIPHER_SERVER_PREFERENCE
SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
#endif
#else
/* Krypton only supports TLSv1.2 anyway. */
#endif
if (params->cert != NULL &&
mg_use_cert(ctx->ssl_ctx, params->cert, params->key, err_msg) !=
MG_SSL_OK) {
return MG_SSL_ERROR;
}
if (params->ca_cert != NULL &&
mg_use_ca_cert(ctx->ssl_ctx, params->ca_cert) != MG_SSL_OK) {
MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
return MG_SSL_ERROR;
}
if (mg_set_cipher_list(ctx->ssl_ctx, params->cipher_suites) != MG_SSL_OK) {
MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
return MG_SSL_ERROR;
}
mbuf_init(&ctx->psk, 0);
if (mg_ssl_if_ossl_set_psk(ctx, params->psk_identity, params->psk_key) !=
MG_SSL_OK) {
MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
return MG_SSL_ERROR;
}
if (!(nc->flags & MG_F_LISTENING) &&
(ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
return MG_SSL_ERROR;
}
if (params->server_name != NULL) {
#ifdef KR_VERSION
SSL_CTX_kr_set_verify_name(ctx->ssl_ctx, params->server_name);
#else
SSL_set_tlsext_host_name(ctx->ssl, params->server_name);
#endif
}
nc->flags |= MG_F_SSL;
return MG_SSL_OK;
}
static enum mg_ssl_if_result mg_ssl_if_ssl_err(struct mg_connection *nc,
int res) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
int err = SSL_get_error(ctx->ssl, res);
if (err == SSL_ERROR_WANT_READ) return MG_SSL_WANT_READ;
if (err == SSL_ERROR_WANT_WRITE) return MG_SSL_WANT_WRITE;
DBG(("%p %p SSL error: %d %d", nc, ctx->ssl_ctx, res, err));
nc->err = err;
return MG_SSL_ERROR;
}
enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
int server_side = (nc->listener != NULL);
int res;
/* If descriptor is not yet set, do it now. */
if (SSL_get_fd(ctx->ssl) < 0) {
if (SSL_set_fd(ctx->ssl, nc->sock) != 1) return MG_SSL_ERROR;
}
res = server_side ? SSL_accept(ctx->ssl) : SSL_connect(ctx->ssl);
if (res != 1) return mg_ssl_if_ssl_err(nc, res);
return MG_SSL_OK;
}
int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
int n = SSL_read(ctx->ssl, buf, buf_size);
DBG(("%p %d -> %d", nc, (int) buf_size, n));
if (n < 0) return mg_ssl_if_ssl_err(nc, n);
if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return n;
}
int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
int n = SSL_write(ctx->ssl, data, len);
DBG(("%p %d -> %d", nc, (int) len, n));
if (n <= 0) return mg_ssl_if_ssl_err(nc, n);
return n;
}
void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
if (ctx == NULL) return;
SSL_shutdown(ctx->ssl);
}
void mg_ssl_if_conn_free(struct mg_connection *nc) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
if (ctx == NULL) return;
nc->ssl_if_data = NULL;
if (ctx->ssl != NULL) SSL_free(ctx->ssl);
if (ctx->ssl_ctx != NULL && nc->listener == NULL) SSL_CTX_free(ctx->ssl_ctx);
mbuf_free(&ctx->psk);
memset(ctx, 0, sizeof(*ctx));
MG_FREE(ctx);
}
/*
* Cipher suite options used for TLS negotiation.
* https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations
*/
static const char mg_s_cipher_list[] =
#if defined(MG_SSL_CRYPTO_MODERN)
"ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:"
"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:"
"DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
"ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
"ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
"ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
"DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
"DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
"!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK"
#elif defined(MG_SSL_CRYPTO_OLD)
"ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
"ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
"DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
"ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
"ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
"ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
"DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
"DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:"
"ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
"AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:"
"HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
"!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
#else /* Default - intermediate. */
"ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
"ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
"DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
"ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
"ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
"ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
"DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
"DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
"AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:"
"DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
"!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
#endif
;
/*
* Default DH params for PFS cipher negotiation. This is a 2048-bit group.
* Will be used if none are provided by the user in the certificate file.
*/
#if !MG_DISABLE_PFS && !defined(KR_VERSION)
static const char mg_s_default_dh_params[] =
"\
-----BEGIN DH PARAMETERS-----\n\
MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\
Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\
+E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\
ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\
wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\
9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\
-----END DH PARAMETERS-----\n";
#endif
static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert) {
if (cert == NULL || strcmp(cert, "*") == 0) {
return MG_SSL_OK;
}
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? MG_SSL_OK
: MG_SSL_ERROR;
}
static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
const char *key,
const char **err_msg) {
if (key == NULL) key = cert;
if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
return MG_SSL_OK;
} else if (SSL_CTX_use_certificate_file(ctx, cert, 1) == 0) {
MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
return MG_SSL_ERROR;
} else if (SSL_CTX_use_PrivateKey_file(ctx, key, 1) == 0) {
MG_SET_PTRPTR(err_msg, "Invalid SSL key");
return MG_SSL_ERROR;
} else if (SSL_CTX_use_certificate_chain_file(ctx, cert) == 0) {
MG_SET_PTRPTR(err_msg, "Invalid CA bundle");
return MG_SSL_ERROR;
} else {
SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
#if !MG_DISABLE_PFS && !defined(KR_VERSION)
BIO *bio = NULL;
DH *dh = NULL;
/* Try to read DH parameters from the cert/key file. */
bio = BIO_new_file(cert, "r");
if (bio != NULL) {
dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
BIO_free(bio);
}
/*
* If there are no DH params in the file, fall back to hard-coded ones.
* Not ideal, but better than nothing.
*/
if (dh == NULL) {
bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1);
dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
BIO_free(bio);
}
if (dh != NULL) {
SSL_CTX_set_tmp_dh(ctx, dh);
SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
DH_free(dh);
}
#if OPENSSL_VERSION_NUMBER > 0x10002000L
SSL_CTX_set_ecdh_auto(ctx, 1);
#endif
#endif
}
return MG_SSL_OK;
}
static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl) {
return (SSL_CTX_set_cipher_list(ctx, cl ? cl : mg_s_cipher_list) == 1
? MG_SSL_OK
: MG_SSL_ERROR);
}
#if !defined(KR_VERSION) && !defined(LIBRESSL_VERSION_NUMBER)
static unsigned int mg_ssl_if_ossl_psk_cb(SSL *ssl, const char *hint,
char *identity,
unsigned int max_identity_len,
unsigned char *psk,
unsigned int max_psk_len) {
struct mg_ssl_if_ctx *ctx =
(struct mg_ssl_if_ctx *) SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl));
size_t key_len = ctx->psk.len - ctx->identity_len - 1;
DBG(("hint: '%s'", (hint ? hint : "")));
if (ctx->identity_len + 1 > max_identity_len) {
DBG(("identity too long"));
return 0;
}
if (key_len > max_psk_len) {
DBG(("key too long"));
return 0;
}
memcpy(identity, ctx->psk.buf, ctx->identity_len + 1);
memcpy(psk, ctx->psk.buf + ctx->identity_len + 1, key_len);
(void) ssl;
return key_len;
}
static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
const char *identity,
const char *key_str) {
unsigned char key[32];
size_t key_len;
size_t i = 0;
if (identity == NULL && key_str == NULL) return MG_SSL_OK;
if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
key_len = strlen(key_str);
if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
memset(key, 0, sizeof(key));
key_len = 0;
for (i = 0; key_str[i] != '\0'; i++) {
unsigned char c;
char hc = tolower((int) key_str[i]);
if (hc >= '0' && hc <= '9') {
c = hc - '0';
} else if (hc >= 'a' && hc <= 'f') {
c = hc - 'a' + 0xa;
} else {
return MG_SSL_ERROR;
}
key_len = i / 2;
key[key_len] <<= 4;
key[key_len] |= c;
}
key_len++;
DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
ctx->identity_len = strlen(identity);
mbuf_append(&ctx->psk, identity, ctx->identity_len + 1);
mbuf_append(&ctx->psk, key, key_len);
SSL_CTX_set_psk_client_callback(ctx->ssl_ctx, mg_ssl_if_ossl_psk_cb);
SSL_CTX_set_app_data(ctx->ssl_ctx, ctx);
return MG_SSL_OK;
}
#else
static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
const char *identity,
const char *key_str) {
(void) ctx;
(void) identity;
(void) key_str;
/* Krypton / LibreSSL does not support PSK. */
return MG_SSL_ERROR;
}
#endif /* !defined(KR_VERSION) && !defined(LIBRESSL_VERSION_NUMBER) */
const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
const char *ca_cert) {
const char *err_msg = NULL;
struct mg_ssl_if_conn_params params;
memset(¶ms, 0, sizeof(params));
params.cert = cert;
params.ca_cert = ca_cert;
if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
return err_msg;
}
return NULL;
}
#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_ssl_if_mbedtls.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS
#include <mbedtls/debug.h>
#include <mbedtls/ecp.h>
#include <mbedtls/net.h>
#include <mbedtls/platform.h>
#include <mbedtls/ssl.h>
#include <mbedtls/ssl_internal.h>
#include <mbedtls/x509_crt.h>
#include <mbedtls/version.h>
static void mg_ssl_mbed_log(void *ctx, int level, const char *file, int line,
const char *str) {
enum cs_log_level cs_level;
switch (level) {
case 1:
cs_level = LL_ERROR;
break;
case 2:
cs_level = LL_INFO;
break;
case 3:
cs_level = LL_DEBUG;
break;
default:
cs_level = LL_VERBOSE_DEBUG;
}
/* mbedTLS passes strings with \n at the end, strip it. */
LOG(cs_level, ("%p %.*s", ctx, (int) (strlen(str) - 1), str));
(void) ctx;
(void) str;
(void) file;
(void) line;
(void) cs_level;
}
struct mg_ssl_if_ctx {
mbedtls_ssl_config *conf;
mbedtls_ssl_context *ssl;
mbedtls_x509_crt *cert;
mbedtls_pk_context *key;
mbedtls_x509_crt *ca_cert;
struct mbuf cipher_suites;
size_t saved_len;
};
/* Must be provided by the platform. ctx is struct mg_connection. */
extern int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len);
void mg_ssl_if_init() {
LOG(LL_INFO, ("%s", MBEDTLS_VERSION_STRING_FULL));
}
enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
struct mg_connection *lc) {
struct mg_ssl_if_ctx *ctx =
(struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
nc->ssl_if_data = ctx;
if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
if (mbedtls_ssl_setup(ctx->ssl, lc_ctx->conf) != 0) {
return MG_SSL_ERROR;
}
return MG_SSL_OK;
}
static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
const char *cert, const char *key,
const char **err_msg);
static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
const char *cert);
static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
const char *ciphers);
#ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
const char *identity,
const char *key);
#endif
enum mg_ssl_if_result mg_ssl_if_conn_init(
struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
const char **err_msg) {
struct mg_ssl_if_ctx *ctx =
(struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""),
(params->key ? params->key : ""),
(params->ca_cert ? params->ca_cert : "")));
if (ctx == NULL) {
MG_SET_PTRPTR(err_msg, "Out of memory");
return MG_SSL_ERROR;
}
nc->ssl_if_data = ctx;
ctx->conf = (mbedtls_ssl_config *) MG_CALLOC(1, sizeof(*ctx->conf));
mbuf_init(&ctx->cipher_suites, 0);
mbedtls_ssl_config_init(ctx->conf);
mbedtls_ssl_conf_dbg(ctx->conf, mg_ssl_mbed_log, nc);
if (mbedtls_ssl_config_defaults(
ctx->conf, (nc->flags & MG_F_LISTENING ? MBEDTLS_SSL_IS_SERVER
: MBEDTLS_SSL_IS_CLIENT),
MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) {
MG_SET_PTRPTR(err_msg, "Failed to init SSL config");
return MG_SSL_ERROR;
}
/* TLS 1.2 and up */
mbedtls_ssl_conf_min_version(ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
MBEDTLS_SSL_MINOR_VERSION_3);
mbedtls_ssl_conf_rng(ctx->conf, mg_ssl_if_mbed_random, nc);
if (params->cert != NULL &&
mg_use_cert(ctx, params->cert, params->key, err_msg) != MG_SSL_OK) {
return MG_SSL_ERROR;
}
if (params->ca_cert != NULL &&
mg_use_ca_cert(ctx, params->ca_cert) != MG_SSL_OK) {
MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
return MG_SSL_ERROR;
}
if (mg_set_cipher_list(ctx, params->cipher_suites) != MG_SSL_OK) {
MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
return MG_SSL_ERROR;
}
#ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
if (mg_ssl_if_mbed_set_psk(ctx, params->psk_identity, params->psk_key) !=
MG_SSL_OK) {
MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
return MG_SSL_ERROR;
}
#endif
if (!(nc->flags & MG_F_LISTENING)) {
ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
mbedtls_ssl_init(ctx->ssl);
if (mbedtls_ssl_setup(ctx->ssl, ctx->conf) != 0) {
MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
return MG_SSL_ERROR;
}
if (params->server_name != NULL &&
mbedtls_ssl_set_hostname(ctx->ssl, params->server_name) != 0) {
return MG_SSL_ERROR;
}
}
#ifdef MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
if (mbedtls_ssl_conf_max_frag_len(ctx->conf,
#if MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 512
MBEDTLS_SSL_MAX_FRAG_LEN_512
#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 1024
MBEDTLS_SSL_MAX_FRAG_LEN_1024
#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 2048
MBEDTLS_SSL_MAX_FRAG_LEN_2048
#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 4096
MBEDTLS_SSL_MAX_FRAG_LEN_4096
#else
#error Invalid MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
#endif
) != 0) {
return MG_SSL_ERROR;
}
#endif
nc->flags |= MG_F_SSL;
return MG_SSL_OK;
}
static int mg_ssl_if_mbed_send(void *ctx, const unsigned char *buf,
size_t len) {
struct mg_connection *nc = (struct mg_connection *) ctx;
int n = nc->iface->vtable->tcp_send(nc, buf, len);
if (n > 0) return n;
if (n == 0) return MBEDTLS_ERR_SSL_WANT_WRITE;
return MBEDTLS_ERR_NET_SEND_FAILED;
}
static int mg_ssl_if_mbed_recv(void *ctx, unsigned char *buf, size_t len) {
struct mg_connection *nc = (struct mg_connection *) ctx;
int n = nc->iface->vtable->tcp_recv(nc, buf, len);
if (n > 0) return n;
if (n == 0) return MBEDTLS_ERR_SSL_WANT_READ;
return MBEDTLS_ERR_NET_RECV_FAILED;
}
static enum mg_ssl_if_result mg_ssl_if_mbed_err(struct mg_connection *nc,
int ret) {
enum mg_ssl_if_result res = MG_SSL_OK;
if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
res = MG_SSL_WANT_READ;
} else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
res = MG_SSL_WANT_WRITE;
} else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
LOG(LL_DEBUG, ("%p TLS connection closed by peer", nc));
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
res = MG_SSL_OK;
} else {
LOG(LL_ERROR, ("%p mbedTLS error: -0x%04x", nc, -ret));
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
res = MG_SSL_ERROR;
}
nc->err = ret;
return res;
}
static void mg_ssl_if_mbed_free_certs_and_keys(struct mg_ssl_if_ctx *ctx) {
if (ctx->cert != NULL) {
mbedtls_x509_crt_free(ctx->cert);
MG_FREE(ctx->cert);
ctx->cert = NULL;
mbedtls_pk_free(ctx->key);
MG_FREE(ctx->key);
ctx->key = NULL;
}
if (ctx->ca_cert != NULL) {
mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
#ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK
if (ctx->conf->ca_chain_file != NULL) {
MG_FREE((void *) ctx->conf->ca_chain_file);
ctx->conf->ca_chain_file = NULL;
}
#endif
mbedtls_x509_crt_free(ctx->ca_cert);
MG_FREE(ctx->ca_cert);
ctx->ca_cert = NULL;
}
}
enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
int err;
/* If bio is not yet set, do it now. */
if (ctx->ssl->p_bio == NULL) {
mbedtls_ssl_set_bio(ctx->ssl, nc, mg_ssl_if_mbed_send, mg_ssl_if_mbed_recv,
NULL);
}
err = mbedtls_ssl_handshake(ctx->ssl);
if (err != 0) return mg_ssl_if_mbed_err(nc, err);
#ifdef MG_SSL_IF_MBEDTLS_FREE_CERTS
/*
* Free the peer certificate, we don't need it after handshake.
* Note that this effectively disables renegotiation.
*/
mbedtls_x509_crt_free(ctx->ssl->session->peer_cert);
mbedtls_free(ctx->ssl->session->peer_cert);
ctx->ssl->session->peer_cert = NULL;
/* On a client connection we can also free our own and CA certs. */
if (nc->listener == NULL) {
if (ctx->conf->key_cert != NULL) {
/* Note that this assumes one key_cert entry, which matches our init. */
MG_FREE(ctx->conf->key_cert);
ctx->conf->key_cert = NULL;
}
mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
mg_ssl_if_mbed_free_certs_and_keys(ctx);
}
#endif
return MG_SSL_OK;
}
int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
int n = mbedtls_ssl_read(ctx->ssl, (unsigned char *) buf, len);
DBG(("%p %d -> %d", nc, (int) len, n));
if (n < 0) return mg_ssl_if_mbed_err(nc, n);
if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return n;
}
int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
/* Per mbedTLS docs, if write returns WANT_READ or WANT_WRITE, the operation
* should be retried with the same data and length.
* Here we assume that the data being pushed will remain the same but the
* amount may grow between calls so we save the length that was used and
* retry. The assumption being that the data itself won't change and won't
* be removed. */
size_t l = len;
if (ctx->saved_len > 0 && ctx->saved_len < l) l = ctx->saved_len;
int n = mbedtls_ssl_write(ctx->ssl, (const unsigned char *) buf, l);
DBG(("%p %d,%d,%d -> %d", nc, (int) len, (int) ctx->saved_len, (int) l, n));
if (n < 0) {
if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE) {
ctx->saved_len = len;
}
return mg_ssl_if_mbed_err(nc, n);
} else if (n > 0) {
ctx->saved_len = 0;
}
return n;
}
void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
if (ctx == NULL) return;
mbedtls_ssl_close_notify(ctx->ssl);
}
void mg_ssl_if_conn_free(struct mg_connection *nc) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
if (ctx == NULL) return;
nc->ssl_if_data = NULL;
if (ctx->ssl != NULL) {
mbedtls_ssl_free(ctx->ssl);
MG_FREE(ctx->ssl);
}
mg_ssl_if_mbed_free_certs_and_keys(ctx);
if (ctx->conf != NULL) {
mbedtls_ssl_config_free(ctx->conf);
MG_FREE(ctx->conf);
}
mbuf_free(&ctx->cipher_suites);
memset(ctx, 0, sizeof(*ctx));
MG_FREE(ctx);
}
static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
const char *ca_cert) {
if (ca_cert == NULL || strcmp(ca_cert, "*") == 0) {
mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
return MG_SSL_OK;
}
ctx->ca_cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->ca_cert));
mbedtls_x509_crt_init(ctx->ca_cert);
#ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK
ca_cert = strdup(ca_cert);
mbedtls_ssl_conf_ca_chain_file(ctx->conf, ca_cert, NULL);
#else
if (mbedtls_x509_crt_parse_file(ctx->ca_cert, ca_cert) != 0) {
return MG_SSL_ERROR;
}
mbedtls_ssl_conf_ca_chain(ctx->conf, ctx->ca_cert, NULL);
#endif
mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
return MG_SSL_OK;
}
static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
const char *cert, const char *key,
const char **err_msg) {
if (key == NULL) key = cert;
if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
return MG_SSL_OK;
}
ctx->cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->cert));
mbedtls_x509_crt_init(ctx->cert);
ctx->key = (mbedtls_pk_context *) MG_CALLOC(1, sizeof(*ctx->key));
mbedtls_pk_init(ctx->key);
if (mbedtls_x509_crt_parse_file(ctx->cert, cert) != 0) {
MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
return MG_SSL_ERROR;
}
if (mbedtls_pk_parse_keyfile(ctx->key, key, NULL) != 0) {
MG_SET_PTRPTR(err_msg, "Invalid SSL key");
return MG_SSL_ERROR;
}
if (mbedtls_ssl_conf_own_cert(ctx->conf, ctx->cert, ctx->key) != 0) {
MG_SET_PTRPTR(err_msg, "Invalid SSL key or cert");
return MG_SSL_ERROR;
}
return MG_SSL_OK;
}
static const int mg_s_cipher_list[] = {
#if CS_PLATFORM != CS_P_ESP8266
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
#else
/*
* ECDHE is way too slow on ESP8266 w/o cryptochip, this sometimes results
* in WiFi STA deauths. Use weaker but faster cipher suites. Sad but true.
* Disable DHE completely because it's just hopelessly slow.
*/
MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
#endif /* CS_PLATFORM != CS_P_ESP8266 */
0,
};
/*
* Ciphers can be specified as a colon-separated list of cipher suite names.
* These can be found in
* https://github.com/ARMmbed/mbedtls/blob/development/library/ssl_ciphersuites.c#L267
* E.g.: TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-256-CCM
*/
static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
const char *ciphers) {
if (ciphers != NULL) {
int l, id;
const char *s = ciphers, *e;
char tmp[50];
while (s != NULL) {
e = strchr(s, ':');
l = (e != NULL ? (e - s) : (int) strlen(s));
strncpy(tmp, s, l);
tmp[l] = '\0';
id = mbedtls_ssl_get_ciphersuite_id(tmp);
DBG(("%s -> %04x", tmp, id));
if (id != 0) {
mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
}
s = (e != NULL ? e + 1 : NULL);
}
if (ctx->cipher_suites.len == 0) return MG_SSL_ERROR;
id = 0;
mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
mbuf_trim(&ctx->cipher_suites);
mbedtls_ssl_conf_ciphersuites(ctx->conf,
(const int *) ctx->cipher_suites.buf);
} else {
mbedtls_ssl_conf_ciphersuites(ctx->conf, mg_s_cipher_list);
}
return MG_SSL_OK;
}
#ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
const char *identity,
const char *key_str) {
unsigned char key[32];
size_t key_len;
if (identity == NULL && key_str == NULL) return MG_SSL_OK;
if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
key_len = strlen(key_str);
if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
size_t i = 0;
memset(key, 0, sizeof(key));
key_len = 0;
for (i = 0; key_str[i] != '\0'; i++) {
unsigned char c;
char hc = tolower((int) key_str[i]);
if (hc >= '0' && hc <= '9') {
c = hc - '0';
} else if (hc >= 'a' && hc <= 'f') {
c = hc - 'a' + 0xa;
} else {
return MG_SSL_ERROR;
}
key_len = i / 2;
key[key_len] <<= 4;
key[key_len] |= c;
}
key_len++;
DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
/* mbedTLS makes copies of psk and identity. */
if (mbedtls_ssl_conf_psk(ctx->conf, (const unsigned char *) key, key_len,
(const unsigned char *) identity,
strlen(identity)) != 0) {
return MG_SSL_ERROR;
}
return MG_SSL_OK;
}
#endif
const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
const char *ca_cert) {
const char *err_msg = NULL;
struct mg_ssl_if_conn_params params;
memset(¶ms, 0, sizeof(params));
params.cert = cert;
params.ca_cert = ca_cert;
if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
return err_msg;
}
return NULL;
}
/* Lazy RNG. Warning: it would be a bad idea to do this in production! */
#ifdef MG_SSL_MBED_DUMMY_RANDOM
int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len) {
(void) ctx;
while (len--) *buf++ = rand();
return 0;
}
#endif
#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_uri.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
/* Amalgamated: #include "mg_internal.h" */
/* Amalgamated: #include "mg_uri.h" */
/*
* scan string until encountering one of `seps`, keeping track of component
* boundaries in `res`.
*
* `p` will point to the char after the separator or it will be `end`.
*/
static void parse_uri_component(const char **p, const char *end,
const char *seps, struct mg_str *res) {
const char *q;
res->p = *p;
for (; *p < end; (*p)++) {
for (q = seps; *q != '\0'; q++) {
if (**p == *q) break;
}
if (*q != '\0') break;
}
res->len = (*p) - res->p;
if (*p < end) (*p)++;
}
int mg_parse_uri(const struct mg_str uri, struct mg_str *scheme,
struct mg_str *user_info, struct mg_str *host,
unsigned int *port, struct mg_str *path, struct mg_str *query,
struct mg_str *fragment) {
struct mg_str rscheme = {0, 0}, ruser_info = {0, 0}, rhost = {0, 0},
rpath = {0, 0}, rquery = {0, 0}, rfragment = {0, 0};
unsigned int rport = 0;
enum {
P_START,
P_SCHEME_OR_PORT,
P_USER_INFO,
P_HOST,
P_PORT,
P_REST
} state = P_START;
const char *p = uri.p, *end = p + uri.len;
while (p < end) {
switch (state) {
case P_START:
/*
* expecting on of:
* - `scheme://xxxx`
* - `xxxx:port`
* - `[a:b:c]:port`
* - `xxxx/path`
*/
if (*p == '[') {
state = P_HOST;
break;
}
for (; p < end; p++) {
if (*p == ':') {
state = P_SCHEME_OR_PORT;
break;
} else if (*p == '/') {
state = P_REST;
break;
}
}
if (state == P_START || state == P_REST) {
rhost.p = uri.p;
rhost.len = p - uri.p;
}
break;
case P_SCHEME_OR_PORT:
if (end - p >= 3 && strncmp(p, "://", 3) == 0) {
rscheme.p = uri.p;
rscheme.len = p - uri.p;
state = P_USER_INFO;
p += 3;
} else {
rhost.p = uri.p;
rhost.len = p - uri.p;
state = P_PORT;
}
break;
case P_USER_INFO:
ruser_info.p = p;
for (; p < end; p++) {
if (*p == '@' || *p == '[' || *p == '/') {
break;
}
}
if (p == end || *p == '/' || *p == '[') {
/* backtrack and parse as host */
p = ruser_info.p;
}
ruser_info.len = p - ruser_info.p;
state = P_HOST;
break;
case P_HOST:
if (*p == '@') p++;
rhost.p = p;
if (*p == '[') {
int found = 0;
for (; !found && p < end; p++) {
found = (*p == ']');
}
if (!found) return -1;
} else {
for (; p < end; p++) {
if (*p == ':' || *p == '/') break;
}
}
rhost.len = p - rhost.p;
if (p < end) {
if (*p == ':') {
state = P_PORT;
break;
} else if (*p == '/') {
state = P_REST;
break;
}
}
break;
case P_PORT:
p++;
for (; p < end; p++) {
if (*p == '/') {
state = P_REST;
break;
}
rport *= 10;
rport += *p - '0';
}
break;
case P_REST:
/* `p` points to separator. `path` includes the separator */
parse_uri_component(&p, end, "?#", &rpath);
if (p < end && *(p - 1) == '?') {
parse_uri_component(&p, end, "#", &rquery);
}
parse_uri_component(&p, end, "", &rfragment);
break;
}
}
if (scheme != 0) *scheme = rscheme;
if (user_info != 0) *user_info = ruser_info;
if (host != 0) *host = rhost;
if (port != 0) *port = rport;
if (path != 0) *path = rpath;
if (query != 0) *query = rquery;
if (fragment != 0) *fragment = rfragment;
return 0;
}
/* Normalize the URI path. Remove/resolve "." and "..". */
int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out) {
const char *s = in->p, *se = s + in->len;
char *cp = (char *) out->p, *d;
if (in->len == 0 || *s != '/') {
out->len = 0;
return 0;
}
d = cp;
while (s < se) {
const char *next = s;
struct mg_str component;
parse_uri_component(&next, se, "/", &component);
if (mg_vcmp(&component, ".") == 0) {
/* Yum. */
} else if (mg_vcmp(&component, "..") == 0) {
/* Backtrack to previous slash. */
if (d > cp + 1 && *(d - 1) == '/') d--;
while (d > cp && *(d - 1) != '/') d--;
} else {
memmove(d, s, next - s);
d += next - s;
}
s = next;
}
if (d == cp) *d++ = '/';
out->p = cp;
out->len = d - cp;
return 1;
}
int mg_assemble_uri(const struct mg_str *scheme, const struct mg_str *user_info,
const struct mg_str *host, unsigned int port,
const struct mg_str *path, const struct mg_str *query,
const struct mg_str *fragment, int normalize_path,
struct mg_str *uri) {
int result = -1;
struct mbuf out;
mbuf_init(&out, 0);
if (scheme != NULL && scheme->len > 0) {
mbuf_append(&out, scheme->p, scheme->len);
mbuf_append(&out, "://", 3);
}
if (user_info != NULL && user_info->len > 0) {
mbuf_append(&out, user_info->p, user_info->len);
mbuf_append(&out, "@", 1);
}
if (host != NULL && host->len > 0) {
mbuf_append(&out, host->p, host->len);
}
if (port != 0) {
char port_str[20];
int port_str_len = sprintf(port_str, ":%u", port);
mbuf_append(&out, port_str, port_str_len);
}
if (path != NULL && path->len > 0) {
if (normalize_path) {
struct mg_str npath = mg_strdup(*path);
if (npath.len != path->len) goto out;
if (!mg_normalize_uri_path(path, &npath)) {
free((void *) npath.p);
goto out;
}
mbuf_append(&out, npath.p, npath.len);
free((void *) npath.p);
} else {
mbuf_append(&out, path->p, path->len);
}
} else if (normalize_path) {
mbuf_append(&out, "/", 1);
}
if (query != NULL && query->len > 0) {
mbuf_append(&out, "?", 1);
mbuf_append(&out, query->p, query->len);
}
if (fragment != NULL && fragment->len > 0) {
mbuf_append(&out, "#", 1);
mbuf_append(&out, fragment->p, fragment->len);
}
result = 0;
out:
if (result == 0) {
uri->p = out.buf;
uri->len = out.len;
} else {
mbuf_free(&out);
uri->p = NULL;
uri->len = 0;
}
return result;
}
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_http.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_HTTP
/* Amalgamated: #include "common/cs_md5.h" */
/* Amalgamated: #include "mg_internal.h" */
/* Amalgamated: #include "mg_util.h" */
/* altbuf {{{ */
/*
* Alternate buffer: fills the client-provided buffer with data; and if it's
* not large enough, allocates another buffer (via mbuf), similar to asprintf.
*/
struct altbuf {
struct mbuf m;
char *user_buf;
size_t len;
size_t user_buf_size;
};
/*
* Initializes altbuf; `buf`, `buf_size` is the client-provided buffer.
*/
MG_INTERNAL void altbuf_init(struct altbuf *ab, char *buf, size_t buf_size) {
mbuf_init(&ab->m, 0);
ab->user_buf = buf;
ab->user_buf_size = buf_size;
ab->len = 0;
}
/*
* Appends a single char to the altbuf.
*/
MG_INTERNAL void altbuf_append(struct altbuf *ab, char c) {
if (ab->len < ab->user_buf_size) {
/* The data fits into the original buffer */
ab->user_buf[ab->len++] = c;
} else {
/* The data can't fit into the original buffer, so write it to mbuf. */
/*
* First of all, see if that's the first byte which overflows the original
* buffer: if so, copy the existing data from there to a newly allocated
* mbuf.
*/
if (ab->len > 0 && ab->m.len == 0) {
mbuf_append(&ab->m, ab->user_buf, ab->len);
}
mbuf_append(&ab->m, &c, 1);
ab->len = ab->m.len;
}
}
/*
* Resets any data previously appended to altbuf.
*/
MG_INTERNAL void altbuf_reset(struct altbuf *ab) {
mbuf_free(&ab->m);
ab->len = 0;
}
/*
* Returns whether the additional buffer was allocated (and thus the data
* is in the mbuf, not the client-provided buffer)
*/
MG_INTERNAL int altbuf_reallocated(struct altbuf *ab) {
return ab->len > ab->user_buf_size;
}
/*
* Returns the actual buffer with data, either the client-provided or a newly
* allocated one. If `trim` is non-zero, mbuf-backed buffer is trimmed first.
*/
MG_INTERNAL char *altbuf_get_buf(struct altbuf *ab, int trim) {
if (altbuf_reallocated(ab)) {
if (trim) {
mbuf_trim(&ab->m);
}
return ab->m.buf;
} else {
return ab->user_buf;
}
}
/* }}} */
static const char *mg_version_header = "Mongoose/" MG_VERSION;
enum mg_http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT };
struct mg_http_proto_data_file {
FILE *fp; /* Opened file. */
int64_t cl; /* Content-Length. How many bytes to send. */
int64_t sent; /* How many bytes have been already sent. */
int keepalive; /* Keep connection open after sending. */
enum mg_http_proto_data_type type;
};
#if MG_ENABLE_HTTP_CGI
struct mg_http_proto_data_cgi {
struct mg_connection *cgi_nc;
};
#endif
struct mg_http_proto_data_chuncked {
int64_t body_len; /* How many bytes of chunked body was reassembled. */
};
struct mg_http_endpoint {
struct mg_http_endpoint *next;
struct mg_str uri_pattern; /* owned */
char *auth_domain; /* owned */
char *auth_file; /* owned */
mg_event_handler_t handler;
#if MG_ENABLE_CALLBACK_USERDATA
void *user_data;
#endif
};
enum mg_http_multipart_stream_state {
MPS_BEGIN,
MPS_WAITING_FOR_BOUNDARY,
MPS_WAITING_FOR_CHUNK,
MPS_GOT_BOUNDARY,
MPS_FINALIZE,
MPS_FINISHED
};
struct mg_http_multipart_stream {
const char *boundary;
int boundary_len;
const char *var_name;
const char *file_name;
void *user_data;
enum mg_http_multipart_stream_state state;
int processing_part;
int data_avail;
};
struct mg_reverse_proxy_data {
struct mg_connection *linked_conn;
};
struct mg_ws_proto_data {
/*
* Defragmented size of the frame so far.
*
* First byte of nc->recv_mbuf.buf is an op, the rest of the data is
* defragmented data.
*/
size_t reass_len;
};
struct mg_http_proto_data {
#if MG_ENABLE_FILESYSTEM
struct mg_http_proto_data_file file;
#endif
#if MG_ENABLE_HTTP_CGI
struct mg_http_proto_data_cgi cgi;
#endif
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
struct mg_http_multipart_stream mp_stream;
#endif
#if MG_ENABLE_HTTP_WEBSOCKET
struct mg_ws_proto_data ws_data;
#endif
struct mg_http_proto_data_chuncked chunk;
struct mg_http_endpoint *endpoints;
mg_event_handler_t endpoint_handler;
struct mg_reverse_proxy_data reverse_proxy_data;
size_t rcvd; /* How many bytes we have received. */
};
static void mg_http_proto_data_destructor(void *proto_data);
struct mg_connection *mg_connect_http_base(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
struct mg_connect_opts opts, const char *scheme1, const char *scheme2,
const char *scheme_ssl1, const char *scheme_ssl2, const char *url,
struct mg_str *path, struct mg_str *user_info, struct mg_str *host);
MG_INTERNAL struct mg_http_proto_data *mg_http_create_proto_data(
struct mg_connection *c) {
/* If we have proto data from previous connection, flush it. */
if (c->proto_data != NULL) {
void *pd = c->proto_data;
c->proto_data = NULL;
mg_http_proto_data_destructor(pd);
}
c->proto_data = MG_CALLOC(1, sizeof(struct mg_http_proto_data));
c->proto_data_destructor = mg_http_proto_data_destructor;
return (struct mg_http_proto_data *) c->proto_data;
}
static struct mg_http_proto_data *mg_http_get_proto_data(
struct mg_connection *c) {
return (struct mg_http_proto_data *) c->proto_data;
}
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
static void mg_http_free_proto_data_mp_stream(
struct mg_http_multipart_stream *mp) {
MG_FREE((void *) mp->boundary);
MG_FREE((void *) mp->var_name);
MG_FREE((void *) mp->file_name);
memset(mp, 0, sizeof(*mp));
}
#endif
#if MG_ENABLE_FILESYSTEM
static void mg_http_free_proto_data_file(struct mg_http_proto_data_file *d) {
if (d != NULL) {
if (d->fp != NULL) {
fclose(d->fp);
}
memset(d, 0, sizeof(struct mg_http_proto_data_file));
}
}
#endif
static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep) {
struct mg_http_endpoint *current = *ep;
while (current != NULL) {
struct mg_http_endpoint *tmp = current->next;
MG_FREE((void *) current->uri_pattern.p);
MG_FREE((void *) current->auth_domain);
MG_FREE((void *) current->auth_file);
MG_FREE(current);
current = tmp;
}
ep = NULL;
}
static void mg_http_free_reverse_proxy_data(struct mg_reverse_proxy_data *rpd) {
if (rpd->linked_conn != NULL) {
/*
* Connection has linked one, we have to unlink & close it
* since _this_ connection is going to die and
* it doesn't make sense to keep another one
*/
struct mg_http_proto_data *pd = mg_http_get_proto_data(rpd->linked_conn);
if (pd->reverse_proxy_data.linked_conn != NULL) {
pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
pd->reverse_proxy_data.linked_conn = NULL;
}
rpd->linked_conn = NULL;
}
}
static void mg_http_proto_data_destructor(void *proto_data) {
struct mg_http_proto_data *pd = (struct mg_http_proto_data *) proto_data;
#if MG_ENABLE_FILESYSTEM
mg_http_free_proto_data_file(&pd->file);
#endif
#if MG_ENABLE_HTTP_CGI
mg_http_free_proto_data_cgi(&pd->cgi);
#endif
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
mg_http_free_proto_data_mp_stream(&pd->mp_stream);
#endif
mg_http_free_proto_data_endpoints(&pd->endpoints);
mg_http_free_reverse_proxy_data(&pd->reverse_proxy_data);
MG_FREE(proto_data);
}
#if MG_ENABLE_FILESYSTEM
#define MIME_ENTRY(_ext, _type) \
{ _ext, sizeof(_ext) - 1, _type }
static const struct {
const char *extension;
size_t ext_len;
const char *mime_type;
} mg_static_builtin_mime_types[] = {
MIME_ENTRY("html", "text/html"),
MIME_ENTRY("html", "text/html"),
MIME_ENTRY("htm", "text/html"),
MIME_ENTRY("shtm", "text/html"),
MIME_ENTRY("shtml", "text/html"),
MIME_ENTRY("css", "text/css"),
MIME_ENTRY("js", "application/x-javascript"),
MIME_ENTRY("ico", "image/x-icon"),
MIME_ENTRY("gif", "image/gif"),
MIME_ENTRY("jpg", "image/jpeg"),
MIME_ENTRY("jpeg", "image/jpeg"),
MIME_ENTRY("png", "image/png"),
MIME_ENTRY("svg", "image/svg+xml"),
MIME_ENTRY("txt", "text/plain"),
MIME_ENTRY("torrent", "application/x-bittorrent"),
MIME_ENTRY("wav", "audio/x-wav"),
MIME_ENTRY("mp3", "audio/x-mp3"),
MIME_ENTRY("mid", "audio/mid"),
MIME_ENTRY("m3u", "audio/x-mpegurl"),
MIME_ENTRY("ogg", "application/ogg"),
MIME_ENTRY("ram", "audio/x-pn-realaudio"),
MIME_ENTRY("xml", "text/xml"),
MIME_ENTRY("ttf", "application/x-font-ttf"),
MIME_ENTRY("json", "application/json"),
MIME_ENTRY("xslt", "application/xml"),
MIME_ENTRY("xsl", "application/xml"),
MIME_ENTRY("ra", "audio/x-pn-realaudio"),
MIME_ENTRY("doc", "application/msword"),
MIME_ENTRY("exe", "application/octet-stream"),
MIME_ENTRY("zip", "application/x-zip-compressed"),
MIME_ENTRY("xls", "application/excel"),
MIME_ENTRY("tgz", "application/x-tar-gz"),
MIME_ENTRY("tar", "application/x-tar"),
MIME_ENTRY("gz", "application/x-gunzip"),
MIME_ENTRY("arj", "application/x-arj-compressed"),
MIME_ENTRY("rar", "application/x-rar-compressed"),
MIME_ENTRY("rtf", "application/rtf"),
MIME_ENTRY("pdf", "application/pdf"),
MIME_ENTRY("swf", "application/x-shockwave-flash"),
MIME_ENTRY("mpg", "video/mpeg"),
MIME_ENTRY("webm", "video/webm"),
MIME_ENTRY("mpeg", "video/mpeg"),
MIME_ENTRY("mov", "video/quicktime"),
MIME_ENTRY("mp4", "video/mp4"),
MIME_ENTRY("m4v", "video/x-m4v"),
MIME_ENTRY("asf", "video/x-ms-asf"),
MIME_ENTRY("avi", "video/x-msvideo"),
MIME_ENTRY("bmp", "image/bmp"),
{NULL, 0, NULL}};
static struct mg_str mg_get_mime_type(const char *path, const char *dflt,
const struct mg_serve_http_opts *opts) {
const char *ext, *overrides;
size_t i, path_len;
struct mg_str r, k, v;
path_len = strlen(path);
overrides = opts->custom_mime_types;
while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) {
ext = path + (path_len - k.len);
if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) {
return v;
}
}
for (i = 0; mg_static_builtin_mime_types[i].extension != NULL; i++) {
ext = path + (path_len - mg_static_builtin_mime_types[i].ext_len);
if (path_len > mg_static_builtin_mime_types[i].ext_len && ext[-1] == '.' &&
mg_casecmp(ext, mg_static_builtin_mime_types[i].extension) == 0) {
r.p = mg_static_builtin_mime_types[i].mime_type;
r.len = strlen(r.p);
return r;
}
}
r.p = dflt;
r.len = strlen(r.p);
return r;
}
#endif
/*
* Check whether full request is buffered. Return:
* -1 if request is malformed
* 0 if request is not yet fully buffered
* >0 actual request length, including last \r\n\r\n
*/
static int mg_http_get_request_len(const char *s, int buf_len) {
const unsigned char *buf = (unsigned char *) s;
int i;
for (i = 0; i < buf_len; i++) {
if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
return -1;
} else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
return i + 2;
} else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
buf[i + 2] == '\n') {
return i + 3;
}
}
return 0;
}
static const char *mg_http_parse_headers(const char *s, const char *end,
int len, struct http_message *req) {
int i = 0;
while (i < (int) ARRAY_SIZE(req->header_names) - 1) {
struct mg_str *k = &req->header_names[i], *v = &req->header_values[i];
s = mg_skip(s, end, ": ", k);
s = mg_skip(s, end, "\r\n", v);
while (v->len > 0 && v->p[v->len - 1] == ' ') {
v->len--; /* Trim trailing spaces in header value */
}
/*
* If header value is empty - skip it and go to next (if any).
* NOTE: Do not add it to headers_values because such addition changes API
* behaviour
*/
if (k->len != 0 && v->len == 0) {
continue;
}
if (k->len == 0 || v->len == 0) {
k->p = v->p = NULL;
k->len = v->len = 0;
break;
}
if (!mg_ncasecmp(k->p, "Content-Length", 14)) {
req->body.len = (size_t) to64(v->p);
req->message.len = len + req->body.len;
}
i++;
}
return s;
}
int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) {
const char *end, *qs;
int len = mg_http_get_request_len(s, n);
if (len <= 0) return len;
memset(hm, 0, sizeof(*hm));
hm->message.p = s;
hm->body.p = s + len;
hm->message.len = hm->body.len = (size_t) ~0;
end = s + len;
/* Request is fully buffered. Skip leading whitespaces. */
while (s < end && isspace(*(unsigned char *) s)) s++;
if (is_req) {
/* Parse request line: method, URI, proto */
s = mg_skip(s, end, " ", &hm->method);
s = mg_skip(s, end, " ", &hm->uri);
s = mg_skip(s, end, "\r\n", &hm->proto);
if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1;
/* If URI contains '?' character, initialize query_string */
if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) {
hm->query_string.p = qs + 1;
hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1);
hm->uri.len = qs - hm->uri.p;
}
} else {
s = mg_skip(s, end, " ", &hm->proto);
if (end - s < 4 || s[3] != ' ') return -1;
hm->resp_code = atoi(s);
if (hm->resp_code < 100 || hm->resp_code >= 600) return -1;
s += 4;
s = mg_skip(s, end, "\r\n", &hm->resp_status_msg);
}
s = mg_http_parse_headers(s, end, len, hm);
/*
* mg_parse_http() is used to parse both HTTP requests and HTTP
* responses. If HTTP response does not have Content-Length set, then
* body is read until socket is closed, i.e. body.len is infinite (~0).
*
* For HTTP requests though, according to
* http://tools.ietf.org/html/rfc7231#section-8.1.3,
* only POST and PUT methods have defined body semantics.
* Therefore, if Content-Length is not specified and methods are
* not one of PUT or POST, set body length to 0.
*
* So,
* if it is HTTP request, and Content-Length is not set,
* and method is not (PUT or POST) then reset body length to zero.
*/
if (hm->body.len == (size_t) ~0 && is_req &&
mg_vcasecmp(&hm->method, "PUT") != 0 &&
mg_vcasecmp(&hm->method, "POST") != 0) {
hm->body.len = 0;
hm->message.len = len;
}
return len;
}
struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) {
size_t i, len = strlen(name);
for (i = 0; hm->header_names[i].len > 0; i++) {
struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i];
if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len))
return v;
}
return NULL;
}
#if MG_ENABLE_FILESYSTEM
static void mg_http_transfer_file_data(struct mg_connection *nc) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
char buf[MG_MAX_HTTP_SEND_MBUF];
size_t n = 0, to_read = 0, left = (size_t)(pd->file.cl - pd->file.sent);
if (pd->file.type == DATA_FILE) {
struct mbuf *io = &nc->send_mbuf;
if (io->len >= MG_MAX_HTTP_SEND_MBUF) {
to_read = 0;
} else {
to_read = MG_MAX_HTTP_SEND_MBUF - io->len;
}
if (to_read > left) {
to_read = left;
}
if (to_read > 0) {
n = mg_fread(buf, 1, to_read, pd->file.fp);
if (n > 0) {
mg_send(nc, buf, n);
pd->file.sent += n;
DBG(("%p sent %d (total %d)", nc, (int) n, (int) pd->file.sent));
}
} else {
/* Rate-limited */
}
if (pd->file.sent >= pd->file.cl) {
LOG(LL_DEBUG, ("%p done, %d bytes, ka %d", nc, (int) pd->file.sent,
pd->file.keepalive));
if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
mg_http_free_proto_data_file(&pd->file);
}
} else if (pd->file.type == DATA_PUT) {
struct mbuf *io = &nc->recv_mbuf;
size_t to_write = left <= 0 ? 0 : left < io->len ? (size_t) left : io->len;
size_t n = mg_fwrite(io->buf, 1, to_write, pd->file.fp);
if (n > 0) {
mbuf_remove(io, n);
pd->file.sent += n;
}
if (n == 0 || pd->file.sent >= pd->file.cl) {
if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
mg_http_free_proto_data_file(&pd->file);
}
}
#if MG_ENABLE_HTTP_CGI
else if (pd->cgi.cgi_nc != NULL) {
/* This is POST data that needs to be forwarded to the CGI process */
if (pd->cgi.cgi_nc != NULL) {
mg_forward(nc, pd->cgi.cgi_nc);
} else {
nc->flags |= MG_F_SEND_AND_CLOSE;
}
}
#endif
}
#endif /* MG_ENABLE_FILESYSTEM */
/*
* Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or
* if it's incomplete. If the chunk is fully buffered, return total number of
* bytes in a chunk, and store data in `data`, `data_len`.
*/
static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data,
size_t *chunk_len) {
unsigned char *s = (unsigned char *) buf;
size_t n = 0; /* scanned chunk length */
size_t i = 0; /* index in s */
/* Scan chunk length. That should be a hexadecimal number. */
while (i < len && isxdigit(s[i])) {
n *= 16;
n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10;
i++;
if (i > 6) {
/* Chunk size is unreasonable. */
return 0;
}
}
/* Skip new line */
if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
return 0;
}
i += 2;
/* Record where the data is */
*chunk_data = (char *) s + i;
*chunk_len = n;
/* Skip data */
i += n;
/* Skip new line */
if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
return 0;
}
return i + 2;
}
MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
struct http_message *hm, char *buf,
size_t blen) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
char *data;
size_t i, n, data_len, body_len, zero_chunk_received = 0;
/* Find out piece of received data that is not yet reassembled */
body_len = (size_t) pd->chunk.body_len;
assert(blen >= body_len);
/* Traverse all fully buffered chunks */
for (i = body_len;
(n = mg_http_parse_chunk(buf + i, blen - i, &data, &data_len)) > 0;
i += n) {
/* Collapse chunk data to the rest of HTTP body */
memmove(buf + body_len, data, data_len);
body_len += data_len;
hm->body.len = body_len;
if (data_len == 0) {
zero_chunk_received = 1;
i += n;
break;
}
}
if (i > body_len) {
/* Shift unparsed content to the parsed body */
assert(i <= blen);
memmove(buf + body_len, buf + i, blen - i);
memset(buf + body_len + blen - i, 0, i - body_len);
nc->recv_mbuf.len -= i - body_len;
pd->chunk.body_len = body_len;
/* Send MG_EV_HTTP_CHUNK event */
nc->flags &= ~MG_F_DELETE_CHUNK;
mg_call(nc, nc->handler, nc->user_data, MG_EV_HTTP_CHUNK, hm);
/* Delete processed data if user set MG_F_DELETE_CHUNK flag */
if (nc->flags & MG_F_DELETE_CHUNK) {
memset(buf, 0, body_len);
memmove(buf, buf + body_len, blen - i);
nc->recv_mbuf.len -= body_len;
hm->body.len = 0;
pd->chunk.body_len = 0;
}
if (zero_chunk_received) {
/* Total message size is len(body) + len(headers) */
hm->message.len =
(size_t) pd->chunk.body_len + blen - i + (hm->body.p - hm->message.p);
}
}
return body_len;
}
struct mg_http_endpoint *mg_http_get_endpoint_handler(struct mg_connection *nc,
struct mg_str *uri_path) {
struct mg_http_proto_data *pd;
struct mg_http_endpoint *ret = NULL;
int matched, matched_max = 0;
struct mg_http_endpoint *ep;
if (nc == NULL) return NULL;
pd = mg_http_get_proto_data(nc);
if (pd == NULL) return NULL;
ep = pd->endpoints;
while (ep != NULL) {
if ((matched = mg_match_prefix_n(ep->uri_pattern, *uri_path)) > 0) {
if (matched > matched_max) {
/* Looking for the longest suitable handler */
ret = ep;
matched_max = matched;
}
}
ep = ep->next;
}
return ret;
}
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
static void mg_http_multipart_continue(struct mg_connection *nc);
static void mg_http_multipart_begin(struct mg_connection *nc,
struct http_message *hm, int req_len);
#endif
static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
struct http_message *hm);
static void deliver_chunk(struct mg_connection *c, struct http_message *hm,
int req_len) {
/* Incomplete message received. Send MG_EV_HTTP_CHUNK event */
hm->body.len = c->recv_mbuf.len - req_len;
c->flags &= ~MG_F_DELETE_CHUNK;
mg_call(c, c->handler, c->user_data, MG_EV_HTTP_CHUNK, hm);
/* Delete processed data if user set MG_F_DELETE_CHUNK flag */
if (c->flags & MG_F_DELETE_CHUNK) c->recv_mbuf.len = req_len;
}
/*
* lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here)
* If a big structure is declared in a big function, lx106 gcc will make it
* even bigger (round up to 4k, from 700 bytes of actual size).
*/
#ifdef __xtensa__
static void mg_http_handler2(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data),
struct http_message *hm) __attribute__((noinline));
void mg_http_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct http_message hm;
mg_http_handler2(nc, ev, ev_data MG_UD_ARG(user_data), &hm);
}
static void mg_http_handler2(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data),
struct http_message *hm) {
#else /* !__XTENSA__ */
void mg_http_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct http_message shm, *hm = &shm;
#endif /* __XTENSA__ */
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
struct mbuf *io = &nc->recv_mbuf;
int req_len;
const int is_req = (nc->listener != NULL);
#if MG_ENABLE_HTTP_WEBSOCKET
struct mg_str *vec;
#endif
if (ev == MG_EV_CLOSE) {
#if MG_ENABLE_HTTP_CGI
/* Close associated CGI forwarder connection */
if (pd != NULL && pd->cgi.cgi_nc != NULL) {
pd->cgi.cgi_nc->user_data = NULL;
pd->cgi.cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
#endif
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
if (pd != NULL && pd->mp_stream.boundary != NULL) {
/*
* Multipart message is in progress, but connection is closed.
* Finish part and request with an error flag.
*/
struct mg_http_multipart_part mp;
memset(&mp, 0, sizeof(mp));
mp.status = -1;
mp.var_name = pd->mp_stream.var_name;
mp.file_name = pd->mp_stream.file_name;
mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
nc->user_data, MG_EV_HTTP_PART_END, &mp);
mp.var_name = NULL;
mp.file_name = NULL;
mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
nc->user_data, MG_EV_HTTP_MULTIPART_REQUEST_END, &mp);
} else
#endif
if (io->len > 0 &&
(req_len = mg_parse_http(io->buf, io->len, hm, is_req)) > 0) {
/*
* For HTTP messages without Content-Length, always send HTTP message
* before MG_EV_CLOSE message.
*/
int ev2 = is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
hm->message.len = io->len;
hm->body.len = io->buf + io->len - hm->body.p;
deliver_chunk(nc, hm, req_len);
mg_http_call_endpoint_handler(nc, ev2, hm);
}
if (pd != NULL && pd->endpoint_handler != NULL &&
pd->endpoint_handler != nc->handler) {
mg_call(nc, pd->endpoint_handler, nc->user_data, ev, NULL);
}
}
#if MG_ENABLE_FILESYSTEM
if (pd != NULL && pd->file.fp != NULL) {
mg_http_transfer_file_data(nc);
}
#endif
mg_call(nc, nc->handler, nc->user_data, ev, ev_data);
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
if (pd != NULL && pd->mp_stream.boundary != NULL &&
(ev == MG_EV_RECV || ev == MG_EV_POLL)) {
if (ev == MG_EV_RECV) {
pd->rcvd += *(int *) ev_data;
mg_http_multipart_continue(nc);
} else if (pd->mp_stream.data_avail) {
/* Try re-delivering the data. */
mg_http_multipart_continue(nc);
}
return;
}
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
if (ev == MG_EV_RECV) {
struct mg_str *s;
again:
req_len = mg_parse_http(io->buf, io->len, hm, is_req);
if (req_len > 0) {
/* New request - new proto data */
pd = mg_http_create_proto_data(nc);
pd->rcvd = io->len;
}
if (req_len > 0 &&
(s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL &&
mg_vcasecmp(s, "chunked") == 0) {
mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len);
}
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
if (req_len > 0 && (s = mg_get_http_header(hm, "Content-Type")) != NULL &&
s->len >= 9 && strncmp(s->p, "multipart", 9) == 0) {
mg_http_multipart_begin(nc, hm, req_len);
mg_http_multipart_continue(nc);
return;
}
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
/* TODO(alashkin): refactor this ifelseifelseifelseifelse */
if ((req_len < 0 ||
(req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE))) {
DBG(("invalid request"));
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
} else if (req_len == 0) {
/* Do nothing, request is not yet fully buffered */
}
#if MG_ENABLE_HTTP_WEBSOCKET
else if (nc->listener == NULL && (nc->flags & MG_F_IS_WEBSOCKET)) {
/* We're websocket client, got handshake response from server. */
DBG(("%p WebSocket upgrade code %d", nc, hm->resp_code));
if (hm->resp_code == 101 &&
mg_get_http_header(hm, "Sec-WebSocket-Accept")) {
/* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */
mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
hm);
mbuf_remove(io, req_len);
nc->proto_handler = mg_ws_handler;
mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data));
} else {
mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
hm);
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
mbuf_remove(io, req_len);
}
} else if (nc->listener != NULL &&
(vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) {
struct mg_http_endpoint *ep;
/* This is a websocket request. Switch protocol handlers. */
mbuf_remove(io, req_len);
nc->proto_handler = mg_ws_handler;
nc->flags |= MG_F_IS_WEBSOCKET;
/*
* If we have a handler set up with mg_register_http_endpoint(),
* deliver subsequent websocket events to this handler after the
* protocol switch.
*/
ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
if (ep != NULL) {
nc->handler = ep->handler;
#if MG_ENABLE_CALLBACK_USERDATA
nc->user_data = ep->user_data;
#endif
}
/* Send handshake */
mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST,
hm);
if (!(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_SEND_AND_CLOSE))) {
if (nc->send_mbuf.len == 0) {
mg_ws_handshake(nc, vec, hm);
}
mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
hm);
mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data));
}
}
#endif /* MG_ENABLE_HTTP_WEBSOCKET */
else if (hm->message.len > pd->rcvd) {
/* Not yet received all HTTP body, deliver MG_EV_HTTP_CHUNK */
deliver_chunk(nc, hm, req_len);
if (nc->recv_mbuf_limit > 0 && nc->recv_mbuf.len >= nc->recv_mbuf_limit) {
LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit "
"%lu bytes, and not drained, closing",
nc, (unsigned long) nc->recv_mbuf.len,
(unsigned long) nc->recv_mbuf_limit));
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
} else {
/* We did receive all HTTP body. */
int request_done = 1;
int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
char addr[32];
mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr),
MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
DBG(("%p %s %.*s %.*s", nc, addr, (int) hm->method.len, hm->method.p,
(int) hm->uri.len, hm->uri.p));
deliver_chunk(nc, hm, req_len);
/* Whole HTTP message is fully buffered, call event handler */
mg_http_call_endpoint_handler(nc, trigger_ev, hm);
mbuf_remove(io, hm->message.len);
pd->rcvd -= hm->message.len;
#if MG_ENABLE_FILESYSTEM
/* We don't have a generic mechanism of communicating that we are done
* responding to a request (should probably add one). But if we are
* serving
* a file, we are definitely not done. */
if (pd->file.fp != NULL) request_done = 0;
#endif
#if MG_ENABLE_HTTP_CGI
/* If this is a CGI request, we are not done either. */
if (pd->cgi.cgi_nc != NULL) request_done = 0;
#endif
if (request_done && io->len > 0) goto again;
}
}
}
static size_t mg_get_line_len(const char *buf, size_t buf_len) {
size_t len = 0;
while (len < buf_len && buf[len] != '\n') len++;
return len == buf_len ? 0 : len + 1;
}
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
static void mg_http_multipart_begin(struct mg_connection *nc,
struct http_message *hm, int req_len) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
struct mg_str *ct;
struct mbuf *io = &nc->recv_mbuf;
char boundary_buf[100];
char *boundary = boundary_buf;
int boundary_len;
ct = mg_get_http_header(hm, "Content-Type");
if (ct == NULL) {
/* We need more data - or it isn't multipart mesage */
goto exit_mp;
}
/* Content-type should start with "multipart" */
if (ct->len < 9 || strncmp(ct->p, "multipart", 9) != 0) {
goto exit_mp;
}
boundary_len =
mg_http_parse_header2(ct, "boundary", &boundary, sizeof(boundary_buf));
if (boundary_len == 0) {
/*
* Content type is multipart, but there is no boundary,
* probably malformed request
*/
nc->flags = MG_F_CLOSE_IMMEDIATELY;
DBG(("invalid request"));
goto exit_mp;
}
/* If we reach this place - that is multipart request */
if (pd->mp_stream.boundary != NULL) {
/*
* Another streaming request was in progress,
* looks like protocol error
*/
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
} else {
struct mg_http_endpoint *ep = NULL;
pd->mp_stream.state = MPS_BEGIN;
pd->mp_stream.boundary = strdup(boundary);
pd->mp_stream.boundary_len = strlen(boundary);
pd->mp_stream.var_name = pd->mp_stream.file_name = NULL;
pd->endpoint_handler = nc->handler;
ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
if (ep != NULL) {
pd->endpoint_handler = ep->handler;
}
mg_http_call_endpoint_handler(nc, MG_EV_HTTP_MULTIPART_REQUEST, hm);
mbuf_remove(io, req_len);
}
exit_mp:
if (boundary != boundary_buf) MG_FREE(boundary);
}
#define CONTENT_DISPOSITION "Content-Disposition: "
static size_t mg_http_multipart_call_handler(struct mg_connection *c, int ev,
const char *data,
size_t data_len) {
struct mg_http_multipart_part mp;
struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
memset(&mp, 0, sizeof(mp));
mp.var_name = pd->mp_stream.var_name;
mp.file_name = pd->mp_stream.file_name;
mp.user_data = pd->mp_stream.user_data;
mp.data.p = data;
mp.data.len = data_len;
mp.num_data_consumed = data_len;
mg_call(c, pd->endpoint_handler, c->user_data, ev, &mp);
pd->mp_stream.user_data = mp.user_data;
pd->mp_stream.data_avail = (mp.num_data_consumed != data_len);
return mp.num_data_consumed;
}
static int mg_http_multipart_finalize(struct mg_connection *c) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
MG_FREE((void *) pd->mp_stream.file_name);
pd->mp_stream.file_name = NULL;
MG_FREE((void *) pd->mp_stream.var_name);
pd->mp_stream.var_name = NULL;
mg_http_multipart_call_handler(c, MG_EV_HTTP_MULTIPART_REQUEST_END, NULL, 0);
mg_http_free_proto_data_mp_stream(&pd->mp_stream);
pd->mp_stream.state = MPS_FINISHED;
return 1;
}
static int mg_http_multipart_wait_for_boundary(struct mg_connection *c) {
const char *boundary;
struct mbuf *io = &c->recv_mbuf;
struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
if (pd->mp_stream.boundary == NULL) {
pd->mp_stream.state = MPS_FINALIZE;
DBG(("Invalid request: boundary not initialized"));
return 0;
}
if ((int) io->len < pd->mp_stream.boundary_len + 2) {
return 0;
}
boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
if (boundary != NULL) {
const char *boundary_end = (boundary + pd->mp_stream.boundary_len);
if (io->len - (boundary_end - io->buf) < 4) {
return 0;
}
if (strncmp(boundary_end, "--\r\n", 4) == 0) {
pd->mp_stream.state = MPS_FINALIZE;
mbuf_remove(io, (boundary_end - io->buf) + 4);
} else {
pd->mp_stream.state = MPS_GOT_BOUNDARY;
}
} else {
return 0;
}
return 1;
}
static void mg_http_parse_header_internal(struct mg_str *hdr,
const char *var_name,
struct altbuf *ab);
static int mg_http_multipart_process_boundary(struct mg_connection *c) {
int data_size;
const char *boundary, *block_begin;
struct mbuf *io = &c->recv_mbuf;
struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
struct altbuf ab_file_name, ab_var_name;
int line_len;
boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
block_begin = boundary + pd->mp_stream.boundary_len + 2;
data_size = io->len - (block_begin - io->buf);
altbuf_init(&ab_file_name, NULL, 0);
altbuf_init(&ab_var_name, NULL, 0);
while (data_size > 0 &&
(line_len = mg_get_line_len(block_begin, data_size)) != 0) {
if (line_len > (int) sizeof(CONTENT_DISPOSITION) &&
mg_ncasecmp(block_begin, CONTENT_DISPOSITION,
sizeof(CONTENT_DISPOSITION) - 1) == 0) {
struct mg_str header;
header.p = block_begin + sizeof(CONTENT_DISPOSITION) - 1;
header.len = line_len - sizeof(CONTENT_DISPOSITION) - 1;
altbuf_reset(&ab_var_name);
mg_http_parse_header_internal(&header, "name", &ab_var_name);
altbuf_reset(&ab_file_name);
mg_http_parse_header_internal(&header, "filename", &ab_file_name);
block_begin += line_len;
data_size -= line_len;
continue;
}
if (line_len == 2 && mg_ncasecmp(block_begin, "\r\n", 2) == 0) {
mbuf_remove(io, block_begin - io->buf + 2);
if (pd->mp_stream.processing_part != 0) {
mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
}
/* Reserve 2 bytes for "\r\n" in file_name and var_name */
altbuf_append(&ab_file_name, '\0');
altbuf_append(&ab_file_name, '\0');
altbuf_append(&ab_var_name, '\0');
altbuf_append(&ab_var_name, '\0');
MG_FREE((void *) pd->mp_stream.file_name);
pd->mp_stream.file_name = altbuf_get_buf(&ab_file_name, 1 /* trim */);
MG_FREE((void *) pd->mp_stream.var_name);
pd->mp_stream.var_name = altbuf_get_buf(&ab_var_name, 1 /* trim */);
mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_BEGIN, NULL, 0);
pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
pd->mp_stream.processing_part++;
return 1;
}
block_begin += line_len;
}
pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
altbuf_reset(&ab_var_name);
altbuf_reset(&ab_file_name);
return 0;
}
static int mg_http_multipart_continue_wait_for_chunk(struct mg_connection *c) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
struct mbuf *io = &c->recv_mbuf;
const char *boundary;
if ((int) io->len < pd->mp_stream.boundary_len + 6 /* \r\n, --, -- */) {
return 0;
}
boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
if (boundary == NULL) {
int data_len = (io->len - (pd->mp_stream.boundary_len + 6));
if (data_len > 0) {
size_t consumed = mg_http_multipart_call_handler(
c, MG_EV_HTTP_PART_DATA, io->buf, (size_t) data_len);
mbuf_remove(io, consumed);
}
return 0;
} else if (boundary != NULL) {
size_t data_len = ((size_t)(boundary - io->buf) - 4);
size_t consumed = mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA,
io->buf, data_len);
mbuf_remove(io, consumed);
if (consumed == data_len) {
mbuf_remove(io, 4);
pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
static void mg_http_multipart_continue(struct mg_connection *c) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
while (1) {
switch (pd->mp_stream.state) {
case MPS_BEGIN: {
pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
break;
}
case MPS_WAITING_FOR_BOUNDARY: {
if (mg_http_multipart_wait_for_boundary(c) == 0) {
return;
}
break;
}
case MPS_GOT_BOUNDARY: {
if (mg_http_multipart_process_boundary(c) == 0) {
return;
}
break;
}
case MPS_WAITING_FOR_CHUNK: {
if (mg_http_multipart_continue_wait_for_chunk(c) == 0) {
return;
}
break;
}
case MPS_FINALIZE: {
if (mg_http_multipart_finalize(c) == 0) {
return;
}
break;
}
case MPS_FINISHED: {
return;
}
}
}
}
struct file_upload_state {
char *lfn;
size_t num_recd;
FILE *fp;
};
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
void mg_set_protocol_http_websocket(struct mg_connection *nc) {
nc->proto_handler = mg_http_handler;
}
const char *mg_status_message(int status_code) {
switch (status_code) {
case 206:
return "Partial Content";
case 301:
return "Moved";
case 302:
return "Found";
case 400:
return "Bad Request";
case 401:
return "Unauthorized";
case 403:
return "Forbidden";
case 404:
return "Not Found";
case 416:
return "Requested Range Not Satisfiable";
case 418:
return "I'm a teapot";
case 500:
return "Internal Server Error";
case 502:
return "Bad Gateway";
case 503:
return "Service Unavailable";
#if MG_ENABLE_EXTRA_ERRORS_DESC
case 100:
return "Continue";
case 101:
return "Switching Protocols";
case 102:
return "Processing";
case 200:
return "OK";
case 201:
return "Created";
case 202:
return "Accepted";
case 203:
return "Non-Authoritative Information";
case 204:
return "No Content";
case 205:
return "Reset Content";
case 207:
return "Multi-Status";
case 208:
return "Already Reported";
case 226:
return "IM Used";
case 300:
return "Multiple Choices";
case 303:
return "See Other";
case 304:
return "Not Modified";
case 305:
return "Use Proxy";
case 306:
return "Switch Proxy";
case 307:
return "Temporary Redirect";
case 308:
return "Permanent Redirect";
case 402:
return "Payment Required";
case 405:
return "Method Not Allowed";
case 406:
return "Not Acceptable";
case 407:
return "Proxy Authentication Required";
case 408:
return "Request Timeout";
case 409:
return "Conflict";
case 410:
return "Gone";
case 411:
return "Length Required";
case 412:
return "Precondition Failed";
case 413:
return "Payload Too Large";
case 414:
return "URI Too Long";
case 415:
return "Unsupported Media Type";
case 417:
return "Expectation Failed";
case 422:
return "Unprocessable Entity";
case 423:
return "Locked";
case 424:
return "Failed Dependency";
case 426:
return "Upgrade Required";
case 428:
return "Precondition Required";
case 429:
return "Too Many Requests";
case 431:
return "Request Header Fields Too Large";
case 451:
return "Unavailable For Legal Reasons";
case 501:
return "Not Implemented";
case 504:
return "Gateway Timeout";
case 505:
return "HTTP Version Not Supported";
case 506:
return "Variant Also Negotiates";
case 507:
return "Insufficient Storage";
case 508:
return "Loop Detected";
case 510:
return "Not Extended";
case 511:
return "Network Authentication Required";
#endif /* MG_ENABLE_EXTRA_ERRORS_DESC */
default:
return "OK";
}
}
void mg_send_response_line_s(struct mg_connection *nc, int status_code,
const struct mg_str extra_headers) {
mg_printf(nc, "HTTP/1.1 %d %s\r\n", status_code,
mg_status_message(status_code));
#ifndef MG_HIDE_SERVER_INFO
mg_printf(nc, "Server: %s\r\n", mg_version_header);
#endif
if (extra_headers.len > 0) {
mg_printf(nc, "%.*s\r\n", (int) extra_headers.len, extra_headers.p);
}
}
void mg_send_response_line(struct mg_connection *nc, int status_code,
const char *extra_headers) {
mg_send_response_line_s(nc, status_code, mg_mk_str(extra_headers));
}
void mg_http_send_redirect(struct mg_connection *nc, int status_code,
const struct mg_str location,
const struct mg_str extra_headers) {
char bbody[100], *pbody = bbody;
int bl = mg_asprintf(&pbody, sizeof(bbody),
"<p>Moved <a href='%.*s'>here</a>.\r\n",
(int) location.len, location.p);
char bhead[150], *phead = bhead;
mg_asprintf(&phead, sizeof(bhead),
"Location: %.*s\r\n"
"Content-Type: text/html\r\n"
"Content-Length: %d\r\n"
"Cache-Control: no-cache\r\n"
"%.*s%s",
(int) location.len, location.p, bl, (int) extra_headers.len,
extra_headers.p, (extra_headers.len > 0 ? "\r\n" : ""));
mg_send_response_line(nc, status_code, phead);
if (phead != bhead) MG_FREE(phead);
mg_send(nc, pbody, bl);
if (pbody != bbody) MG_FREE(pbody);
}
void mg_send_head(struct mg_connection *c, int status_code,
int64_t content_length, const char *extra_headers) {
mg_send_response_line(c, status_code, extra_headers);
if (content_length < 0) {
mg_printf(c, "%s", "Transfer-Encoding: chunked\r\n");
} else {
mg_printf(c, "Content-Length: %" INT64_FMT "\r\n", content_length);
}
mg_send(c, "\r\n", 2);
}
void mg_http_send_error(struct mg_connection *nc, int code,
const char *reason) {
if (!reason) reason = mg_status_message(code);
LOG(LL_DEBUG, ("%p %d %s", nc, code, reason));
mg_send_head(nc, code, strlen(reason),
"Content-Type: text/plain\r\nConnection: close");
mg_send(nc, reason, strlen(reason));
nc->flags |= MG_F_SEND_AND_CLOSE;
}
#if MG_ENABLE_FILESYSTEM
static void mg_http_construct_etag(char *buf, size_t buf_len,
const cs_stat_t *st) {
snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime,
(int64_t) st->st_size);
}
#ifndef WINCE
static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
}
#else
/* Look wince_lib.c for WindowsCE implementation */
static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t);
#endif
static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a,
int64_t *b) {
/*
* There is no snscanf. Headers are not guaranteed to be NUL-terminated,
* so we have this. Ugh.
*/
int result;
char *p = (char *) MG_MALLOC(header->len + 1);
if (p == NULL) return 0;
memcpy(p, header->p, header->len);
p[header->len] = '\0';
result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
MG_FREE(p);
return result;
}
void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm,
const char *path, const struct mg_str mime_type,
const struct mg_str extra_headers) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
cs_stat_t st;
LOG(LL_DEBUG, ("%p [%s] %.*s", nc, path, (int) mime_type.len, mime_type.p));
if (mg_stat(path, &st) != 0 || (pd->file.fp = mg_fopen(path, "rb")) == NULL) {
int code, err = mg_get_errno();
switch (err) {
case EACCES:
code = 403;
break;
case ENOENT:
code = 404;
break;
default:
code = 500;
};
mg_http_send_error(nc, code, "Open failed");
} else {
char etag[50], current_time[50], last_modified[50], range[70];
time_t t = (time_t) mg_time();
int64_t r1 = 0, r2 = 0, cl = st.st_size;
struct mg_str *range_hdr = mg_get_http_header(hm, "Range");
int n, status_code = 200;
/* Handle Range header */
range[0] = '\0';
if (range_hdr != NULL &&
(n = mg_http_parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 &&
r2 >= 0) {
/* If range is specified like "400-", set second limit to content len */
if (n == 1) {
r2 = cl - 1;
}
if (r1 > r2 || r2 >= cl) {
status_code = 416;
cl = 0;
snprintf(range, sizeof(range),
"Content-Range: bytes */%" INT64_FMT "\r\n",
(int64_t) st.st_size);
} else {
status_code = 206;
cl = r2 - r1 + 1;
snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT
"-%" INT64_FMT "/%" INT64_FMT "\r\n",
r1, r1 + cl - 1, (int64_t) st.st_size);
#if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L || \
_XOPEN_SOURCE >= 600
fseeko(pd->file.fp, r1, SEEK_SET);
#else
fseek(pd->file.fp, (long) r1, SEEK_SET);
#endif
}
}
#if !MG_DISABLE_HTTP_KEEP_ALIVE
{
struct mg_str *conn_hdr = mg_get_http_header(hm, "Connection");
if (conn_hdr != NULL) {
pd->file.keepalive = (mg_vcasecmp(conn_hdr, "keep-alive") == 0);
} else {
pd->file.keepalive = (mg_vcmp(&hm->proto, "HTTP/1.1") == 0);
}
}
#endif
mg_http_construct_etag(etag, sizeof(etag), &st);
mg_gmt_time_string(current_time, sizeof(current_time), &t);
mg_gmt_time_string(last_modified, sizeof(last_modified), &st.st_mtime);
/*
* Content length casted to size_t because:
* 1) that's the maximum buffer size anyway
* 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last
* position
* TODO(mkm): fix ESP8266 RTOS SDK
*/
mg_send_response_line_s(nc, status_code, extra_headers);
mg_printf(nc,
"Date: %s\r\n"
"Last-Modified: %s\r\n"
"Accept-Ranges: bytes\r\n"
"Content-Type: %.*s\r\n"
"Connection: %s\r\n"
"Content-Length: %" SIZE_T_FMT
"\r\n"
"%sEtag: %s\r\n\r\n",
current_time, last_modified, (int) mime_type.len, mime_type.p,
(pd->file.keepalive ? "keep-alive" : "close"), (size_t) cl, range,
etag);
pd->file.cl = cl;
pd->file.type = DATA_FILE;
mg_http_transfer_file_data(nc);
}
}
static void mg_http_serve_file2(struct mg_connection *nc, const char *path,
struct http_message *hm,
struct mg_serve_http_opts *opts) {
#if MG_ENABLE_HTTP_SSI
if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) {
mg_handle_ssi_request(nc, hm, path, opts);
return;
}
#endif
mg_http_serve_file(nc, hm, path, mg_get_mime_type(path, "text/plain", opts),
mg_mk_str(opts->extra_headers));
}
#endif
int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
int is_form_url_encoded) {
int i, j, a, b;
#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
if (src[i] == '%') {
if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) &&
isxdigit(*(const unsigned char *) (src + i + 2))) {
a = tolower(*(const unsigned char *) (src + i + 1));
b = tolower(*(const unsigned char *) (src + i + 2));
dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
i += 2;
} else {
return -1;
}
} else if (is_form_url_encoded && src[i] == '+') {
dst[j] = ' ';
} else {
dst[j] = src[i];
}
}
dst[j] = '\0'; /* Null-terminate the destination */
return i >= src_len ? j : -1;
}
int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
size_t dst_len) {
const char *p, *e, *s;
size_t name_len;
int len;
/*
* According to the documentation function returns negative
* value in case of error. For debug purposes it returns:
* -1 - src is wrong (NUUL)
* -2 - dst is wrong (NULL)
* -3 - failed to decode url or dst is to small
* -4 - name does not exist
*/
if (dst == NULL || dst_len == 0) {
len = -2;
} else if (buf->p == NULL || name == NULL || buf->len == 0) {
len = -1;
dst[0] = '\0';
} else {
name_len = strlen(name);
e = buf->p + buf->len;
len = -4;
dst[0] = '\0';
for (p = buf->p; p + name_len < e; p++) {
if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' &&
!mg_ncasecmp(name, p, name_len)) {
p += name_len + 1;
s = (const char *) memchr(p, '&', (size_t)(e - p));
if (s == NULL) {
s = e;
}
len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
/* -1 means: failed to decode or dst is too small */
if (len == -1) {
len = -3;
}
break;
}
}
}
return len;
}
void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) {
char chunk_size[50];
int n;
n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len);
mg_send(nc, chunk_size, n);
mg_send(nc, buf, len);
mg_send(nc, "\r\n", 2);
}
void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) {
char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
int len;
va_list ap;
va_start(ap, fmt);
len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
va_end(ap);
if (len >= 0) {
mg_send_http_chunk(nc, buf, len);
}
/* LCOV_EXCL_START */
if (buf != mem && buf != NULL) {
MG_FREE(buf);
}
/* LCOV_EXCL_STOP */
}
void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) {
char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
int i, j, len;
va_list ap;
va_start(ap, fmt);
len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
va_end(ap);
if (len >= 0) {
for (i = j = 0; i < len; i++) {
if (buf[i] == '<' || buf[i] == '>') {
mg_send(nc, buf + j, i - j);
mg_send(nc, buf[i] == '<' ? "<" : ">", 4);
j = i + 1;
}
}
mg_send(nc, buf + j, i - j);
}
/* LCOV_EXCL_START */
if (buf != mem && buf != NULL) {
MG_FREE(buf);
}
/* LCOV_EXCL_STOP */
}
static void mg_http_parse_header_internal(struct mg_str *hdr,
const char *var_name,
struct altbuf *ab) {
int ch = ' ', ch1 = ',', ch2 = ';', n = strlen(var_name);
const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL;
/* Find where variable starts */
for (s = hdr->p; s != NULL && s + n < end; s++) {
if ((s == hdr->p || s[-1] == ch || s[-1] == ch1 || s[-1] == ';') &&
s[n] == '=' && !strncmp(s, var_name, n))
break;
}
if (s != NULL && &s[n + 1] < end) {
s += n + 1;
if (*s == '"' || *s == '\'') {
ch = ch1 = ch2 = *s++;
}
p = s;
while (p < end && p[0] != ch && p[0] != ch1 && p[0] != ch2) {
if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++;
altbuf_append(ab, *p++);
}
if (ch != ' ' && *p != ch) {
altbuf_reset(ab);
}
}
/* If there is some data, append a NUL. */
if (ab->len > 0) {
altbuf_append(ab, '\0');
}
}
int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf,
size_t buf_size) {
struct altbuf ab;
altbuf_init(&ab, *buf, buf_size);
if (hdr == NULL) return 0;
if (*buf != NULL && buf_size > 0) *buf[0] = '\0';
mg_http_parse_header_internal(hdr, var_name, &ab);
/*
* Get a (trimmed) buffer, and return a len without a NUL byte which might
* have been added.
*/
*buf = altbuf_get_buf(&ab, 1 /* trim */);
return ab.len > 0 ? ab.len - 1 : 0;
}
int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
size_t buf_size) {
char *buf2 = buf;
int len = mg_http_parse_header2(hdr, var_name, &buf2, buf_size);
if (buf2 != buf) {
/* Buffer was not enough and was reallocated: free it and just return 0 */
MG_FREE(buf2);
return 0;
}
return len;
}
int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len,
char *pass, size_t pass_len) {
struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
if (hdr == NULL) return -1;
return mg_parse_http_basic_auth(hdr, user, user_len, pass, pass_len);
}
int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len,
char *pass, size_t pass_len) {
char *buf = NULL;
char fmt[64];
int res = 0;
if (mg_strncmp(*hdr, mg_mk_str("Basic "), 6) != 0) return -1;
buf = (char *) MG_MALLOC(hdr->len);
cs_base64_decode((unsigned char *) hdr->p + 6, hdr->len, buf, NULL);
/* e.g. "%123[^:]:%321[^\n]" */
snprintf(fmt, sizeof(fmt), "%%%" SIZE_T_FMT "[^:]:%%%" SIZE_T_FMT "[^\n]",
user_len - 1, pass_len - 1);
if (sscanf(buf, fmt, user, pass) == 0) {
res = -1;
}
MG_FREE(buf);
return res;
}
#if MG_ENABLE_FILESYSTEM
static int mg_is_file_hidden(const char *path,
const struct mg_serve_http_opts *opts,
int exclude_specials) {
const char *p1 = opts->per_directory_auth_file;
const char *p2 = opts->hidden_file_pattern;
/* Strip directory path from the file name */
const char *pdir = strrchr(path, DIRSEP);
if (pdir != NULL) {
path = pdir + 1;
}
return (exclude_specials && (!strcmp(path, ".") || !strcmp(path, ".."))) ||
(p1 != NULL && mg_match_prefix(p1, strlen(p1), path) == strlen(p1)) ||
(p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0);
}
#if !MG_DISABLE_HTTP_DIGEST_AUTH
#ifndef MG_EXT_MD5
void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[],
const size_t *msg_lens, uint8_t *digest) {
size_t i;
cs_md5_ctx md5_ctx;
cs_md5_init(&md5_ctx);
for (i = 0; i < num_msgs; i++) {
cs_md5_update(&md5_ctx, msgs[i], msg_lens[i]);
}
cs_md5_final(digest, &md5_ctx);
}
#else
extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[],
const size_t *msg_lens, uint8_t *digest);
#endif
void cs_md5(char buf[33], ...) {
unsigned char hash[16];
const uint8_t *msgs[20], *p;
size_t msg_lens[20];
size_t num_msgs = 0;
va_list ap;
va_start(ap, buf);
while ((p = va_arg(ap, const unsigned char *) ) != NULL) {
msgs[num_msgs] = p;
msg_lens[num_msgs] = va_arg(ap, size_t);
num_msgs++;
}
va_end(ap);
mg_hash_md5_v(num_msgs, msgs, msg_lens, hash);
cs_to_hex(buf, hash, sizeof(hash));
}
static void mg_mkmd5resp(const char *method, size_t method_len, const char *uri,
size_t uri_len, const char *ha1, size_t ha1_len,
const char *nonce, size_t nonce_len, const char *nc,
size_t nc_len, const char *cnonce, size_t cnonce_len,
const char *qop, size_t qop_len, char *resp) {
static const char colon[] = ":";
static const size_t one = 1;
char ha2[33];
cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL);
cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc,
nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len,
colon, one, ha2, sizeof(ha2) - 1, NULL);
}
int mg_http_create_digest_auth_header(char *buf, size_t buf_len,
const char *method, const char *uri,
const char *auth_domain, const char *user,
const char *passwd, const char *nonce) {
static const char colon[] = ":", qop[] = "auth";
static const size_t one = 1;
char ha1[33], resp[33], cnonce[40];
snprintf(cnonce, sizeof(cnonce), "%lx", (unsigned long) mg_time());
cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain,
(size_t) strlen(auth_domain), colon, one, passwd,
(size_t) strlen(passwd), NULL);
mg_mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1,
nonce, strlen(nonce), "1", one, cnonce, strlen(cnonce), qop,
sizeof(qop) - 1, resp);
return snprintf(buf, buf_len,
"Authorization: Digest username=\"%s\","
"realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s,"
"nonce=%s,response=%s\r\n",
user, auth_domain, uri, qop, cnonce, nonce, resp);
}
/*
* Check for authentication timeout.
* Clients send time stamp encoded in nonce. Make sure it is not too old,
* to prevent replay attacks.
* Assumption: nonce is a hexadecimal number of seconds since 1970.
*/
static int mg_check_nonce(const char *nonce) {
unsigned long now = (unsigned long) mg_time();
unsigned long val = (unsigned long) strtoul(nonce, NULL, 16);
return (now >= val) && (now - val < 60 * 60);
}
int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain,
FILE *fp) {
int ret = 0;
struct mg_str *hdr;
char username_buf[50], cnonce_buf[64], response_buf[40], uri_buf[200],
qop_buf[20], nc_buf[20], nonce_buf[16];
char *username = username_buf, *cnonce = cnonce_buf, *response = response_buf,
*uri = uri_buf, *qop = qop_buf, *nc = nc_buf, *nonce = nonce_buf;
/* Parse "Authorization:" header, fail fast on parse error */
if (hm == NULL || fp == NULL ||
(hdr = mg_get_http_header(hm, "Authorization")) == NULL ||
mg_http_parse_header2(hdr, "username", &username, sizeof(username_buf)) ==
0 ||
mg_http_parse_header2(hdr, "cnonce", &cnonce, sizeof(cnonce_buf)) == 0 ||
mg_http_parse_header2(hdr, "response", &response, sizeof(response_buf)) ==
0 ||
mg_http_parse_header2(hdr, "uri", &uri, sizeof(uri_buf)) == 0 ||
mg_http_parse_header2(hdr, "qop", &qop, sizeof(qop_buf)) == 0 ||
mg_http_parse_header2(hdr, "nc", &nc, sizeof(nc_buf)) == 0 ||
mg_http_parse_header2(hdr, "nonce", &nonce, sizeof(nonce_buf)) == 0 ||
mg_check_nonce(nonce) == 0) {
ret = 0;
goto clean;
}
/* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */
ret = mg_check_digest_auth(
hm->method,
mg_mk_str_n(
hm->uri.p,
hm->uri.len + (hm->query_string.len ? hm->query_string.len + 1 : 0)),
mg_mk_str(username), mg_mk_str(cnonce), mg_mk_str(response),
mg_mk_str(qop), mg_mk_str(nc), mg_mk_str(nonce), mg_mk_str(auth_domain),
fp);
clean:
if (username != username_buf) MG_FREE(username);
if (cnonce != cnonce_buf) MG_FREE(cnonce);
if (response != response_buf) MG_FREE(response);
if (uri != uri_buf) MG_FREE(uri);
if (qop != qop_buf) MG_FREE(qop);
if (nc != nc_buf) MG_FREE(nc);
if (nonce != nonce_buf) MG_FREE(nonce);
return ret;
}
int mg_check_digest_auth(struct mg_str method, struct mg_str uri,
struct mg_str username, struct mg_str cnonce,
struct mg_str response, struct mg_str qop,
struct mg_str nc, struct mg_str nonce,
struct mg_str auth_domain, FILE *fp) {
char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)];
char exp_resp[33];
/*
* Read passwords file line by line. If should have htdigest format,
* i.e. each line should be a colon-separated sequence:
* USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD
*/
while (fgets(buf, sizeof(buf), fp) != NULL) {
if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 &&
mg_vcmp(&username, f_user) == 0 &&
mg_vcmp(&auth_domain, f_domain) == 0) {
/* Username and domain matched, check the password */
mg_mkmd5resp(method.p, method.len, uri.p, uri.len, f_ha1, strlen(f_ha1),
nonce.p, nonce.len, nc.p, nc.len, cnonce.p, cnonce.len,
qop.p, qop.len, exp_resp);
LOG(LL_DEBUG, ("%.*s %s %.*s %s", (int) username.len, username.p,
f_domain, (int) response.len, response.p, exp_resp));
return mg_ncasecmp(response.p, exp_resp, strlen(exp_resp)) == 0;
}
}
/* None of the entries in the passwords file matched - return failure */
return 0;
}
int mg_http_is_authorized(struct http_message *hm, struct mg_str path,
const char *domain, const char *passwords_file,
int flags) {
char buf[MG_MAX_PATH];
const char *p;
FILE *fp;
int authorized = 1;
if (domain != NULL && passwords_file != NULL) {
if (flags & MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE) {
fp = mg_fopen(passwords_file, "r");
} else if (flags & MG_AUTH_FLAG_IS_DIRECTORY) {
snprintf(buf, sizeof(buf), "%.*s%c%s", (int) path.len, path.p, DIRSEP,
passwords_file);
fp = mg_fopen(buf, "r");
} else {
p = strrchr(path.p, DIRSEP);
if (p == NULL) p = path.p;
snprintf(buf, sizeof(buf), "%.*s%c%s", (int) (p - path.p), path.p, DIRSEP,
passwords_file);
fp = mg_fopen(buf, "r");
}
if (fp != NULL) {
authorized = mg_http_check_digest_auth(hm, domain, fp);
fclose(fp);
} else if (!(flags & MG_AUTH_FLAG_ALLOW_MISSING_FILE)) {
authorized = 0;
}
}
LOG(LL_DEBUG, ("%.*s %s %x %d", (int) path.len, path.p,
passwords_file ? passwords_file : "", flags, authorized));
return authorized;
}
#else
int mg_http_is_authorized(struct http_message *hm, const struct mg_str path,
const char *domain, const char *passwords_file,
int flags) {
(void) hm;
(void) path;
(void) domain;
(void) passwords_file;
(void) flags;
return 1;
}
#endif
#if MG_ENABLE_DIRECTORY_LISTING
static void mg_escape(const char *src, char *dst, size_t dst_len) {
size_t n = 0;
while (*src != '\0' && n + 5 < dst_len) {
unsigned char ch = *(unsigned char *) src++;
if (ch == '<') {
n += snprintf(dst + n, dst_len - n, "%s", "<");
} else {
dst[n++] = ch;
}
}
dst[n] = '\0';
}
static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name,
cs_stat_t *stp) {
char size[64], mod[64], path[MG_MAX_PATH];
int64_t fsize = stp->st_size;
int is_dir = S_ISDIR(stp->st_mode);
const char *slash = is_dir ? "/" : "";
struct mg_str href;
if (is_dir) {
snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
} else {
/*
* We use (double) cast below because MSVC 6 compiler cannot
* convert unsigned __int64 to double.
*/
if (fsize < 1024) {
snprintf(size, sizeof(size), "%d", (int) fsize);
} else if (fsize < 0x100000) {
snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
} else if (fsize < 0x40000000) {
snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
} else {
snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
}
}
strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime));
mg_escape(file_name, path, sizeof(path));
href = mg_url_encode(mg_mk_str(file_name));
mg_printf_http_chunk(nc,
"<tr><td><a href=\"%s%s\">%s%s</a></td>"
"<td>%s</td><td name=%" INT64_FMT ">%s</td></tr>\n",
href.p, slash, path, slash, mod, is_dir ? -1 : fsize,
size);
free((void *) href.p);
}
static void mg_scan_directory(struct mg_connection *nc, const char *dir,
const struct mg_serve_http_opts *opts,
void (*func)(struct mg_connection *, const char *,
cs_stat_t *)) {
char path[MG_MAX_PATH + 1];
cs_stat_t st;
struct dirent *dp;
DIR *dirp;
LOG(LL_DEBUG, ("%p [%s]", nc, dir));
if ((dirp = (opendir(dir))) != NULL) {
while ((dp = readdir(dirp)) != NULL) {
/* Do not show current dir and hidden files */
if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
continue;
}
snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name);
if (mg_stat(path, &st) == 0) {
func(nc, (const char *) dp->d_name, &st);
}
}
closedir(dirp);
} else {
LOG(LL_DEBUG, ("%p opendir(%s) -> %d", nc, dir, mg_get_errno()));
}
}
static void mg_send_directory_listing(struct mg_connection *nc, const char *dir,
struct http_message *hm,
struct mg_serve_http_opts *opts) {
static const char *sort_js_code =
"<script>function srt(tb, sc, so, d) {"
"var tr = Array.prototype.slice.call(tb.rows, 0),"
"tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
"n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
"t1 = a.cells[2].getAttribute('name'), "
"t2 = b.cells[2].getAttribute('name'); "
"return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
"n1 ? parseInt(n2) - parseInt(n1) : "
"c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
static const char *sort_js_code2 =
"for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
"if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
"};"
"window.onload = function() {"
"var tb = document.getElementById('tb');"
"var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
"var sc = m[1], so = m[2]; document.onclick = function(ev) { "
"var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
"sc = c; ev.preventDefault();}};"
"srt(tb, sc, so, true);"
"}"
"</script>";
mg_send_response_line(nc, 200, opts->extra_headers);
mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked",
"Content-Type", "text/html; charset=utf-8");
mg_printf_http_chunk(
nc,
"<html><head><title>Index of %.*s</title>%s%s"
"<style>th,td {text-align: left; padding-right: 1em; "
"font-family: monospace; }</style></head>\n"
"<body><h1>Index of %.*s</h1>\n<table cellpadding=0><thead>"
"<tr><th><a href=# rel=0>Name</a></th><th>"
"<a href=# rel=1>Modified</a</th>"
"<th><a href=# rel=2>Size</a></th></tr>"
"<tr><td colspan=3><hr></td></tr>\n"
"</thead>\n"
"<tbody id=tb>",
(int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2,
(int) hm->uri.len, hm->uri.p);
mg_scan_directory(nc, dir, opts, mg_print_dir_entry);
mg_printf_http_chunk(nc,
"</tbody><tr><td colspan=3><hr></td></tr>\n"
"</table>\n"
"<address>%s</address>\n"
"</body></html>",
mg_version_header);
mg_send_http_chunk(nc, "", 0);
/* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */
nc->flags |= MG_F_SEND_AND_CLOSE;
}
#endif /* MG_ENABLE_DIRECTORY_LISTING */
/*
* Given a directory path, find one of the files specified in the
* comma-separated list of index files `list`.
* First found index file wins. If an index file is found, then gets
* appended to the `path`, stat-ed, and result of `stat()` passed to `stp`.
* If index file is not found, then `path` and `stp` remain unchanged.
*/
MG_INTERNAL void mg_find_index_file(const char *path, const char *list,
char **index_file, cs_stat_t *stp) {
struct mg_str vec;
size_t path_len = strlen(path);
int found = 0;
*index_file = NULL;
/* Traverse index files list. For each entry, append it to the given */
/* path and see if the file exists. If it exists, break the loop */
while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) {
cs_stat_t st;
size_t len = path_len + 1 + vec.len + 1;
*index_file = (char *) MG_REALLOC(*index_file, len);
if (*index_file == NULL) break;
snprintf(*index_file, len, "%s%c%.*s", path, DIRSEP, (int) vec.len, vec.p);
/* Does it exist? Is it a file? */
if (mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) {
/* Yes it does, break the loop */
*stp = st;
found = 1;
break;
}
}
if (!found) {
MG_FREE(*index_file);
*index_file = NULL;
}
LOG(LL_DEBUG, ("[%s] [%s]", path, (*index_file ? *index_file : "")));
}
#if MG_ENABLE_HTTP_URL_REWRITES
static int mg_http_send_port_based_redirect(
struct mg_connection *c, struct http_message *hm,
const struct mg_serve_http_opts *opts) {
const char *rewrites = opts->url_rewrites;
struct mg_str a, b;
char local_port[20] = {'%'};
mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1,
MG_SOCK_STRINGIFY_PORT);
while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
if (mg_vcmp(&a, local_port) == 0) {
mg_send_response_line(c, 301, NULL);
mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n",
(int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1),
hm->uri.p);
return 1;
}
}
return 0;
}
static void mg_reverse_proxy_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct http_message *hm = (struct http_message *) ev_data;
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
if (pd == NULL || pd->reverse_proxy_data.linked_conn == NULL) {
DBG(("%p: upstream closed", nc));
return;
}
switch (ev) {
case MG_EV_CONNECT:
if (*(int *) ev_data != 0) {
mg_http_send_error(pd->reverse_proxy_data.linked_conn, 502, NULL);
}
break;
/* TODO(mkm): handle streaming */
case MG_EV_HTTP_REPLY:
mg_send(pd->reverse_proxy_data.linked_conn, hm->message.p,
hm->message.len);
pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
break;
case MG_EV_CLOSE:
pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
break;
}
#if MG_ENABLE_CALLBACK_USERDATA
(void) user_data;
#endif
}
void mg_http_reverse_proxy(struct mg_connection *nc,
const struct http_message *hm, struct mg_str mount,
struct mg_str upstream) {
struct mg_connection *be;
char burl[256], *purl = burl;
int i;
const char *error;
struct mg_connect_opts opts;
struct mg_str path = MG_NULL_STR, user_info = MG_NULL_STR, host = MG_NULL_STR;
memset(&opts, 0, sizeof(opts));
opts.error_string = &error;
mg_asprintf(&purl, sizeof(burl), "%.*s%.*s", (int) upstream.len, upstream.p,
(int) (hm->uri.len - mount.len), hm->uri.p + mount.len);
be = mg_connect_http_base(nc->mgr, MG_CB(mg_reverse_proxy_handler, NULL),
opts, "http", NULL, "https", NULL, purl, &path,
&user_info, &host);
LOG(LL_DEBUG, ("Proxying %.*s to %s (rule: %.*s)", (int) hm->uri.len,
hm->uri.p, purl, (int) mount.len, mount.p));
if (be == NULL) {
LOG(LL_ERROR, ("Error connecting to %s: %s", purl, error));
mg_http_send_error(nc, 502, NULL);
goto cleanup;
}
/* link connections to each other, they must live and die together */
mg_http_get_proto_data(be)->reverse_proxy_data.linked_conn = nc;
mg_http_get_proto_data(nc)->reverse_proxy_data.linked_conn = be;
/* send request upstream */
mg_printf(be, "%.*s %.*s HTTP/1.1\r\n", (int) hm->method.len, hm->method.p,
(int) path.len, path.p);
mg_printf(be, "Host: %.*s\r\n", (int) host.len, host.p);
for (i = 0; i < MG_MAX_HTTP_HEADERS && hm->header_names[i].len > 0; i++) {
struct mg_str hn = hm->header_names[i];
struct mg_str hv = hm->header_values[i];
/* we rewrite the host header */
if (mg_vcasecmp(&hn, "Host") == 0) continue;
/*
* Don't pass chunked transfer encoding to the client because hm->body is
* already dechunked when we arrive here.
*/
if (mg_vcasecmp(&hn, "Transfer-encoding") == 0 &&
mg_vcasecmp(&hv, "chunked") == 0) {
mg_printf(be, "Content-Length: %" SIZE_T_FMT "\r\n", hm->body.len);
continue;
}
/* We don't support proxying Expect: 100-continue. */
if (mg_vcasecmp(&hn, "Expect") == 0 &&
mg_vcasecmp(&hv, "100-continue") == 0) {
continue;
}
mg_printf(be, "%.*s: %.*s\r\n", (int) hn.len, hn.p, (int) hv.len, hv.p);
}
mg_send(be, "\r\n", 2);
mg_send(be, hm->body.p, hm->body.len);
cleanup:
if (purl != burl) MG_FREE(purl);
}
static int mg_http_handle_forwarding(struct mg_connection *nc,
struct http_message *hm,
const struct mg_serve_http_opts *opts) {
const char *rewrites = opts->url_rewrites;
struct mg_str a, b;
struct mg_str p1 = MG_MK_STR("http://"), p2 = MG_MK_STR("https://");
while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
if (mg_strncmp(a, hm->uri, a.len) == 0) {
if (mg_strncmp(b, p1, p1.len) == 0 || mg_strncmp(b, p2, p2.len) == 0) {
mg_http_reverse_proxy(nc, hm, a, b);
return 1;
}
}
}
return 0;
}
#endif /* MG_ENABLE_FILESYSTEM */
MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
const struct mg_serve_http_opts *opts,
char **local_path,
struct mg_str *remainder) {
int ok = 1;
const char *cp = hm->uri.p, *cp_end = hm->uri.p + hm->uri.len;
struct mg_str root = {NULL, 0};
const char *file_uri_start = cp;
*local_path = NULL;
remainder->p = NULL;
remainder->len = 0;
{ /* 1. Determine which root to use. */
#if MG_ENABLE_HTTP_URL_REWRITES
const char *rewrites = opts->url_rewrites;
#else
const char *rewrites = "";
#endif
struct mg_str *hh = mg_get_http_header(hm, "Host");
struct mg_str a, b;
/* Check rewrites first. */
while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
if (a.len > 1 && a.p[0] == '@') {
/* Host rewrite. */
if (hh != NULL && hh->len == a.len - 1 &&
mg_ncasecmp(a.p + 1, hh->p, a.len - 1) == 0) {
root = b;
break;
}
} else {
/* Regular rewrite, URI=directory */
size_t match_len = mg_match_prefix_n(a, hm->uri);
if (match_len > 0) {
file_uri_start = hm->uri.p + match_len;
if (*file_uri_start == '/' || file_uri_start == cp_end) {
/* Match ended at component boundary, ok. */
} else if (*(file_uri_start - 1) == '/') {
/* Pattern ends with '/', backtrack. */
file_uri_start--;
} else {
/* No match: must fall on the component boundary. */
continue;
}
root = b;
break;
}
}
}
/* If no rewrite rules matched, use DAV or regular document root. */
if (root.p == NULL) {
#if MG_ENABLE_HTTP_WEBDAV
if (opts->dav_document_root != NULL && mg_is_dav_request(&hm->method)) {
root.p = opts->dav_document_root;
root.len = strlen(opts->dav_document_root);
} else
#endif
{
root.p = opts->document_root;
root.len = strlen(opts->document_root);
}
}
assert(root.p != NULL && root.len > 0);
}
{ /* 2. Find where in the canonical URI path the local path ends. */
const char *u = file_uri_start + 1;
char *lp = (char *) MG_MALLOC(root.len + hm->uri.len + 1);
char *lp_end = lp + root.len + hm->uri.len + 1;
char *p = lp, *ps;
int exists = 1;
if (lp == NULL) {
ok = 0;
goto out;
}
memcpy(p, root.p, root.len);
p += root.len;
if (*(p - 1) == DIRSEP) p--;
*p = '\0';
ps = p;
/* Chop off URI path components one by one and build local path. */
while (u <= cp_end) {
const char *next = u;
struct mg_str component;
if (exists) {
cs_stat_t st;
exists = (mg_stat(lp, &st) == 0);
if (exists && S_ISREG(st.st_mode)) {
/* We found the terminal, the rest of the URI (if any) is path_info.
*/
if (*(u - 1) == '/') u--;
break;
}
}
if (u >= cp_end) break;
parse_uri_component((const char **) &next, cp_end, "/", &component);
if (component.len > 0) {
int len;
memmove(p + 1, component.p, component.len);
len = mg_url_decode(p + 1, component.len, p + 1, lp_end - p - 1, 0);
if (len <= 0) {
ok = 0;
break;
}
component.p = p + 1;
component.len = len;
if (mg_vcmp(&component, ".") == 0) {
/* Yum. */
} else if (mg_vcmp(&component, "..") == 0) {
while (p > ps && *p != DIRSEP) p--;
*p = '\0';
} else {
size_t i;
#ifdef _WIN32
/* On Windows, make sure it's valid Unicode (no funny stuff). */
wchar_t buf[MG_MAX_PATH * 2];
if (to_wchar(component.p, buf, MG_MAX_PATH) == 0) {
DBG(("[%.*s] smells funny", (int) component.len, component.p));
ok = 0;
break;
}
#endif
*p++ = DIRSEP;
/* No NULs and DIRSEPs in the component (percent-encoded). */
for (i = 0; i < component.len; i++, p++) {
if (*p == '\0' || *p == DIRSEP
#ifdef _WIN32
/* On Windows, "/" is also accepted, so check for that too. */
||
*p == '/'
#endif
) {
ok = 0;
break;
}
}
}
}
u = next;
}
if (ok) {
*local_path = lp;
if (u > cp_end) u = cp_end;
remainder->p = u;
remainder->len = cp_end - u;
} else {
MG_FREE(lp);
}
}
out:
LOG(LL_DEBUG,
("'%.*s' -> '%s' + '%.*s'", (int) hm->uri.len, hm->uri.p,
*local_path ? *local_path : "", (int) remainder->len, remainder->p));
return ok;
}
static int mg_get_month_index(const char *s) {
static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
size_t i;
for (i = 0; i < ARRAY_SIZE(month_names); i++)
if (!strcmp(s, month_names[i])) return (int) i;
return -1;
}
static int mg_num_leap_years(int year) {
return year / 4 - year / 100 + year / 400;
}
/* Parse UTC date-time string, and return the corresponding time_t value. */
MG_INTERNAL time_t mg_parse_date_string(const char *datetime) {
static const unsigned short days_before_month[] = {
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
char month_str[32];
int second, minute, hour, day, month, year, leap_days, days;
time_t result = (time_t) 0;
if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour,
&minute, &second) == 6) ||
(sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour,
&minute, &second) == 6) ||
(sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year,
&hour, &minute, &second) == 6) ||
(sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour,
&minute, &second) == 6)) &&
year > 1970 && (month = mg_get_month_index(month_str)) != -1) {
leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970);
year -= 1970;
days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
}
return result;
}
MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) {
struct mg_str *hdr;
if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) {
char etag[64];
mg_http_construct_etag(etag, sizeof(etag), st);
return mg_vcasecmp(hdr, etag) == 0;
} else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) {
return st->st_mtime <= mg_parse_date_string(hdr->p);
} else {
return 0;
}
}
void mg_http_send_digest_auth_request(struct mg_connection *c,
const char *domain) {
mg_printf(c,
"HTTP/1.1 401 Unauthorized\r\n"
"WWW-Authenticate: Digest qop=\"auth\", "
"realm=\"%s\", nonce=\"%lx\"\r\n"
"Content-Length: 0\r\n\r\n",
domain, (unsigned long) mg_time());
}
static void mg_http_send_options(struct mg_connection *nc,
struct mg_serve_http_opts *opts) {
mg_send_response_line(nc, 200, opts->extra_headers);
mg_printf(nc, "%s",
"Allow: GET, POST, HEAD, CONNECT, OPTIONS"
#if MG_ENABLE_HTTP_WEBDAV
", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2"
#endif
"\r\n\r\n");
nc->flags |= MG_F_SEND_AND_CLOSE;
}
static int mg_is_creation_request(const struct http_message *hm) {
return mg_vcmp(&hm->method, "MKCOL") == 0 || mg_vcmp(&hm->method, "PUT") == 0;
}
MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path,
const struct mg_str *path_info,
struct http_message *hm,
struct mg_serve_http_opts *opts) {
int exists, is_directory, is_cgi;
#if MG_ENABLE_HTTP_WEBDAV
int is_dav = mg_is_dav_request(&hm->method);
#else
int is_dav = 0;
#endif
char *index_file = NULL;
cs_stat_t st;
exists = (mg_stat(path, &st) == 0);
is_directory = exists && S_ISDIR(st.st_mode);
if (is_directory)
mg_find_index_file(path, opts->index_files, &index_file, &st);
is_cgi =
(mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern),
index_file ? index_file : path) > 0);
LOG(LL_DEBUG,
("%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", nc,
(int) hm->method.len, hm->method.p, path, exists, is_directory, is_dav,
is_cgi, index_file ? index_file : ""));
if (is_directory && hm->uri.p[hm->uri.len - 1] != '/' && !is_dav) {
mg_printf(nc,
"HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n"
"Content-Length: 0\r\n\r\n",
(int) hm->uri.len, hm->uri.p);
MG_FREE(index_file);
return;
}
/* If we have path_info, the only way to handle it is CGI. */
if (path_info->len > 0 && !is_cgi) {
mg_http_send_error(nc, 501, NULL);
MG_FREE(index_file);
return;
}
if (is_dav && opts->dav_document_root == NULL) {
mg_http_send_error(nc, 501, NULL);
} else if (!mg_http_is_authorized(
hm, mg_mk_str(path), opts->auth_domain, opts->global_auth_file,
((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) |
MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE |
MG_AUTH_FLAG_ALLOW_MISSING_FILE)) ||
!mg_http_is_authorized(
hm, mg_mk_str(path), opts->auth_domain,
opts->per_directory_auth_file,
((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) |
MG_AUTH_FLAG_ALLOW_MISSING_FILE))) {
mg_http_send_digest_auth_request(nc, opts->auth_domain);
} else if (is_cgi) {
#if MG_ENABLE_HTTP_CGI
mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts);
#else
mg_http_send_error(nc, 501, NULL);
#endif /* MG_ENABLE_HTTP_CGI */
} else if ((!exists ||
mg_is_file_hidden(path, opts, 0 /* specials are ok */)) &&
!mg_is_creation_request(hm)) {
mg_http_send_error(nc, 404, NULL);
#if MG_ENABLE_HTTP_WEBDAV
} else if (!mg_vcmp(&hm->method, "PROPFIND")) {
mg_handle_propfind(nc, path, &st, hm, opts);
#if !MG_DISABLE_DAV_AUTH
} else if (is_dav &&
(opts->dav_auth_file == NULL ||
(strcmp(opts->dav_auth_file, "-") != 0 &&
!mg_http_is_authorized(
hm, mg_mk_str(path), opts->auth_domain, opts->dav_auth_file,
((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) |
MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE |
MG_AUTH_FLAG_ALLOW_MISSING_FILE))))) {
mg_http_send_digest_auth_request(nc, opts->auth_domain);
#endif
} else if (!mg_vcmp(&hm->method, "MKCOL")) {
mg_handle_mkcol(nc, path, hm);
} else if (!mg_vcmp(&hm->method, "DELETE")) {
mg_handle_delete(nc, opts, path);
} else if (!mg_vcmp(&hm->method, "PUT")) {
mg_handle_put(nc, path, hm);
} else if (!mg_vcmp(&hm->method, "MOVE")) {
mg_handle_move(nc, opts, path, hm);
#if MG_ENABLE_FAKE_DAVLOCK
} else if (!mg_vcmp(&hm->method, "LOCK")) {
mg_handle_lock(nc, path);
#endif
#endif /* MG_ENABLE_HTTP_WEBDAV */
} else if (!mg_vcmp(&hm->method, "OPTIONS")) {
mg_http_send_options(nc, opts);
} else if (is_directory && index_file == NULL) {
#if MG_ENABLE_DIRECTORY_LISTING
if (strcmp(opts->enable_directory_listing, "yes") == 0) {
mg_send_directory_listing(nc, path, hm, opts);
} else {
mg_http_send_error(nc, 403, NULL);
}
#else
mg_http_send_error(nc, 501, NULL);
#endif
} else if (mg_is_not_modified(hm, &st)) {
mg_http_send_error(nc, 304, "Not Modified");
} else {
mg_http_serve_file2(nc, index_file ? index_file : path, hm, opts);
}
MG_FREE(index_file);
}
void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
struct mg_serve_http_opts opts) {
char *path = NULL;
struct mg_str *hdr, path_info;
uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr);
if (mg_check_ip_acl(opts.ip_acl, remote_ip) != 1) {
/* Not allowed to connect */
mg_http_send_error(nc, 403, NULL);
nc->flags |= MG_F_SEND_AND_CLOSE;
return;
}
#if MG_ENABLE_HTTP_URL_REWRITES
if (mg_http_handle_forwarding(nc, hm, &opts)) {
return;
}
if (mg_http_send_port_based_redirect(nc, hm, &opts)) {
return;
}
#endif
if (opts.document_root == NULL) {
opts.document_root = ".";
}
if (opts.per_directory_auth_file == NULL) {
opts.per_directory_auth_file = ".htpasswd";
}
if (opts.enable_directory_listing == NULL) {
opts.enable_directory_listing = "yes";
}
if (opts.cgi_file_pattern == NULL) {
opts.cgi_file_pattern = "**.cgi$|**.php$";
}
if (opts.ssi_pattern == NULL) {
opts.ssi_pattern = "**.shtml$|**.shtm$";
}
if (opts.index_files == NULL) {
opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php";
}
/* Normalize path - resolve "." and ".." (in-place). */
if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) {
mg_http_send_error(nc, 400, NULL);
return;
}
if (mg_uri_to_local_path(hm, &opts, &path, &path_info) == 0) {
mg_http_send_error(nc, 404, NULL);
return;
}
mg_send_http_file(nc, path, &path_info, hm, &opts);
MG_FREE(path);
path = NULL;
/* Close connection for non-keep-alive requests */
if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 ||
((hdr = mg_get_http_header(hm, "Connection")) != NULL &&
mg_vcmp(hdr, "keep-alive") != 0)) {
#if 0
nc->flags |= MG_F_SEND_AND_CLOSE;
#endif
}
}
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data,
mg_fu_fname_fn local_name_fn
MG_UD_ARG(void *user_data)) {
switch (ev) {
case MG_EV_HTTP_PART_BEGIN: {
struct mg_http_multipart_part *mp =
(struct mg_http_multipart_part *) ev_data;
struct file_upload_state *fus;
struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name));
mp->user_data = NULL;
if (lfn.p == NULL || lfn.len == 0) {
LOG(LL_ERROR, ("%p Not allowed to upload %s", nc, mp->file_name));
mg_printf(nc,
"HTTP/1.1 403 Not Allowed\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"
"Not allowed to upload %s\r\n",
mp->file_name);
nc->flags |= MG_F_SEND_AND_CLOSE;
return;
}
fus = (struct file_upload_state *) MG_CALLOC(1, sizeof(*fus));
if (fus == NULL) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return;
}
fus->lfn = (char *) MG_MALLOC(lfn.len + 1);
memcpy(fus->lfn, lfn.p, lfn.len);
fus->lfn[lfn.len] = '\0';
if (lfn.p != mp->file_name) MG_FREE((char *) lfn.p);
LOG(LL_DEBUG,
("%p Receiving file %s -> %s", nc, mp->file_name, fus->lfn));
fus->fp = mg_fopen(fus->lfn, "wb");
if (fus->fp == NULL) {
mg_printf(nc,
"HTTP/1.1 500 Internal Server Error\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n");
LOG(LL_ERROR, ("Failed to open %s: %d\n", fus->lfn, mg_get_errno()));
mg_printf(nc, "Failed to open %s: %d\n", fus->lfn, mg_get_errno());
/* Do not close the connection just yet, discard remainder of the data.
* This is because at the time of writing some browsers (Chrome) fail to
* render response before all the data is sent. */
}
mp->user_data = (void *) fus;
break;
}
case MG_EV_HTTP_PART_DATA: {
struct mg_http_multipart_part *mp =
(struct mg_http_multipart_part *) ev_data;
struct file_upload_state *fus =
(struct file_upload_state *) mp->user_data;
if (fus == NULL || fus->fp == NULL) break;
if (mg_fwrite(mp->data.p, 1, mp->data.len, fus->fp) != mp->data.len) {
LOG(LL_ERROR, ("Failed to write to %s: %d, wrote %d", fus->lfn,
mg_get_errno(), (int) fus->num_recd));
if (mg_get_errno() == ENOSPC
#ifdef SPIFFS_ERR_FULL
|| mg_get_errno() == SPIFFS_ERR_FULL
#endif
) {
mg_printf(nc,
"HTTP/1.1 413 Payload Too Large\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n");
mg_printf(nc, "Failed to write to %s: no space left; wrote %d\r\n",
fus->lfn, (int) fus->num_recd);
} else {
mg_printf(nc,
"HTTP/1.1 500 Internal Server Error\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n");
mg_printf(nc, "Failed to write to %s: %d, wrote %d", mp->file_name,
mg_get_errno(), (int) fus->num_recd);
}
fclose(fus->fp);
remove(fus->lfn);
fus->fp = NULL;
/* Do not close the connection just yet, discard remainder of the data.
* This is because at the time of writing some browsers (Chrome) fail to
* render response before all the data is sent. */
return;
}
fus->num_recd += mp->data.len;
LOG(LL_DEBUG, ("%p rec'd %d bytes, %d total", nc, (int) mp->data.len,
(int) fus->num_recd));
break;
}
case MG_EV_HTTP_PART_END: {
struct mg_http_multipart_part *mp =
(struct mg_http_multipart_part *) ev_data;
struct file_upload_state *fus =
(struct file_upload_state *) mp->user_data;
if (fus == NULL) break;
if (mp->status >= 0 && fus->fp != NULL) {
LOG(LL_DEBUG, ("%p Uploaded %s (%s), %d bytes", nc, mp->file_name,
fus->lfn, (int) fus->num_recd));
} else {
LOG(LL_ERROR, ("Failed to store %s (%s)", mp->file_name, fus->lfn));
/*
* mp->status < 0 means connection was terminated, so no reason to send
* HTTP reply
*/
}
if (fus->fp != NULL) fclose(fus->fp);
MG_FREE(fus->lfn);
MG_FREE(fus);
mp->user_data = NULL;
/* Don't close the connection yet, there may be more files to come. */
break;
}
case MG_EV_HTTP_MULTIPART_REQUEST_END: {
mg_printf(nc,
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"
"Ok.\r\n");
nc->flags |= MG_F_SEND_AND_CLOSE;
break;
}
}
#if MG_ENABLE_CALLBACK_USERDATA
(void) user_data;
#endif
}
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
#endif /* MG_ENABLE_FILESYSTEM */
struct mg_connection *mg_connect_http_base(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
struct mg_connect_opts opts, const char *scheme1, const char *scheme2,
const char *scheme_ssl1, const char *scheme_ssl2, const char *url,
struct mg_str *path, struct mg_str *user_info, struct mg_str *host) {
struct mg_connection *nc = NULL;
unsigned int port_i = 0;
int use_ssl = 0;
struct mg_str scheme, query, fragment;
char conn_addr_buf[2];
char *conn_addr = conn_addr_buf;
if (mg_parse_uri(mg_mk_str(url), &scheme, user_info, host, &port_i, path,
&query, &fragment) != 0) {
MG_SET_PTRPTR(opts.error_string, "cannot parse url");
goto out;
}
/* If query is present, do not strip it. Pass to the caller. */
if (query.len > 0) path->len += query.len + 1;
if (scheme.len == 0 || mg_vcmp(&scheme, scheme1) == 0 ||
(scheme2 != NULL && mg_vcmp(&scheme, scheme2) == 0)) {
use_ssl = 0;
if (port_i == 0) port_i = 80;
} else if (mg_vcmp(&scheme, scheme_ssl1) == 0 ||
(scheme2 != NULL && mg_vcmp(&scheme, scheme_ssl2) == 0)) {
use_ssl = 1;
if (port_i == 0) port_i = 443;
} else {
goto out;
}
mg_asprintf(&conn_addr, sizeof(conn_addr_buf), "tcp://%.*s:%u",
(int) host->len, host->p, port_i);
if (conn_addr == NULL) goto out;
LOG(LL_DEBUG, ("%s use_ssl? %d %s", url, use_ssl, conn_addr));
if (use_ssl) {
#if MG_ENABLE_SSL
/*
* Schema requires SSL, but no SSL parameters were provided in opts.
* In order to maintain backward compatibility, use a faux-SSL with no
* verification.
*/
if (opts.ssl_ca_cert == NULL) {
opts.ssl_ca_cert = "*";
}
#else
MG_SET_PTRPTR(opts.error_string, "ssl is disabled");
goto out;
#endif
}
if ((nc = mg_connect_opt(mgr, conn_addr, MG_CB(ev_handler, user_data),
opts)) != NULL) {
mg_set_protocol_http_websocket(nc);
}
out:
if (conn_addr != NULL && conn_addr != conn_addr_buf) MG_FREE(conn_addr);
return nc;
}
struct mg_connection *mg_connect_http_opt(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
struct mg_connect_opts opts, const char *url, const char *extra_headers,
const char *post_data) {
struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR;
struct mg_str host = MG_NULL_STR, path = MG_NULL_STR;
struct mbuf auth;
struct mg_connection *nc =
mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
NULL, "https", NULL, url, &path, &user, &host);
if (nc == NULL) {
return NULL;
}
mbuf_init(&auth, 0);
if (user.len > 0) {
mg_basic_auth_header(user, null_str, &auth);
}
if (post_data == NULL) post_data = "";
if (extra_headers == NULL) extra_headers = "";
if (path.len == 0) path = mg_mk_str("/");
if (host.len == 0) host = mg_mk_str("");
mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT
"\r\n%.*s%s\r\n%s",
(post_data[0] == '\0' ? "GET" : "POST"), (int) path.len, path.p,
(int) (path.p - host.p), host.p, strlen(post_data), (int) auth.len,
(auth.buf == NULL ? "" : auth.buf), extra_headers, post_data);
mbuf_free(&auth);
return nc;
}
struct mg_connection *mg_connect_http(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
const char *url, const char *extra_headers, const char *post_data) {
struct mg_connect_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_connect_http_opt(mgr, MG_CB(ev_handler, user_data), opts, url,
extra_headers, post_data);
}
size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
size_t var_name_len, char *file_name,
size_t file_name_len, const char **data,
size_t *data_len) {
static const char cd[] = "Content-Disposition: ";
size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
int shl;
if (buf == NULL || buf_len <= 0) return 0;
if ((shl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0;
hl = shl;
if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
/* Get boundary length */
bl = mg_get_line_len(buf, buf_len);
/* Loop through headers, fetch variable name and file name */
var_name[0] = file_name[0] = '\0';
for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) {
if (mg_ncasecmp(cd, buf + n, cdl) == 0) {
struct mg_str header;
header.p = buf + n + cdl;
header.len = ll - (cdl + 2);
{
char *var_name2 = var_name;
mg_http_parse_header2(&header, "name", &var_name2, var_name_len);
/* TODO: handle reallocated buffer correctly */
if (var_name2 != var_name) {
MG_FREE(var_name2);
var_name[0] = '\0';
}
}
{
char *file_name2 = file_name;
mg_http_parse_header2(&header, "filename", &file_name2, file_name_len);
/* TODO: handle reallocated buffer correctly */
if (file_name2 != file_name) {
MG_FREE(file_name2);
file_name[0] = '\0';
}
}
}
}
/* Scan through the body, search for terminating boundary */
for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
if (buf[pos] == '-' && !strncmp(buf, &buf[pos], bl - 2)) {
if (data_len != NULL) *data_len = (pos - 2) - hl;
if (data != NULL) *data = buf + hl;
return pos;
}
}
return 0;
}
void mg_register_http_endpoint_opt(struct mg_connection *nc,
const char *uri_path,
mg_event_handler_t handler,
struct mg_http_endpoint_opts opts) {
struct mg_http_proto_data *pd = NULL;
struct mg_http_endpoint *new_ep = NULL;
if (nc == NULL) return;
new_ep = (struct mg_http_endpoint *) MG_CALLOC(1, sizeof(*new_ep));
if (new_ep == NULL) return;
pd = mg_http_get_proto_data(nc);
if (pd == NULL) pd = mg_http_create_proto_data(nc);
new_ep->uri_pattern = mg_strdup(mg_mk_str(uri_path));
if (opts.auth_domain != NULL && opts.auth_file != NULL) {
new_ep->auth_domain = strdup(opts.auth_domain);
new_ep->auth_file = strdup(opts.auth_file);
}
new_ep->handler = handler;
#if MG_ENABLE_CALLBACK_USERDATA
new_ep->user_data = opts.user_data;
#endif
new_ep->next = pd->endpoints;
pd->endpoints = new_ep;
}
static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
struct http_message *hm) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
void *user_data = nc->user_data;
if (ev == MG_EV_HTTP_REQUEST
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
|| ev == MG_EV_HTTP_MULTIPART_REQUEST
#endif
) {
struct mg_http_endpoint *ep =
mg_http_get_endpoint_handler(nc->listener, &hm->uri);
if (ep != NULL) {
#if MG_ENABLE_FILESYSTEM && !MG_DISABLE_HTTP_DIGEST_AUTH
if (!mg_http_is_authorized(hm, hm->uri, ep->auth_domain, ep->auth_file,
MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE)) {
mg_http_send_digest_auth_request(nc, ep->auth_domain);
return;
}
#endif
pd->endpoint_handler = ep->handler;
#if MG_ENABLE_CALLBACK_USERDATA
user_data = ep->user_data;
#endif
}
}
mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler,
user_data, ev, hm);
}
void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
MG_CB(mg_event_handler_t handler,
void *user_data)) {
struct mg_http_endpoint_opts opts;
memset(&opts, 0, sizeof(opts));
#if MG_ENABLE_CALLBACK_USERDATA
opts.user_data = user_data;
#endif
mg_register_http_endpoint_opt(nc, uri_path, handler, opts);
}
#endif /* MG_ENABLE_HTTP */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_http_cgi.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#ifndef _WIN32
#include <signal.h>
#endif
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI
#ifndef MG_MAX_CGI_ENVIR_VARS
#define MG_MAX_CGI_ENVIR_VARS 64
#endif
#ifndef MG_ENV_EXPORT_TO_CGI
#define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
#endif
#define MG_F_HTTP_CGI_PARSE_HEADERS MG_F_USER_1
/*
* This structure helps to create an environment for the spawned CGI program.
* Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
* last element must be NULL.
* However, on Windows there is a requirement that all these VARIABLE=VALUE\0
* strings must reside in a contiguous buffer. The end of the buffer is
* marked by two '\0' characters.
* We satisfy both worlds: we create an envp array (which is vars), all
* entries are actually pointers inside buf.
*/
struct mg_cgi_env_block {
struct mg_connection *nc;
char buf[MG_CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */
int len; /* Space taken */
int nvars; /* Number of variables in envp[] */
};
#ifdef _WIN32
struct mg_threadparam {
sock_t s;
HANDLE hPipe;
};
static int mg_wait_until_ready(sock_t sock, int for_read) {
fd_set set;
FD_ZERO(&set);
FD_SET(sock, &set);
return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1;
}
static void *mg_push_to_stdin(void *arg) {
struct mg_threadparam *tp = (struct mg_threadparam *) arg;
int n, sent, stop = 0;
DWORD k;
char buf[BUFSIZ];
while (!stop && mg_wait_until_ready(tp->s, 1) &&
(n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
for (sent = 0; !stop && sent < n; sent += k) {
if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
}
}
DBG(("%s", "FORWARED EVERYTHING TO CGI"));
CloseHandle(tp->hPipe);
MG_FREE(tp);
return NULL;
}
static void *mg_pull_from_stdout(void *arg) {
struct mg_threadparam *tp = (struct mg_threadparam *) arg;
int k = 0, stop = 0;
DWORD n, sent;
char buf[BUFSIZ];
while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
for (sent = 0; !stop && sent < n; sent += k) {
if (mg_wait_until_ready(tp->s, 0) &&
(k = send(tp->s, buf + sent, n - sent, 0)) <= 0)
stop = 1;
}
}
DBG(("%s", "EOF FROM CGI"));
CloseHandle(tp->hPipe);
shutdown(tp->s, 2); // Without this, IO thread may get truncated data
closesocket(tp->s);
MG_FREE(tp);
return NULL;
}
static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe,
void *(*func)(void *)) {
struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp));
if (tp != NULL) {
tp->s = sock;
tp->hPipe = hPipe;
mg_start_thread(func, tp);
}
}
static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) {
wchar_t buf[MG_MAX_PATH], buf2[MG_MAX_PATH];
to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
}
static int mg_start_process(const char *interp, const char *cmd,
const char *env, const char *envp[],
const char *dir, sock_t sock) {
STARTUPINFOW si;
PROCESS_INFORMATION pi;
HANDLE a[2], b[2], me = GetCurrentProcess();
wchar_t wcmd[MG_MAX_PATH], full_dir[MG_MAX_PATH];
char buf[MG_MAX_PATH], buf2[MG_MAX_PATH], buf5[MG_MAX_PATH],
buf4[MG_MAX_PATH], cmdline[MG_MAX_PATH];
DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
FILE *fp;
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
CreatePipe(&a[0], &a[1], NULL, 0);
CreatePipe(&b[0], &b[1], NULL, 0);
DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) {
buf[0] = buf[1] = '\0';
fgets(buf, sizeof(buf), fp);
buf[sizeof(buf) - 1] = '\0';
if (buf[0] == '#' && buf[1] == '!') {
interp = buf + 2;
/* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */
while (*interp != '\0' && isspace(*(unsigned char *) interp)) {
interp++;
}
}
fclose(fp);
}
snprintf(buf, sizeof(buf), "%s/%s", dir, cmd);
mg_abs_path(buf, buf2, ARRAY_SIZE(buf2));
mg_abs_path(dir, buf5, ARRAY_SIZE(buf5));
to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
if (interp != NULL) {
mg_abs_path(interp, buf4, ARRAY_SIZE(buf4));
snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2);
} else {
snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2);
}
to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
(void *) env, full_dir, &si, &pi) != 0) {
mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin);
mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout);
CloseHandle(si.hStdOutput);
CloseHandle(si.hStdInput);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
} else {
CloseHandle(a[1]);
CloseHandle(b[0]);
closesocket(sock);
}
DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
/* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */
(void) envp;
return (pi.hProcess != NULL);
}
#else
static int mg_start_process(const char *interp, const char *cmd,
const char *env, const char *envp[],
const char *dir, sock_t sock) {
char buf[500];
pid_t pid = fork();
(void) env;
if (pid == 0) {
/*
* In Linux `chdir` declared with `warn_unused_result` attribute
* To shutup compiler we have yo use result in some way
*/
int tmp = chdir(dir);
(void) tmp;
(void) dup2(sock, 0);
(void) dup2(sock, 1);
closesocket(sock);
/*
* After exec, all signal handlers are restored to their default values,
* with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
* implementation, SIGCHLD's handler will leave unchanged after exec
* if it was set to be ignored. Restore it to default action.
*/
signal(SIGCHLD, SIG_DFL);
if (interp == NULL) {
execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */
} else {
execle(interp, interp, cmd, (char *) 0, envp);
}
snprintf(buf, sizeof(buf),
"Status: 500\r\n\r\n"
"500 Server Error: %s%s%s: %s",
interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd,
strerror(errno));
send(1, buf, strlen(buf), 0);
_exit(EXIT_FAILURE); /* exec call failed */
}
return (pid != 0);
}
#endif /* _WIN32 */
/*
* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
* pointer into the vars array.
*/
static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) {
int n, space;
char *added = block->buf + block->len;
va_list ap;
/* Calculate how much space is left in the buffer */
space = sizeof(block->buf) - (block->len + 2);
if (space > 0) {
/* Copy VARIABLE=VALUE\0 string into the free space */
va_start(ap, fmt);
n = vsnprintf(added, (size_t) space, fmt, ap);
va_end(ap);
/* Make sure we do not overflow buffer and the envp array */
if (n > 0 && n + 1 < space &&
block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
/* Append a pointer to the added string into the envp array */
block->vars[block->nvars++] = added;
/* Bump up used length counter. Include \0 terminator */
block->len += n + 1;
}
}
return added;
}
static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) {
const char *s;
if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s);
}
static void mg_prepare_cgi_environment(struct mg_connection *nc,
const char *prog,
const struct mg_str *path_info,
const struct http_message *hm,
const struct mg_serve_http_opts *opts,
struct mg_cgi_env_block *blk) {
const char *s;
struct mg_str *h;
char *p;
size_t i;
char buf[100];
size_t path_info_len = path_info != NULL ? path_info->len : 0;
blk->len = blk->nvars = 0;
blk->nc = nc;
if ((s = getenv("SERVER_NAME")) != NULL) {
mg_addenv(blk, "SERVER_NAME=%s", s);
} else {
mg_sock_to_str(nc->sock, buf, sizeof(buf), 3);
mg_addenv(blk, "SERVER_NAME=%s", buf);
}
mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root);
mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root);
mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION);
/* Prepare the environment block */
mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p);
mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p,
hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len,
hm->query_string.p);
mg_conn_addr_to_str(nc, buf, sizeof(buf),
MG_SOCK_STRINGIFY_REMOTE | MG_SOCK_STRINGIFY_IP);
mg_addenv(blk, "REMOTE_ADDR=%s", buf);
mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_PORT);
mg_addenv(blk, "SERVER_PORT=%s", buf);
s = hm->uri.p + hm->uri.len - path_info_len - 1;
if (*s == '/') {
const char *base_name = strrchr(prog, DIRSEP);
mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p,
(base_name != NULL ? base_name + 1 : prog));
} else {
mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p);
}
mg_addenv(blk, "SCRIPT_FILENAME=%s", prog);
if (path_info != NULL && path_info->len > 0) {
mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p);
/* Not really translated... */
mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p);
}
#if MG_ENABLE_SSL
mg_addenv(blk, "HTTPS=%s", (nc->flags & MG_F_SSL ? "on" : "off"));
#else
mg_addenv(blk, "HTTPS=off");
#endif
if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) !=
NULL) {
mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p);
}
if (hm->query_string.len > 0) {
mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len,
hm->query_string.p);
}
if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) !=
NULL) {
mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p);
}
mg_addenv2(blk, "PATH");
mg_addenv2(blk, "TMP");
mg_addenv2(blk, "TEMP");
mg_addenv2(blk, "TMPDIR");
mg_addenv2(blk, "PERLLIB");
mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI);
#ifdef _WIN32
mg_addenv2(blk, "COMSPEC");
mg_addenv2(blk, "SYSTEMROOT");
mg_addenv2(blk, "SystemDrive");
mg_addenv2(blk, "ProgramFiles");
mg_addenv2(blk, "ProgramFiles(x86)");
mg_addenv2(blk, "CommonProgramFiles(x86)");
#else
mg_addenv2(blk, "LD_LIBRARY_PATH");
#endif /* _WIN32 */
/* Add all headers as HTTP_* variables */
for (i = 0; hm->header_names[i].len > 0; i++) {
p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len,
hm->header_names[i].p, (int) hm->header_values[i].len,
hm->header_values[i].p);
/* Convert variable name into uppercase, and change - to _ */
for (; *p != '=' && *p != '\0'; p++) {
if (*p == '-') *p = '_';
*p = (char) toupper(*(unsigned char *) p);
}
}
blk->vars[blk->nvars++] = NULL;
blk->buf[blk->len++] = '\0';
}
static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
#if !MG_ENABLE_CALLBACK_USERDATA
void *user_data = cgi_nc->user_data;
#endif
struct mg_connection *nc = (struct mg_connection *) user_data;
(void) ev_data;
if (nc == NULL) {
/* The corresponding network connection was closed. */
cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return;
}
switch (ev) {
case MG_EV_RECV:
/*
* CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n"
* It outputs headers, then body. Headers might include "Status"
* header, which changes CODE, and it might include "Location" header
* which changes CODE to 302.
*
* Therefore we do not send the output from the CGI script to the user
* until all CGI headers are received.
*
* Here we parse the output from the CGI script, and if all headers has
* been received, send appropriate reply line, and forward all
* received headers to the client.
*/
if (nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS) {
struct mbuf *io = &cgi_nc->recv_mbuf;
int len = mg_http_get_request_len(io->buf, io->len);
if (len == 0) break;
if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) {
cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
mg_http_send_error(nc, 500, "Bad headers");
} else {
struct http_message hm;
struct mg_str *h;
mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm);
if (mg_get_http_header(&hm, "Location") != NULL) {
mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n");
} else if ((h = mg_get_http_header(&hm, "Status")) != NULL) {
mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p);
} else {
mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n");
}
}
nc->flags &= ~MG_F_HTTP_CGI_PARSE_HEADERS;
}
if (!(nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS)) {
mg_forward(cgi_nc, nc);
}
break;
case MG_EV_CLOSE:
DBG(("%p CLOSE", cgi_nc));
mg_http_free_proto_data_cgi(&mg_http_get_proto_data(nc)->cgi);
nc->flags |= MG_F_SEND_AND_CLOSE;
break;
}
}
MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
const struct mg_str *path_info,
const struct http_message *hm,
const struct mg_serve_http_opts *opts) {
struct mg_cgi_env_block blk;
char dir[MG_MAX_PATH];
const char *p;
sock_t fds[2];
DBG(("%p [%s]", nc, prog));
mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk);
/*
* CGI must be executed in its own directory. 'dir' must point to the
* directory containing executable program, 'p' must point to the
* executable program name relative to 'dir'.
*/
if ((p = strrchr(prog, DIRSEP)) == NULL) {
snprintf(dir, sizeof(dir), "%s", ".");
} else {
snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
prog = p + 1;
}
if (!mg_socketpair(fds, SOCK_STREAM)) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return;
}
#ifndef _WIN32
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_handler = SIG_IGN;
sa.sa_flags = 0;
sigaction(SIGCHLD, &sa, NULL);
#endif
if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir,
fds[1]) != 0) {
struct mg_connection *cgi_nc =
mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler MG_UD_ARG(nc));
struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(nc);
cgi_pd->cgi.cgi_nc = cgi_nc;
#if !MG_ENABLE_CALLBACK_USERDATA
cgi_pd->cgi.cgi_nc->user_data = nc;
#endif
nc->flags |= MG_F_HTTP_CGI_PARSE_HEADERS;
/* Push POST data to the CGI */
if (hm->body.len > 0) {
mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, hm->body.len);
}
mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len);
} else {
closesocket(fds[0]);
mg_http_send_error(nc, 500, "CGI failure");
}
#ifndef _WIN32
closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */
#endif
}
MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) {
if (d == NULL) return;
if (d->cgi_nc != NULL) {
d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
d->cgi_nc->user_data = NULL;
}
memset(d, 0, sizeof(*d));
}
#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_http_ssi.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM
static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
const char *path, FILE *fp, int include_level,
const struct mg_serve_http_opts *opts);
static void mg_send_file_data(struct mg_connection *nc, FILE *fp) {
char buf[BUFSIZ];
size_t n;
while ((n = mg_fread(buf, 1, sizeof(buf), fp)) > 0) {
mg_send(nc, buf, n);
}
}
static void mg_do_ssi_include(struct mg_connection *nc, struct http_message *hm,
const char *ssi, char *tag, int include_level,
const struct mg_serve_http_opts *opts) {
char file_name[MG_MAX_PATH], path[MG_MAX_PATH], *p;
FILE *fp;
/*
* sscanf() is safe here, since send_ssi_file() also uses buffer
* of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
*/
if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
/* File name is relative to the webserver root */
snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name);
} else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
/*
* File name is relative to the webserver working directory
* or it is absolute system path
*/
snprintf(path, sizeof(path), "%s", file_name);
} else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
/* File name is relative to the currect document */
snprintf(path, sizeof(path), "%s", ssi);
if ((p = strrchr(path, DIRSEP)) != NULL) {
p[1] = '\0';
}
snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name);
} else {
mg_printf(nc, "Bad SSI #include: [%s]", tag);
return;
}
if ((fp = mg_fopen(path, "rb")) == NULL) {
mg_printf(nc, "SSI include error: mg_fopen(%s): %s", path,
strerror(mg_get_errno()));
} else {
mg_set_close_on_exec((sock_t) fileno(fp));
if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) >
0) {
mg_send_ssi_file(nc, hm, path, fp, include_level + 1, opts);
} else {
mg_send_file_data(nc, fp);
}
fclose(fp);
}
}
#if MG_ENABLE_HTTP_SSI_EXEC
static void do_ssi_exec(struct mg_connection *nc, char *tag) {
char cmd[BUFSIZ];
FILE *fp;
if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
mg_printf(nc, "Bad SSI #exec: [%s]", tag);
} else if ((fp = popen(cmd, "r")) == NULL) {
mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(mg_get_errno()));
} else {
mg_send_file_data(nc, fp);
pclose(fp);
}
}
#endif /* MG_ENABLE_HTTP_SSI_EXEC */
/*
* SSI directive has the following format:
* <!--#directive parameter=value parameter=value -->
*/
static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
const char *path, FILE *fp, int include_level,
const struct mg_serve_http_opts *opts) {
static const struct mg_str btag = MG_MK_STR("<!--#");
static const struct mg_str d_include = MG_MK_STR("include");
static const struct mg_str d_call = MG_MK_STR("call");
#if MG_ENABLE_HTTP_SSI_EXEC
static const struct mg_str d_exec = MG_MK_STR("exec");
#endif
char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */
int ch, len, in_ssi_tag;
if (include_level > 10) {
mg_printf(nc, "SSI #include level is too deep (%s)", path);
return;
}
in_ssi_tag = len = 0;
while ((ch = fgetc(fp)) != EOF) {
if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
size_t i = len - 2;
in_ssi_tag = 0;
/* Trim closing --> */
buf[i--] = '\0';
while (i > 0 && buf[i] == ' ') {
buf[i--] = '\0';
}
/* Handle known SSI directives */
if (strncmp(p, d_include.p, d_include.len) == 0) {
mg_do_ssi_include(nc, hm, path, p + d_include.len + 1, include_level,
opts);
} else if (strncmp(p, d_call.p, d_call.len) == 0) {
struct mg_ssi_call_ctx cctx;
memset(&cctx, 0, sizeof(cctx));
cctx.req = hm;
cctx.file = mg_mk_str(path);
cctx.arg = mg_mk_str(p + d_call.len + 1);
mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL,
(void *) cctx.arg.p); /* NUL added above */
mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL_CTX, &cctx);
#if MG_ENABLE_HTTP_SSI_EXEC
} else if (strncmp(p, d_exec.p, d_exec.len) == 0) {
do_ssi_exec(nc, p + d_exec.len + 1);
#endif
} else {
/* Silently ignore unknown SSI directive. */
}
len = 0;
} else if (ch == '<') {
in_ssi_tag = 1;
if (len > 0) {
mg_send(nc, buf, (size_t) len);
}
len = 0;
buf[len++] = ch & 0xff;
} else if (in_ssi_tag) {
if (len == (int) btag.len && strncmp(buf, btag.p, btag.len) != 0) {
/* Not an SSI tag */
in_ssi_tag = 0;
} else if (len == (int) sizeof(buf) - 2) {
mg_printf(nc, "%s: SSI tag is too large", path);
len = 0;
}
buf[len++] = ch & 0xff;
} else {
buf[len++] = ch & 0xff;
if (len == (int) sizeof(buf)) {
mg_send(nc, buf, (size_t) len);
len = 0;
}
}
}
/* Send the rest of buffered data */
if (len > 0) {
mg_send(nc, buf, (size_t) len);
}
}
MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
struct http_message *hm,
const char *path,
const struct mg_serve_http_opts *opts) {
FILE *fp;
struct mg_str mime_type;
DBG(("%p %s", nc, path));
if ((fp = mg_fopen(path, "rb")) == NULL) {
mg_http_send_error(nc, 404, NULL);
} else {
mg_set_close_on_exec((sock_t) fileno(fp));
mime_type = mg_get_mime_type(path, "text/plain", opts);
mg_send_response_line(nc, 200, opts->extra_headers);
mg_printf(nc,
"Content-Type: %.*s\r\n"
"Connection: close\r\n\r\n",
(int) mime_type.len, mime_type.p);
mg_send_ssi_file(nc, hm, path, fp, 0, opts);
fclose(fp);
nc->flags |= MG_F_SEND_AND_CLOSE;
}
}
#endif /* MG_ENABLE_HTTP_SSI && MG_ENABLE_HTTP && MG_ENABLE_FILESYSTEM */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_http_webdav.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV
MG_INTERNAL int mg_is_dav_request(const struct mg_str *s) {
static const char *methods[] = {
"PUT",
"DELETE",
"MKCOL",
"PROPFIND",
"MOVE"
#if MG_ENABLE_FAKE_DAVLOCK
,
"LOCK",
"UNLOCK"
#endif
};
size_t i;
for (i = 0; i < ARRAY_SIZE(methods); i++) {
if (mg_vcmp(s, methods[i]) == 0) {
return 1;
}
}
return 0;
}
static int mg_mkdir(const char *path, uint32_t mode) {
#ifndef _WIN32
return mkdir(path, mode);
#else
(void) mode;
return _mkdir(path);
#endif
}
static void mg_print_props(struct mg_connection *nc, const char *name,
cs_stat_t *stp) {
char mtime[64];
time_t t = stp->st_mtime; /* store in local variable for NDK compile */
struct mg_str name_esc = mg_url_encode(mg_mk_str(name));
mg_gmt_time_string(mtime, sizeof(mtime), &t);
mg_printf(nc,
"<d:response>"
"<d:href>%s</d:href>"
"<d:propstat>"
"<d:prop>"
"<d:resourcetype>%s</d:resourcetype>"
"<d:getcontentlength>%" INT64_FMT
"</d:getcontentlength>"
"<d:getlastmodified>%s</d:getlastmodified>"
"</d:prop>"
"<d:status>HTTP/1.1 200 OK</d:status>"
"</d:propstat>"
"</d:response>\n",
name_esc.p, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
(int64_t) stp->st_size, mtime);
free((void *) name_esc.p);
}
MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
cs_stat_t *stp, struct http_message *hm,
struct mg_serve_http_opts *opts) {
static const char header[] =
"HTTP/1.1 207 Multi-Status\r\n"
"Connection: close\r\n"
"Content-Type: text/xml; charset=utf-8\r\n\r\n"
"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<d:multistatus xmlns:d='DAV:'>\n";
static const char footer[] = "</d:multistatus>\n";
const struct mg_str *depth = mg_get_http_header(hm, "Depth");
/* Print properties for the requested resource itself */
if (S_ISDIR(stp->st_mode) &&
strcmp(opts->enable_directory_listing, "yes") != 0) {
mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
} else {
char uri[MG_MAX_PATH];
mg_send(nc, header, sizeof(header) - 1);
snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p);
mg_print_props(nc, uri, stp);
if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) {
mg_scan_directory(nc, path, opts, mg_print_props);
}
mg_send(nc, footer, sizeof(footer) - 1);
nc->flags |= MG_F_SEND_AND_CLOSE;
}
}
#if MG_ENABLE_FAKE_DAVLOCK
/*
* Windows explorer (probably there are another WebDav clients like it)
* requires LOCK support in webdav. W/out this, it still works, but fails
* to save file: shows error message and offers "Save As".
* "Save as" works, but this message is very annoying.
* This is fake lock, which doesn't lock something, just returns LOCK token,
* UNLOCK always answers "OK".
* With this fake LOCK Windows Explorer looks happy and saves file.
* NOTE: that is not DAV LOCK imlementation, it is just a way to shut up
* Windows native DAV client. This is why FAKE LOCK is not enabed by default
*/
MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path) {
static const char *reply =
"HTTP/1.1 207 Multi-Status\r\n"
"Connection: close\r\n"
"Content-Type: text/xml; charset=utf-8\r\n\r\n"
"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<d:multistatus xmlns:d='DAV:'>\n"
"<D:lockdiscovery>\n"
"<D:activelock>\n"
"<D:locktoken>\n"
"<D:href>\n"
"opaquelocktoken:%s%u"
"</D:href>"
"</D:locktoken>"
"</D:activelock>\n"
"</D:lockdiscovery>"
"</d:multistatus>\n";
mg_printf(nc, reply, path, (unsigned int) mg_time());
nc->flags |= MG_F_SEND_AND_CLOSE;
}
#endif
MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
struct http_message *hm) {
int status_code = 500;
if (hm->body.len != (size_t) ~0 && hm->body.len > 0) {
status_code = 415;
} else if (!mg_mkdir(path, 0755)) {
status_code = 201;
} else if (errno == EEXIST) {
status_code = 405;
} else if (errno == EACCES) {
status_code = 403;
} else if (errno == ENOENT) {
status_code = 409;
} else {
status_code = 500;
}
mg_http_send_error(nc, status_code, NULL);
}
static int mg_remove_directory(const struct mg_serve_http_opts *opts,
const char *dir) {
char path[MG_MAX_PATH];
struct dirent *dp;
cs_stat_t st;
DIR *dirp;
if ((dirp = opendir(dir)) == NULL) return 0;
while ((dp = readdir(dirp)) != NULL) {
if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
continue;
}
snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
mg_stat(path, &st);
if (S_ISDIR(st.st_mode)) {
mg_remove_directory(opts, path);
} else {
remove(path);
}
}
closedir(dirp);
rmdir(dir);
return 1;
}
MG_INTERNAL void mg_handle_move(struct mg_connection *c,
const struct mg_serve_http_opts *opts,
const char *path, struct http_message *hm) {
const struct mg_str *dest = mg_get_http_header(hm, "Destination");
if (dest == NULL) {
mg_http_send_error(c, 411, NULL);
} else {
const char *p = (char *) memchr(dest->p, '/', dest->len);
if (p != NULL && p[1] == '/' &&
(p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) {
char buf[MG_MAX_PATH];
snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root,
(int) (dest->p + dest->len - p), p);
if (rename(path, buf) == 0) {
mg_http_send_error(c, 200, NULL);
} else {
mg_http_send_error(c, 418, NULL);
}
} else {
mg_http_send_error(c, 500, NULL);
}
}
}
MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
const struct mg_serve_http_opts *opts,
const char *path) {
cs_stat_t st;
if (mg_stat(path, &st) != 0) {
mg_http_send_error(nc, 404, NULL);
} else if (S_ISDIR(st.st_mode)) {
mg_remove_directory(opts, path);
mg_http_send_error(nc, 204, NULL);
} else if (remove(path) == 0) {
mg_http_send_error(nc, 204, NULL);
} else {
mg_http_send_error(nc, 423, NULL);
}
}
/* Return -1 on error, 1 on success. */
static int mg_create_itermediate_directories(const char *path) {
const char *s;
/* Create intermediate directories if they do not exist */
for (s = path + 1; *s != '\0'; s++) {
if (*s == '/') {
char buf[MG_MAX_PATH];
cs_stat_t st;
snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path);
buf[sizeof(buf) - 1] = '\0';
if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) {
return -1;
}
}
}
return 1;
}
MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
struct http_message *hm) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
cs_stat_t st;
const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length");
int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201;
mg_http_free_proto_data_file(&pd->file);
if ((rc = mg_create_itermediate_directories(path)) == 0) {
mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
} else if (rc == -1) {
mg_http_send_error(nc, 500, NULL);
} else if (cl_hdr == NULL) {
mg_http_send_error(nc, 411, NULL);
} else if ((pd->file.fp = mg_fopen(path, "w+b")) == NULL) {
mg_http_send_error(nc, 500, NULL);
} else {
const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range");
int64_t r1 = 0, r2 = 0;
pd->file.type = DATA_PUT;
mg_set_close_on_exec((sock_t) fileno(pd->file.fp));
pd->file.cl = to64(cl_hdr->p);
if (range_hdr != NULL &&
mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) {
status_code = 206;
fseeko(pd->file.fp, r1, SEEK_SET);
pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1;
}
mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
/* Remove HTTP request from the mbuf, leave only payload */
mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len);
mg_http_transfer_file_data(nc);
}
}
#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_http_websocket.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET
/* Amalgamated: #include "common/cs_sha1.h" */
#ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS
#define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5
#endif
#define FLAGS_MASK_FIN (1 << 7)
#define FLAGS_MASK_OP 0x0f
static int mg_is_ws_fragment(unsigned char flags) {
return (flags & FLAGS_MASK_FIN) == 0 ||
(flags & FLAGS_MASK_OP) == WEBSOCKET_OP_CONTINUE;
}
static int mg_is_ws_first_fragment(unsigned char flags) {
return (flags & FLAGS_MASK_FIN) == 0 &&
(flags & FLAGS_MASK_OP) != WEBSOCKET_OP_CONTINUE;
}
static int mg_is_ws_control_frame(unsigned char flags) {
unsigned char op = (flags & FLAGS_MASK_OP);
return op == WEBSOCKET_OP_CLOSE || op == WEBSOCKET_OP_PING ||
op == WEBSOCKET_OP_PONG;
}
static void mg_handle_incoming_websocket_frame(struct mg_connection *nc,
struct websocket_message *wsm) {
if (wsm->flags & 0x8) {
mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm);
} else {
mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_FRAME, wsm);
}
}
static struct mg_ws_proto_data *mg_ws_get_proto_data(struct mg_connection *nc) {
struct mg_http_proto_data *htd = mg_http_get_proto_data(nc);
return (htd != NULL ? &htd->ws_data : NULL);
}
/*
* Sends a Close websocket frame with the given data, and closes the underlying
* connection. If `len` is ~0, strlen(data) is used.
*/
static void mg_ws_close(struct mg_connection *nc, const void *data,
size_t len) {
if ((int) len == ~0) {
len = strlen((const char *) data);
}
mg_send_websocket_frame(nc, WEBSOCKET_OP_CLOSE, data, len);
nc->flags |= MG_F_SEND_AND_CLOSE;
}
static int mg_deliver_websocket_data(struct mg_connection *nc) {
/* Using unsigned char *, cause of integer arithmetic below */
uint64_t i, data_len = 0, frame_len = 0, new_data_len = nc->recv_mbuf.len,
len, mask_len = 0, header_len = 0;
struct mg_ws_proto_data *wsd = mg_ws_get_proto_data(nc);
unsigned char *new_data = (unsigned char *) nc->recv_mbuf.buf,
*e = (unsigned char *) nc->recv_mbuf.buf + nc->recv_mbuf.len;
uint8_t flags;
int ok, reass;
if (wsd->reass_len > 0) {
/*
* We already have some previously received data which we need to
* reassemble and deliver to the client code when we get the final
* fragment.
*
* NOTE: it doesn't mean that the current message must be a continuation:
* it might be a control frame (Close, Ping or Pong), which should be
* handled without breaking the fragmented message.
*/
size_t existing_len = wsd->reass_len;
assert(new_data_len >= existing_len);
new_data += existing_len;
new_data_len -= existing_len;
}
flags = new_data[0];
reass = new_data_len > 0 && mg_is_ws_fragment(flags) &&
!(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG);
if (reass && mg_is_ws_control_frame(flags)) {
/*
* Control frames can't be fragmented, so if we encounter fragmented
* control frame, close connection immediately.
*/
mg_ws_close(nc, "fragmented control frames are illegal", ~0);
return 0;
} else if (new_data_len > 0 && !reass && !mg_is_ws_control_frame(flags) &&
wsd->reass_len > 0) {
/*
* When in the middle of a fragmented message, only the continuations
* and control frames are allowed.
*/
mg_ws_close(nc, "non-continuation in the middle of a fragmented message",
~0);
return 0;
}
if (new_data_len >= 2) {
len = new_data[1] & 0x7f;
mask_len = new_data[1] & FLAGS_MASK_FIN ? 4 : 0;
if (len < 126 && new_data_len >= mask_len) {
data_len = len;
header_len = 2 + mask_len;
} else if (len == 126 && new_data_len >= 4 + mask_len) {
header_len = 4 + mask_len;
data_len = ntohs(*(uint16_t *) &new_data[2]);
} else if (new_data_len >= 10 + mask_len) {
header_len = 10 + mask_len;
data_len = (((uint64_t) ntohl(*(uint32_t *) &new_data[2])) << 32) +
ntohl(*(uint32_t *) &new_data[6]);
}
}
frame_len = header_len + data_len;
ok = (frame_len > 0 && frame_len <= new_data_len);
/* Check for overflow */
if (frame_len < header_len || frame_len < data_len) {
ok = 0;
mg_ws_close(nc, "overflowed message", ~0);
}
if (ok) {
size_t cleanup_len = 0;
struct websocket_message wsm;
wsm.size = (size_t) data_len;
wsm.data = new_data + header_len;
wsm.flags = flags;
/* Apply mask if necessary */
if (mask_len > 0) {
for (i = 0; i < data_len; i++) {
new_data[i + header_len] ^= (new_data + header_len - mask_len)[i % 4];
}
}
if (reass) {
/* This is a message fragment */
if (mg_is_ws_first_fragment(flags)) {
/*
* On the first fragmented frame, skip the first byte (op) and also
* reset size to 1 (op), it'll be incremented with the data len below.
*/
new_data += 1;
wsd->reass_len = 1 /* op */;
}
/* Append this frame to the reassembled buffer */
memmove(new_data, wsm.data, e - wsm.data);
wsd->reass_len += wsm.size;
nc->recv_mbuf.len -= wsm.data - new_data;
if (flags & FLAGS_MASK_FIN) {
/* On last fragmented frame - call user handler and remove data */
wsm.flags = FLAGS_MASK_FIN | nc->recv_mbuf.buf[0];
wsm.data = (unsigned char *) nc->recv_mbuf.buf + 1 /* op */;
wsm.size = wsd->reass_len - 1 /* op */;
cleanup_len = wsd->reass_len;
wsd->reass_len = 0;
/* Pass reassembled message to the client code. */
mg_handle_incoming_websocket_frame(nc, &wsm);
mbuf_remove(&nc->recv_mbuf, cleanup_len); /* Cleanup frame */
}
} else {
/*
* This is a complete message, not a fragment. It might happen in between
* of a fragmented message (in this case, WebSocket protocol requires
* current message to be a control frame).
*/
cleanup_len = (size_t) frame_len;
/* First of all, check if we need to react on a control frame. */
switch (flags & FLAGS_MASK_OP) {
case WEBSOCKET_OP_PING:
mg_send_websocket_frame(nc, WEBSOCKET_OP_PONG, wsm.data, wsm.size);
break;
case WEBSOCKET_OP_CLOSE:
mg_ws_close(nc, wsm.data, wsm.size);
break;
}
/* Pass received message to the client code. */
mg_handle_incoming_websocket_frame(nc, &wsm);
/* Cleanup frame */
memmove(nc->recv_mbuf.buf + wsd->reass_len,
nc->recv_mbuf.buf + wsd->reass_len + cleanup_len,
nc->recv_mbuf.len - wsd->reass_len - cleanup_len);
nc->recv_mbuf.len -= cleanup_len;
}
}
return ok;
}
struct ws_mask_ctx {
size_t pos; /* zero means unmasked */
uint32_t mask;
};
static uint32_t mg_ws_random_mask(void) {
uint32_t mask;
/*
* The spec requires WS client to generate hard to
* guess mask keys. From RFC6455, Section 5.3:
*
* The unpredictability of the masking key is essential to prevent
* authors of malicious applications from selecting the bytes that appear on
* the wire.
*
* Hence this feature is essential when the actual end user of this API
* is untrusted code that wouldn't have access to a lower level net API
* anyway (e.g. web browsers). Hence this feature is low prio for most
* mongoose use cases and thus can be disabled, e.g. when porting to a platform
* that lacks rand().
*/
#if MG_DISABLE_WS_RANDOM_MASK
mask = 0xefbeadde; /* generated with a random number generator, I swear */
#else
if (sizeof(long) >= 4) {
mask = (uint32_t) rand();
} else if (sizeof(long) == 2) {
mask = (uint32_t) rand() << 16 | (uint32_t) rand();
}
#endif
return mask;
}
static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len,
struct ws_mask_ctx *ctx) {
int header_len;
unsigned char header[10];
header[0] =
(op & WEBSOCKET_DONT_FIN ? 0x0 : FLAGS_MASK_FIN) | (op & FLAGS_MASK_OP);
if (len < 126) {
header[1] = (unsigned char) len;
header_len = 2;
} else if (len < 65535) {
uint16_t tmp = htons((uint16_t) len);
header[1] = 126;
memcpy(&header[2], &tmp, sizeof(tmp));
header_len = 4;
} else {
uint32_t tmp;
header[1] = 127;
tmp = htonl((uint32_t)((uint64_t) len >> 32));
memcpy(&header[2], &tmp, sizeof(tmp));
tmp = htonl((uint32_t)(len & 0xffffffff));
memcpy(&header[6], &tmp, sizeof(tmp));
header_len = 10;
}
/* client connections enable masking */
if (nc->listener == NULL) {
header[1] |= 1 << 7; /* set masking flag */
mg_send(nc, header, header_len);
ctx->mask = mg_ws_random_mask();
mg_send(nc, &ctx->mask, sizeof(ctx->mask));
ctx->pos = nc->send_mbuf.len;
} else {
mg_send(nc, header, header_len);
ctx->pos = 0;
}
}
static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) {
size_t i;
if (ctx->pos == 0) return;
for (i = 0; i < (mbuf->len - ctx->pos); i++) {
mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4];
}
}
void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data,
size_t len) {
struct ws_mask_ctx ctx;
DBG(("%p %d %d", nc, op, (int) len));
mg_send_ws_header(nc, op, len, &ctx);
mg_send(nc, data, len);
mg_ws_mask_frame(&nc->send_mbuf, &ctx);
if (op == WEBSOCKET_OP_CLOSE) {
nc->flags |= MG_F_SEND_AND_CLOSE;
}
}
void mg_send_websocket_framev(struct mg_connection *nc, int op,
const struct mg_str *strv, int strvcnt) {
struct ws_mask_ctx ctx;
int i;
int len = 0;
for (i = 0; i < strvcnt; i++) {
len += strv[i].len;
}
mg_send_ws_header(nc, op, len, &ctx);
for (i = 0; i < strvcnt; i++) {
mg_send(nc, strv[i].p, strv[i].len);
}
mg_ws_mask_frame(&nc->send_mbuf, &ctx);
if (op == WEBSOCKET_OP_CLOSE) {
nc->flags |= MG_F_SEND_AND_CLOSE;
}
}
void mg_printf_websocket_frame(struct mg_connection *nc, int op,
const char *fmt, ...) {
char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
va_list ap;
int len;
va_start(ap, fmt);
if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
mg_send_websocket_frame(nc, op, buf, len);
}
va_end(ap);
if (buf != mem && buf != NULL) {
MG_FREE(buf);
}
}
MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
mg_call(nc, nc->handler, nc->user_data, ev, ev_data);
switch (ev) {
case MG_EV_RECV:
do {
} while (mg_deliver_websocket_data(nc));
break;
case MG_EV_POLL:
/* Ping idle websocket connections */
{
time_t now = *(time_t *) ev_data;
if (nc->flags & MG_F_IS_WEBSOCKET &&
now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) {
mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0);
}
}
break;
default:
break;
}
#if MG_ENABLE_CALLBACK_USERDATA
(void) user_data;
#endif
}
#ifndef MG_EXT_SHA1
void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
const size_t *msg_lens, uint8_t *digest) {
size_t i;
cs_sha1_ctx sha_ctx;
cs_sha1_init(&sha_ctx);
for (i = 0; i < num_msgs; i++) {
cs_sha1_update(&sha_ctx, msgs[i], msg_lens[i]);
}
cs_sha1_final(digest, &sha_ctx);
}
#else
extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
const size_t *msg_lens, uint8_t *digest);
#endif
MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
const struct mg_str *key,
struct http_message *hm) {
static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
const uint8_t *msgs[2] = {(const uint8_t *) key->p, (const uint8_t *) magic};
const size_t msg_lens[2] = {key->len, 36};
unsigned char sha[20];
char b64_sha[30];
struct mg_str *s;
mg_hash_sha1_v(2, msgs, msg_lens, sha);
mg_base64_encode(sha, sizeof(sha), b64_sha);
mg_printf(nc, "%s",
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n");
s = mg_get_http_header(hm, "Sec-WebSocket-Protocol");
if (s != NULL) {
mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) s->len, s->p);
}
mg_printf(nc, "Sec-WebSocket-Accept: %s%s", b64_sha, "\r\n\r\n");
DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha));
}
void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
const char *host, const char *protocol,
const char *extra_headers) {
mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL,
NULL);
}
void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path,
const char *host, const char *protocol,
const char *extra_headers, const char *user,
const char *pass) {
mg_send_websocket_handshake3v(nc, mg_mk_str(path), mg_mk_str(host),
mg_mk_str(protocol), mg_mk_str(extra_headers),
mg_mk_str(user), mg_mk_str(pass));
}
void mg_send_websocket_handshake3v(struct mg_connection *nc,
const struct mg_str path,
const struct mg_str host,
const struct mg_str protocol,
const struct mg_str extra_headers,
const struct mg_str user,
const struct mg_str pass) {
struct mbuf auth;
char key[25];
uint32_t nonce[4];
nonce[0] = mg_ws_random_mask();
nonce[1] = mg_ws_random_mask();
nonce[2] = mg_ws_random_mask();
nonce[3] = mg_ws_random_mask();
mg_base64_encode((unsigned char *) &nonce, sizeof(nonce), key);
mbuf_init(&auth, 0);
if (user.len > 0) {
mg_basic_auth_header(user, pass, &auth);
}
/*
* NOTE: the (auth.buf == NULL ? "" : auth.buf) is because cc3200 libc is
* broken: it doesn't like zero length to be passed to %.*s
* i.e. sprintf("f%.*so", (int)0, NULL), yields `f\0o`.
* because it handles NULL specially (and incorrectly).
*/
mg_printf(nc,
"GET %.*s HTTP/1.1\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"%.*s"
"Sec-WebSocket-Version: 13\r\n"
"Sec-WebSocket-Key: %s\r\n",
(int) path.len, path.p, (int) auth.len,
(auth.buf == NULL ? "" : auth.buf), key);
/* TODO(mkm): take default hostname from http proto data if host == NULL */
if (host.len > 0) {
int host_len = (int) (path.p - host.p); /* Account for possible :PORT */
mg_printf(nc, "Host: %.*s\r\n", host_len, host.p);
}
if (protocol.len > 0) {
mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) protocol.len,
protocol.p);
}
if (extra_headers.len > 0) {
mg_printf(nc, "%.*s", (int) extra_headers.len, extra_headers.p);
}
mg_printf(nc, "\r\n");
nc->flags |= MG_F_IS_WEBSOCKET;
mbuf_free(&auth);
}
void mg_send_websocket_handshake(struct mg_connection *nc, const char *path,
const char *extra_headers) {
struct mg_str null_str = MG_NULL_STR;
mg_send_websocket_handshake3v(
nc, mg_mk_str(path), null_str /* host */, null_str /* protocol */,
mg_mk_str(extra_headers), null_str /* user */, null_str /* pass */);
}
struct mg_connection *mg_connect_ws_opt(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
struct mg_connect_opts opts, const char *url, const char *protocol,
const char *extra_headers) {
struct mg_str null_str = MG_NULL_STR;
struct mg_str host = MG_NULL_STR, path = MG_NULL_STR, user_info = MG_NULL_STR;
struct mg_connection *nc =
mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
"ws", "https", "wss", url, &path, &user_info, &host);
if (nc != NULL) {
mg_send_websocket_handshake3v(nc, path, host, mg_mk_str(protocol),
mg_mk_str(extra_headers), user_info,
null_str);
}
return nc;
}
struct mg_connection *mg_connect_ws(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
const char *url, const char *protocol, const char *extra_headers) {
struct mg_connect_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_connect_ws_opt(mgr, MG_CB(ev_handler, user_data), opts, url,
protocol, extra_headers);
}
#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_util.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
/* Amalgamated: #include "common/cs_base64.h" */
/* Amalgamated: #include "mg_internal.h" */
/* Amalgamated: #include "mg_util.h" */
/* For platforms with limited libc */
#ifndef MAX
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif
const char *mg_skip(const char *s, const char *end, const char *delims,
struct mg_str *v) {
v->p = s;
while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++;
v->len = s - v->p;
while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++;
return s;
}
#if MG_ENABLE_FILESYSTEM && !defined(MG_USER_FILE_FUNCTIONS)
int mg_stat(const char *path, cs_stat_t *st) {
#ifdef _WIN32
wchar_t wpath[MG_MAX_PATH];
to_wchar(path, wpath, ARRAY_SIZE(wpath));
DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
return _wstati64(wpath, st);
#else
return stat(path, st);
#endif
}
FILE *mg_fopen(const char *path, const char *mode) {
#ifdef _WIN32
wchar_t wpath[MG_MAX_PATH], wmode[10];
to_wchar(path, wpath, ARRAY_SIZE(wpath));
to_wchar(mode, wmode, ARRAY_SIZE(wmode));
return _wfopen(wpath, wmode);
#else
return fopen(path, mode);
#endif
}
int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */
#if defined(_WIN32) && !defined(WINCE)
wchar_t wpath[MG_MAX_PATH];
to_wchar(path, wpath, ARRAY_SIZE(wpath));
return _wopen(wpath, flag, mode);
#else
return open(path, flag, mode); /* LCOV_EXCL_LINE */
#endif
}
size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f) {
return fread(ptr, size, count, f);
}
size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f) {
return fwrite(ptr, size, count, f);
}
#endif
void mg_base64_encode(const unsigned char *src, int src_len, char *dst) {
cs_base64_encode(src, src_len, dst);
}
int mg_base64_decode(const unsigned char *s, int len, char *dst) {
return cs_base64_decode(s, len, dst, NULL);
}
#if MG_ENABLE_THREADS
void *mg_start_thread(void *(*f)(void *), void *p) {
#ifdef WINCE
return (void *) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0, NULL);
#elif defined(_WIN32)
return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p);
#else
pthread_t thread_id = (pthread_t) 0;
pthread_attr_t attr;
(void) pthread_attr_init(&attr);
(void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
#if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1
(void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE);
#endif
pthread_create(&thread_id, &attr, f, p);
pthread_attr_destroy(&attr);
return (void *) thread_id;
#endif
}
#endif /* MG_ENABLE_THREADS */
/* Set close-on-exec bit for a given socket. */
void mg_set_close_on_exec(sock_t sock) {
#if defined(_WIN32) && !defined(WINCE)
(void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
#elif defined(__unix__)
fcntl(sock, F_SETFD, FD_CLOEXEC);
#else
(void) sock;
#endif
}
int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
int flags) {
int is_v6;
if (buf == NULL || len <= 0) return 0;
memset(buf, 0, len);
#if MG_ENABLE_IPV6
is_v6 = sa->sa.sa_family == AF_INET6;
#else
is_v6 = 0;
#endif
if (flags & MG_SOCK_STRINGIFY_IP) {
#if MG_ENABLE_IPV6
const void *addr = NULL;
char *start = buf;
socklen_t capacity = len;
if (!is_v6) {
addr = &sa->sin.sin_addr;
} else {
addr = (void *) &sa->sin6.sin6_addr;
if (flags & MG_SOCK_STRINGIFY_PORT) {
*buf = '[';
start++;
capacity--;
}
}
if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) {
goto cleanup;
}
#elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32)
/* Only Windoze Vista (and newer) have inet_ntop() */
char *addr_str = inet_ntoa(sa->sin.sin_addr);
if (addr_str != NULL) {
strncpy(buf, inet_ntoa(sa->sin.sin_addr), len - 1);
} else {
goto cleanup;
}
#else
if (inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len) == NULL) {
goto cleanup;
}
#endif
}
if (flags & MG_SOCK_STRINGIFY_PORT) {
int port = ntohs(sa->sin.sin_port);
if (flags & MG_SOCK_STRINGIFY_IP) {
int buf_len = strlen(buf);
snprintf(buf + buf_len, len - (buf_len + 1), "%s:%d", (is_v6 ? "]" : ""),
port);
} else {
snprintf(buf, len, "%d", port);
}
}
return strlen(buf);
cleanup:
*buf = '\0';
return 0;
}
int mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len,
int flags) {
union socket_address sa;
memset(&sa, 0, sizeof(sa));
mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
return mg_sock_addr_to_str(&sa, buf, len, flags);
}
#if MG_ENABLE_HEXDUMP
static int mg_hexdump_n(const void *buf, int len, char *dst, int dst_len,
int offset) {
const unsigned char *p = (const unsigned char *) buf;
char ascii[17] = "";
int i, idx, n = 0;
for (i = 0; i < len; i++) {
idx = i % 16;
if (idx == 0) {
if (i > 0) n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii);
n += snprintf(dst + n, MAX(dst_len - n, 0), "%04x ", i + offset);
}
if (dst_len - n < 0) {
return n;
}
n += snprintf(dst + n, MAX(dst_len - n, 0), " %02x", p[i]);
ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
ascii[idx + 1] = '\0';
}
while (i++ % 16) n += snprintf(dst + n, MAX(dst_len - n, 0), "%s", " ");
n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii);
return n;
}
int mg_hexdump(const void *buf, int len, char *dst, int dst_len) {
return mg_hexdump_n(buf, len, dst, dst_len, 0);
}
void mg_hexdumpf(FILE *fp, const void *buf, int len) {
char tmp[80];
int offset = 0, n;
while (len > 0) {
n = (len < 16 ? len : 16);
mg_hexdump_n(((const char *) buf) + offset, n, tmp, sizeof(tmp), offset);
fputs(tmp, fp);
offset += n;
len -= n;
}
}
void mg_hexdump_connection(struct mg_connection *nc, const char *path,
const void *buf, int num_bytes, int ev) {
FILE *fp = NULL;
char src[60], dst[60];
const char *tag = NULL;
switch (ev) {
case MG_EV_RECV:
tag = "<-";
break;
case MG_EV_SEND:
tag = "->";
break;
case MG_EV_ACCEPT:
tag = "<A";
break;
case MG_EV_CONNECT:
tag = "C>";
break;
case MG_EV_CLOSE:
tag = "XX";
break;
}
if (tag == NULL) return; /* Don't log MG_EV_TIMER, etc */
if (strcmp(path, "-") == 0) {
fp = stdout;
} else if (strcmp(path, "--") == 0) {
fp = stderr;
#if MG_ENABLE_FILESYSTEM
} else {
fp = mg_fopen(path, "a");
#endif
}
if (fp == NULL) return;
mg_conn_addr_to_str(nc, src, sizeof(src),
MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
mg_conn_addr_to_str(nc, dst, sizeof(dst), MG_SOCK_STRINGIFY_IP |
MG_SOCK_STRINGIFY_PORT |
MG_SOCK_STRINGIFY_REMOTE);
fprintf(fp, "%lu %p %s %s %s %d\n", (unsigned long) mg_time(), (void *) nc,
src, tag, dst, (int) num_bytes);
if (num_bytes > 0) {
mg_hexdumpf(fp, buf, num_bytes);
}
if (fp != stdout && fp != stderr) fclose(fp);
}
#endif
int mg_is_big_endian(void) {
static const int n = 1;
/* TODO(mkm) use compiletime check with 4-byte char literal */
return ((char *) &n)[0] == 0;
}
DO_NOT_WARN_UNUSED MG_INTERNAL int mg_get_errno(void) {
#ifndef WINCE
return errno;
#else
/* TODO(alashkin): translate error codes? */
return GetLastError();
#endif
}
void mg_mbuf_append_base64_putc(char ch, void *user_data) {
struct mbuf *mbuf = (struct mbuf *) user_data;
mbuf_append(mbuf, &ch, sizeof(ch));
}
void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len) {
struct cs_base64_ctx ctx;
cs_base64_init(&ctx, mg_mbuf_append_base64_putc, mbuf);
cs_base64_update(&ctx, (const char *) data, len);
cs_base64_finish(&ctx);
}
void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass,
struct mbuf *buf) {
const char *header_prefix = "Authorization: Basic ";
const char *header_suffix = "\r\n";
struct cs_base64_ctx ctx;
cs_base64_init(&ctx, mg_mbuf_append_base64_putc, buf);
mbuf_append(buf, header_prefix, strlen(header_prefix));
cs_base64_update(&ctx, user.p, user.len);
if (pass.len > 0) {
cs_base64_update(&ctx, ":", 1);
cs_base64_update(&ctx, pass.p, pass.len);
}
cs_base64_finish(&ctx);
mbuf_append(buf, header_suffix, strlen(header_suffix));
}
struct mg_str mg_url_encode_opt(const struct mg_str src,
const struct mg_str safe, unsigned int flags) {
const char *hex =
(flags & MG_URL_ENCODE_F_UPPERCASE_HEX ? "0123456789ABCDEF"
: "0123456789abcdef");
size_t i = 0;
struct mbuf mb;
mbuf_init(&mb, src.len);
for (i = 0; i < src.len; i++) {
const unsigned char c = *((const unsigned char *) src.p + i);
if (isalnum(c) || mg_strchr(safe, c) != NULL) {
mbuf_append(&mb, &c, 1);
} else if (c == ' ' && (flags & MG_URL_ENCODE_F_SPACE_AS_PLUS)) {
mbuf_append(&mb, "+", 1);
} else {
mbuf_append(&mb, "%", 1);
mbuf_append(&mb, &hex[c >> 4], 1);
mbuf_append(&mb, &hex[c & 15], 1);
}
}
mbuf_append(&mb, "", 1);
mbuf_trim(&mb);
return mg_mk_str_n(mb.buf, mb.len - 1);
}
struct mg_str mg_url_encode(const struct mg_str src) {
return mg_url_encode_opt(src, mg_mk_str("._-$,;~()/"), 0);
}
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_mqtt.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_MQTT
#include <string.h>
/* Amalgamated: #include "mg_internal.h" */
/* Amalgamated: #include "mg_mqtt.h" */
static uint16_t getu16(const char *p) {
const uint8_t *up = (const uint8_t *) p;
return (up[0] << 8) + up[1];
}
static const char *scanto(const char *p, struct mg_str *s) {
s->len = getu16(p);
s->p = p + 2;
return s->p + s->len;
}
MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) {
uint8_t header;
size_t len = 0, len_len = 0;
const char *p, *end;
unsigned char lc = 0;
int cmd;
if (io->len < 2) return MG_MQTT_ERROR_INCOMPLETE_MSG;
header = io->buf[0];
cmd = header >> 4;
/* decode mqtt variable length */
len = len_len = 0;
p = io->buf + 1;
while ((size_t)(p - io->buf) < io->len) {
lc = *((const unsigned char *) p++);
len += (lc & 0x7f) << 7 * len_len;
len_len++;
if (!(lc & 0x80)) break;
if (len_len > 4) return MG_MQTT_ERROR_MALFORMED_MSG;
}
end = p + len;
if (lc & 0x80 || len > (io->len - (p - io->buf))) {
return MG_MQTT_ERROR_INCOMPLETE_MSG;
}
mm->cmd = cmd;
mm->qos = MG_MQTT_GET_QOS(header);
switch (cmd) {
case MG_MQTT_CMD_CONNECT: {
p = scanto(p, &mm->protocol_name);
if (p > end - 4) return MG_MQTT_ERROR_MALFORMED_MSG;
mm->protocol_version = *(uint8_t *) p++;
mm->connect_flags = *(uint8_t *) p++;
mm->keep_alive_timer = getu16(p);
p += 2;
if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
p = scanto(p, &mm->client_id);
if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
if (mm->connect_flags & MG_MQTT_HAS_WILL) {
if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
p = scanto(p, &mm->will_topic);
}
if (mm->connect_flags & MG_MQTT_HAS_WILL) {
if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
p = scanto(p, &mm->will_message);
}
if (mm->connect_flags & MG_MQTT_HAS_USER_NAME) {
if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
p = scanto(p, &mm->user_name);
}
if (mm->connect_flags & MG_MQTT_HAS_PASSWORD) {
if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
p = scanto(p, &mm->password);
}
if (p != end) return MG_MQTT_ERROR_MALFORMED_MSG;
LOG(LL_DEBUG,
("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] "
"will_msg [%.*s] user_name [%.*s] password [%.*s]",
(int) len, (int) mm->connect_flags, (int) mm->keep_alive_timer,
(int) mm->protocol_name.len, mm->protocol_name.p,
(int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len,
mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p,
(int) mm->user_name.len, mm->user_name.p, (int) mm->password.len,
mm->password.p));
break;
}
case MG_MQTT_CMD_CONNACK:
if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
mm->connack_ret_code = p[1];
break;
case MG_MQTT_CMD_PUBACK:
case MG_MQTT_CMD_PUBREC:
case MG_MQTT_CMD_PUBREL:
case MG_MQTT_CMD_PUBCOMP:
case MG_MQTT_CMD_SUBACK:
mm->message_id = getu16(p);
break;
case MG_MQTT_CMD_PUBLISH: {
p = scanto(p, &mm->topic);
if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
if (mm->qos > 0) {
if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
mm->message_id = getu16(p);
p += 2;
}
mm->payload.p = p;
mm->payload.len = end - p;
break;
}
case MG_MQTT_CMD_SUBSCRIBE:
if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
mm->message_id = getu16(p);
p += 2;
/*
* topic expressions are left in the payload and can be parsed with
* `mg_mqtt_next_subscribe_topic`
*/
mm->payload.p = p;
mm->payload.len = end - p;
break;
default:
/* Unhandled command */
break;
}
mm->len = end - io->buf;
return mm->len;
}
static void mqtt_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct mbuf *io = &nc->recv_mbuf;
struct mg_mqtt_message mm;
memset(&mm, 0, sizeof(mm));
nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
switch (ev) {
case MG_EV_ACCEPT:
if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc);
break;
case MG_EV_RECV: {
/* There can be multiple messages in the buffer, process them all. */
while (1) {
int len = parse_mqtt(io, &mm);
if (len < 0) {
if (len == MG_MQTT_ERROR_MALFORMED_MSG) {
/* Protocol error. */
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
} else if (len == MG_MQTT_ERROR_INCOMPLETE_MSG) {
/* Not fully buffered, let's check if we have a chance to get more
* data later */
if (nc->recv_mbuf_limit > 0 &&
nc->recv_mbuf.len >= nc->recv_mbuf_limit) {
LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit "
"%lu bytes, and not drained, closing",
nc, (unsigned long) nc->recv_mbuf.len,
(unsigned long) nc->recv_mbuf_limit));
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
} else {
/* Should never be here */
LOG(LL_ERROR, ("%p invalid len: %d, closing", nc, len));
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
break;
}
nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm MG_UD_ARG(user_data));
mbuf_remove(io, len);
}
break;
}
case MG_EV_POLL: {
struct mg_mqtt_proto_data *pd =
(struct mg_mqtt_proto_data *) nc->proto_data;
double now = mg_time();
if (pd->keep_alive > 0 && pd->last_control_time > 0 &&
(now - pd->last_control_time) > pd->keep_alive) {
LOG(LL_DEBUG, ("Send PINGREQ"));
mg_mqtt_ping(nc);
}
break;
}
}
}
static void mg_mqtt_proto_data_destructor(void *proto_data) {
MG_FREE(proto_data);
}
static struct mg_str mg_mqtt_next_topic_component(struct mg_str *topic) {
struct mg_str res = *topic;
const char *c = mg_strchr(*topic, '/');
if (c != NULL) {
res.len = (c - topic->p);
topic->len -= (res.len + 1);
topic->p += (res.len + 1);
} else {
topic->len = 0;
}
return res;
}
/* Refernce: https://mosquitto.org/man/mqtt-7.html */
int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic) {
struct mg_str ec, tc;
if (exp.len == 0) return 0;
while (1) {
ec = mg_mqtt_next_topic_component(&exp);
tc = mg_mqtt_next_topic_component(&topic);
if (ec.len == 0) {
if (tc.len != 0) return 0;
if (exp.len == 0) break;
continue;
}
if (mg_vcmp(&ec, "+") == 0) {
if (tc.len == 0 && topic.len == 0) return 0;
continue;
}
if (mg_vcmp(&ec, "#") == 0) {
/* Must be the last component in the expression or it's invalid. */
return (exp.len == 0);
}
if (mg_strcmp(ec, tc) != 0) {
return 0;
}
}
return (tc.len == 0 && topic.len == 0);
}
int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic) {
return mg_mqtt_match_topic_expression(mg_mk_str(exp), topic);
}
void mg_set_protocol_mqtt(struct mg_connection *nc) {
nc->proto_handler = mqtt_handler;
nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data));
nc->proto_data_destructor = mg_mqtt_proto_data_destructor;
}
static void mg_send_mqtt_header(struct mg_connection *nc, uint8_t cmd,
uint8_t flags, size_t len) {
struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
uint8_t buf[1 + sizeof(size_t)];
uint8_t *vlen = &buf[1];
buf[0] = (cmd << 4) | flags;
/* mqtt variable length encoding */
do {
*vlen = len % 0x80;
len /= 0x80;
if (len > 0) *vlen |= 0x80;
vlen++;
} while (len > 0);
mg_send(nc, buf, vlen - buf);
pd->last_control_time = mg_time();
}
void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) {
static struct mg_send_mqtt_handshake_opts opts;
mg_send_mqtt_handshake_opt(nc, client_id, opts);
}
void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
struct mg_send_mqtt_handshake_opts opts) {
struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
uint16_t id_len = 0, wt_len = 0, wm_len = 0, user_len = 0, pw_len = 0;
uint16_t netbytes;
size_t total_len;
if (client_id != NULL) {
id_len = strlen(client_id);
}
total_len = 7 + 1 + 2 + 2 + id_len;
if (opts.user_name != NULL) {
opts.flags |= MG_MQTT_HAS_USER_NAME;
}
if (opts.password != NULL) {
opts.flags |= MG_MQTT_HAS_PASSWORD;
}
if (opts.will_topic != NULL && opts.will_message != NULL) {
wt_len = strlen(opts.will_topic);
wm_len = strlen(opts.will_message);
opts.flags |= MG_MQTT_HAS_WILL;
}
if (opts.keep_alive == 0) {
opts.keep_alive = 60;
}
if (opts.flags & MG_MQTT_HAS_WILL) {
total_len += 2 + wt_len + 2 + wm_len;
}
if (opts.flags & MG_MQTT_HAS_USER_NAME) {
user_len = strlen(opts.user_name);
total_len += 2 + user_len;
}
if (opts.flags & MG_MQTT_HAS_PASSWORD) {
pw_len = strlen(opts.password);
total_len += 2 + pw_len;
}
mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNECT, 0, total_len);
mg_send(nc, "\00\04MQTT\04", 7);
mg_send(nc, &opts.flags, 1);
netbytes = htons(opts.keep_alive);
mg_send(nc, &netbytes, 2);
netbytes = htons(id_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, client_id, id_len);
if (opts.flags & MG_MQTT_HAS_WILL) {
netbytes = htons(wt_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, opts.will_topic, wt_len);
netbytes = htons(wm_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, opts.will_message, wm_len);
}
if (opts.flags & MG_MQTT_HAS_USER_NAME) {
netbytes = htons(user_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, opts.user_name, user_len);
}
if (opts.flags & MG_MQTT_HAS_PASSWORD) {
netbytes = htons(pw_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, opts.password, pw_len);
}
if (pd != NULL) {
pd->keep_alive = opts.keep_alive;
}
}
void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
uint16_t message_id, int flags, const void *data,
size_t len) {
uint16_t netbytes;
uint16_t topic_len = strlen(topic);
size_t total_len = 2 + topic_len + len;
if (MG_MQTT_GET_QOS(flags) > 0) {
total_len += 2;
}
mg_send_mqtt_header(nc, MG_MQTT_CMD_PUBLISH, flags, total_len);
netbytes = htons(topic_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, topic, topic_len);
if (MG_MQTT_GET_QOS(flags) > 0) {
netbytes = htons(message_id);
mg_send(nc, &netbytes, 2);
}
mg_send(nc, data, len);
}
void mg_mqtt_subscribe(struct mg_connection *nc,
const struct mg_mqtt_topic_expression *topics,
size_t topics_len, uint16_t message_id) {
uint16_t netbytes;
size_t i;
uint16_t topic_len;
size_t total_len = 2;
for (i = 0; i < topics_len; i++) {
total_len += 2 + strlen(topics[i].topic) + 1;
}
mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1), total_len);
netbytes = htons(message_id);
mg_send(nc, (char *) &netbytes, 2);
for (i = 0; i < topics_len; i++) {
topic_len = strlen(topics[i].topic);
netbytes = htons(topic_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, topics[i].topic, topic_len);
mg_send(nc, &topics[i].qos, 1);
}
}
int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
struct mg_str *topic, uint8_t *qos, int pos) {
unsigned char *buf = (unsigned char *) msg->payload.p + pos;
int new_pos;
if ((size_t) pos >= msg->payload.len) return -1;
topic->len = buf[0] << 8 | buf[1];
topic->p = (char *) buf + 2;
new_pos = pos + 2 + topic->len + 1;
if ((size_t) new_pos > msg->payload.len) return -1;
*qos = buf[2 + topic->len];
return new_pos;
}
void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
size_t topics_len, uint16_t message_id) {
uint16_t netbytes;
size_t i;
uint16_t topic_len;
size_t total_len = 2;
for (i = 0; i < topics_len; i++) {
total_len += 2 + strlen(topics[i]);
}
mg_send_mqtt_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1), total_len);
netbytes = htons(message_id);
mg_send(nc, (char *) &netbytes, 2);
for (i = 0; i < topics_len; i++) {
topic_len = strlen(topics[i]);
netbytes = htons(topic_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, topics[i], topic_len);
}
}
void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) {
uint8_t unused = 0;
mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNACK, 0, 2);
mg_send(nc, &unused, 1);
mg_send(nc, &return_code, 1);
}
/*
* Sends a command which contains only a `message_id` and a QoS level of 1.
*
* Helper function.
*/
static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd,
uint16_t message_id) {
uint16_t netbytes;
uint8_t flags = (cmd == MG_MQTT_CMD_PUBREL ? 2 : 0);
mg_send_mqtt_header(nc, cmd, flags, 2 /* len */);
netbytes = htons(message_id);
mg_send(nc, &netbytes, 2);
}
void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id);
}
void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id);
}
void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id);
}
void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id);
}
void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
uint16_t message_id) {
size_t i;
uint16_t netbytes;
mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len);
netbytes = htons(message_id);
mg_send(nc, &netbytes, 2);
for (i = 0; i < qoss_len; i++) {
mg_send(nc, &qoss[i], 1);
}
}
void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id);
}
void mg_mqtt_ping(struct mg_connection *nc) {
mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0);
}
void mg_mqtt_pong(struct mg_connection *nc) {
mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0);
}
void mg_mqtt_disconnect(struct mg_connection *nc) {
mg_send_mqtt_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0);
}
#endif /* MG_ENABLE_MQTT */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_mqtt_server.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
/* Amalgamated: #include "mg_internal.h" */
/* Amalgamated: #include "mg_mqtt_server.h" */
#if MG_ENABLE_MQTT_BROKER
static void mg_mqtt_session_init(struct mg_mqtt_broker *brk,
struct mg_mqtt_session *s,
struct mg_connection *nc) {
s->brk = brk;
s->subscriptions = NULL;
s->num_subscriptions = 0;
s->nc = nc;
}
static void mg_mqtt_add_session(struct mg_mqtt_session *s) {
LIST_INSERT_HEAD(&s->brk->sessions, s, link);
}
static void mg_mqtt_remove_session(struct mg_mqtt_session *s) {
LIST_REMOVE(s, link);
}
static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) {
size_t i;
for (i = 0; i < s->num_subscriptions; i++) {
MG_FREE((void *) s->subscriptions[i].topic);
}
MG_FREE(s->subscriptions);
MG_FREE(s);
}
static void mg_mqtt_close_session(struct mg_mqtt_session *s) {
mg_mqtt_remove_session(s);
mg_mqtt_destroy_session(s);
}
void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) {
LIST_INIT(&brk->sessions);
brk->user_data = user_data;
}
static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk,
struct mg_connection *nc) {
struct mg_mqtt_session *s =
(struct mg_mqtt_session *) MG_CALLOC(1, sizeof *s);
if (s == NULL) {
/* LCOV_EXCL_START */
mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE);
return;
/* LCOV_EXCL_STOP */
}
/* TODO(mkm): check header (magic and version) */
mg_mqtt_session_init(brk, s, nc);
nc->priv_2 = s;
mg_mqtt_add_session(s);
mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED);
}
static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc,
struct mg_mqtt_message *msg) {
struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->priv_2;
uint8_t qoss[MG_MQTT_MAX_SESSION_SUBSCRIPTIONS];
size_t num_subs = 0;
struct mg_str topic;
uint8_t qos;
int pos;
struct mg_mqtt_topic_expression *te;
for (pos = 0;
(pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) {
if (num_subs >= sizeof(MG_MQTT_MAX_SESSION_SUBSCRIPTIONS) ||
(ss->num_subscriptions + num_subs >=
MG_MQTT_MAX_SESSION_SUBSCRIPTIONS)) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return;
}
qoss[num_subs++] = qos;
}
if (num_subs > 0) {
te = (struct mg_mqtt_topic_expression *) MG_REALLOC(
ss->subscriptions,
sizeof(*ss->subscriptions) * (ss->num_subscriptions + num_subs));
if (te == NULL) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return;
}
ss->subscriptions = te;
for (pos = 0;
pos < (int) msg->payload.len &&
(pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;
ss->num_subscriptions++) {
te = &ss->subscriptions[ss->num_subscriptions];
te->topic = (char *) MG_MALLOC(topic.len + 1);
te->qos = qos;
memcpy((char *) te->topic, topic.p, topic.len);
((char *) te->topic)[topic.len] = '\0';
}
}
if (pos == (int) msg->payload.len) {
mg_mqtt_suback(nc, qoss, num_subs, msg->message_id);
} else {
/* We did not fully parse the payload, something must be wrong. */
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
}
static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk,
struct mg_mqtt_message *msg) {
struct mg_mqtt_session *s;
size_t i;
for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
for (i = 0; i < s->num_subscriptions; i++) {
if (mg_mqtt_vmatch_topic_expression(s->subscriptions[i].topic,
msg->topic)) {
char buf[100], *p = buf;
mg_asprintf(&p, sizeof(buf), "%.*s", (int) msg->topic.len,
msg->topic.p);
if (p == NULL) {
return;
}
mg_mqtt_publish(s->nc, p, 0, 0, msg->payload.p, msg->payload.len);
if (p != buf) {
MG_FREE(p);
}
break;
}
}
}
}
void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) {
struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data;
struct mg_mqtt_broker *brk;
if (nc->listener) {
brk = (struct mg_mqtt_broker *) nc->listener->priv_2;
} else {
brk = (struct mg_mqtt_broker *) nc->priv_2;
}
switch (ev) {
case MG_EV_ACCEPT:
if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc);
nc->priv_2 = NULL; /* Clear up the inherited pointer to broker */
break;
case MG_EV_MQTT_CONNECT:
if (nc->priv_2 == NULL) {
mg_mqtt_broker_handle_connect(brk, nc);
} else {
/* Repeated CONNECT */
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
break;
case MG_EV_MQTT_SUBSCRIBE:
if (nc->priv_2 != NULL) {
mg_mqtt_broker_handle_subscribe(nc, msg);
} else {
/* Subscribe before CONNECT */
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
break;
case MG_EV_MQTT_PUBLISH:
if (nc->priv_2 != NULL) {
mg_mqtt_broker_handle_publish(brk, msg);
} else {
/* Publish before CONNECT */
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
break;
case MG_EV_CLOSE:
if (nc->listener && nc->priv_2 != NULL) {
mg_mqtt_close_session((struct mg_mqtt_session *) nc->priv_2);
}
break;
}
}
struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk,
struct mg_mqtt_session *s) {
return s == NULL ? LIST_FIRST(&brk->sessions) : LIST_NEXT(s, link);
}
#endif /* MG_ENABLE_MQTT_BROKER */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_dns.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_DNS
/* Amalgamated: #include "mg_internal.h" */
/* Amalgamated: #include "mg_dns.h" */
static int mg_dns_tid = 0xa0;
struct mg_dns_header {
uint16_t transaction_id;
uint16_t flags;
uint16_t num_questions;
uint16_t num_answers;
uint16_t num_authority_prs;
uint16_t num_other_prs;
};
struct mg_dns_resource_record *mg_dns_next_record(
struct mg_dns_message *msg, int query,
struct mg_dns_resource_record *prev) {
struct mg_dns_resource_record *rr;
for (rr = (prev == NULL ? msg->answers : prev + 1);
rr - msg->answers < msg->num_answers; rr++) {
if (rr->rtype == query) {
return rr;
}
}
return NULL;
}
int mg_dns_parse_record_data(struct mg_dns_message *msg,
struct mg_dns_resource_record *rr, void *data,
size_t data_len) {
switch (rr->rtype) {
case MG_DNS_A_RECORD:
if (data_len < sizeof(struct in_addr)) {
return -1;
}
if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) {
return -1;
}
memcpy(data, rr->rdata.p, data_len);
return 0;
#if MG_ENABLE_IPV6
case MG_DNS_AAAA_RECORD:
if (data_len < sizeof(struct in6_addr)) {
return -1; /* LCOV_EXCL_LINE */
}
memcpy(data, rr->rdata.p, data_len);
return 0;
#endif
case MG_DNS_CNAME_RECORD:
mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len);
return 0;
}
return -1;
}
int mg_dns_insert_header(struct mbuf *io, size_t pos,
struct mg_dns_message *msg) {
struct mg_dns_header header;
memset(&header, 0, sizeof(header));
header.transaction_id = msg->transaction_id;
header.flags = htons(msg->flags);
header.num_questions = htons(msg->num_questions);
header.num_answers = htons(msg->num_answers);
return mbuf_insert(io, pos, &header, sizeof(header));
}
int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg) {
unsigned char *begin, *end;
struct mg_dns_resource_record *last_q;
if (msg->num_questions <= 0) return 0;
begin = (unsigned char *) msg->pkt.p + sizeof(struct mg_dns_header);
last_q = &msg->questions[msg->num_questions - 1];
end = (unsigned char *) last_q->name.p + last_q->name.len + 4;
return mbuf_append(io, begin, end - begin);
}
int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) {
const char *s;
unsigned char n;
size_t pos = io->len;
do {
if ((s = strchr(name, '.')) == NULL) {
s = name + len;
}
if (s - name > 127) {
return -1; /* TODO(mkm) cover */
}
n = s - name; /* chunk length */
mbuf_append(io, &n, 1); /* send length */
mbuf_append(io, name, n);
if (*s == '.') {
n++;
}
name += n;
len -= n;
} while (*s != '\0');
mbuf_append(io, "\0", 1); /* Mark end of host name */
return io->len - pos;
}
int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr,
const char *name, size_t nlen, const void *rdata,
size_t rlen) {
size_t pos = io->len;
uint16_t u16;
uint32_t u32;
if (rr->kind == MG_DNS_INVALID_RECORD) {
return -1; /* LCOV_EXCL_LINE */
}
if (mg_dns_encode_name(io, name, nlen) == -1) {
return -1;
}
u16 = htons(rr->rtype);
mbuf_append(io, &u16, 2);
u16 = htons(rr->rclass);
mbuf_append(io, &u16, 2);
if (rr->kind == MG_DNS_ANSWER) {
u32 = htonl(rr->ttl);
mbuf_append(io, &u32, 4);
if (rr->rtype == MG_DNS_CNAME_RECORD) {
int clen;
/* fill size after encoding */
size_t off = io->len;
mbuf_append(io, &u16, 2);
if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) {
return -1;
}
u16 = clen;
io->buf[off] = u16 >> 8;
io->buf[off + 1] = u16 & 0xff;
} else {
u16 = htons((uint16_t) rlen);
mbuf_append(io, &u16, 2);
mbuf_append(io, rdata, rlen);
}
}
return io->len - pos;
}
void mg_send_dns_query(struct mg_connection *nc, const char *name,
int query_type) {
struct mg_dns_message *msg =
(struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg));
struct mbuf pkt;
struct mg_dns_resource_record *rr = &msg->questions[0];
DBG(("%s %d", name, query_type));
mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */);
msg->transaction_id = ++mg_dns_tid;
msg->flags = 0x100;
msg->num_questions = 1;
mg_dns_insert_header(&pkt, 0, msg);
rr->rtype = query_type;
rr->rclass = 1; /* Class: inet */
rr->kind = MG_DNS_QUESTION;
if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) {
/* TODO(mkm): return an error code */
goto cleanup; /* LCOV_EXCL_LINE */
}
/* TCP DNS requires messages to be prefixed with len */
if (!(nc->flags & MG_F_UDP)) {
uint16_t len = htons((uint16_t) pkt.len);
mbuf_insert(&pkt, 0, &len, 2);
}
mg_send(nc, pkt.buf, pkt.len);
mbuf_free(&pkt);
cleanup:
MG_FREE(msg);
}
static unsigned char *mg_parse_dns_resource_record(
unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr,
int reply) {
unsigned char *name = data;
int chunk_len, data_len;
while (data < end && (chunk_len = *data)) {
if (((unsigned char *) data)[0] & 0xc0) {
data += 1;
break;
}
data += chunk_len + 1;
}
if (data > end - 5) {
return NULL;
}
rr->name.p = (char *) name;
rr->name.len = data - name + 1;
data++;
rr->rtype = data[0] << 8 | data[1];
data += 2;
rr->rclass = data[0] << 8 | data[1];
data += 2;
rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION;
if (reply) {
if (data >= end - 6) {
return NULL;
}
rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 |
data[2] << 8 | data[3];
data += 4;
data_len = *data << 8 | *(data + 1);
data += 2;
rr->rdata.p = (char *) data;
rr->rdata.len = data_len;
data += data_len;
}
return data;
}
int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) {
struct mg_dns_header *header = (struct mg_dns_header *) buf;
unsigned char *data = (unsigned char *) buf + sizeof(*header);
unsigned char *end = (unsigned char *) buf + len;
int i;
memset(msg, 0, sizeof(*msg));
msg->pkt.p = buf;
msg->pkt.len = len;
if (len < (int) sizeof(*header)) return -1;
msg->transaction_id = header->transaction_id;
msg->flags = ntohs(header->flags);
msg->num_questions = ntohs(header->num_questions);
if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) {
msg->num_questions = (int) ARRAY_SIZE(msg->questions);
}
msg->num_answers = ntohs(header->num_answers);
if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) {
msg->num_answers = (int) ARRAY_SIZE(msg->answers);
}
for (i = 0; i < msg->num_questions; i++) {
data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0);
if (data == NULL) return -1;
}
for (i = 0; i < msg->num_answers; i++) {
data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1);
if (data == NULL) return -1;
}
return 0;
}
size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
char *dst, int dst_len) {
int chunk_len, num_ptrs = 0;
char *old_dst = dst;
const unsigned char *data = (unsigned char *) name->p;
const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len;
if (data >= end) {
return 0;
}
while ((chunk_len = *data++)) {
int leeway = dst_len - (dst - old_dst);
if (data >= end) {
return 0;
}
if ((chunk_len & 0xc0) == 0xc0) {
uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0];
if (off >= msg->pkt.len) {
return 0;
}
/* Basic circular loop avoidance: allow up to 16 pointer hops. */
if (++num_ptrs > 15) {
return 0;
}
data = (unsigned char *) msg->pkt.p + off;
continue;
}
if (chunk_len > 63) {
return 0;
}
if (chunk_len > leeway) {
chunk_len = leeway;
}
if (data + chunk_len >= end) {
return 0;
}
memcpy(dst, data, chunk_len);
data += chunk_len;
dst += chunk_len;
leeway -= chunk_len;
if (leeway == 0) {
return dst - old_dst;
}
*dst++ = '.';
}
if (dst != old_dst) {
*--dst = 0;
}
return dst - old_dst;
}
static void dns_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct mbuf *io = &nc->recv_mbuf;
struct mg_dns_message msg;
/* Pass low-level events to the user handler */
nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
switch (ev) {
case MG_EV_RECV:
if (!(nc->flags & MG_F_UDP)) {
mbuf_remove(&nc->recv_mbuf, 2);
}
if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) {
/* reply + recursion allowed + format error */
memset(&msg, 0, sizeof(msg));
msg.flags = 0x8081;
mg_dns_insert_header(io, 0, &msg);
if (!(nc->flags & MG_F_UDP)) {
uint16_t len = htons((uint16_t) io->len);
mbuf_insert(io, 0, &len, 2);
}
mg_send(nc, io->buf, io->len);
} else {
/* Call user handler with parsed message */
nc->handler(nc, MG_DNS_MESSAGE, &msg MG_UD_ARG(user_data));
}
mbuf_remove(io, io->len);
break;
}
}
void mg_set_protocol_dns(struct mg_connection *nc) {
nc->proto_handler = dns_handler;
}
#endif /* MG_ENABLE_DNS */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_dns_server.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_DNS_SERVER
/* Amalgamated: #include "mg_internal.h" */
/* Amalgamated: #include "dns-server.h" */
struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
struct mg_dns_message *msg) {
struct mg_dns_reply rep;
rep.msg = msg;
rep.io = io;
rep.start = io->len;
/* reply + recursion allowed */
msg->flags |= 0x8080;
mg_dns_copy_questions(io, msg);
msg->num_answers = 0;
return rep;
}
void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) {
size_t sent = r->io->len - r->start;
mg_dns_insert_header(r->io, r->start, r->msg);
if (!(nc->flags & MG_F_UDP)) {
uint16_t len = htons((uint16_t) sent);
mbuf_insert(r->io, r->start, &len, 2);
}
if (&nc->send_mbuf != r->io) {
mg_send(nc, r->io->buf + r->start, r->io->len - r->start);
r->io->len = r->start;
}
}
int mg_dns_reply_record(struct mg_dns_reply *reply,
struct mg_dns_resource_record *question,
const char *name, int rtype, int ttl, const void *rdata,
size_t rdata_len) {
struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg;
char rname[512];
struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers];
if (msg->num_answers >= MG_MAX_DNS_ANSWERS) {
return -1; /* LCOV_EXCL_LINE */
}
if (name == NULL) {
name = rname;
rname[511] = 0;
mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1);
}
*ans = *question;
ans->kind = MG_DNS_ANSWER;
ans->rtype = rtype;
ans->ttl = ttl;
if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata,
rdata_len) == -1) {
return -1; /* LCOV_EXCL_LINE */
};
msg->num_answers++;
return 0;
}
#endif /* MG_ENABLE_DNS_SERVER */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_resolv.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_ASYNC_RESOLVER
/* Amalgamated: #include "mg_internal.h" */
/* Amalgamated: #include "mg_resolv.h" */
#ifndef MG_DEFAULT_NAMESERVER
#define MG_DEFAULT_NAMESERVER "8.8.8.8"
#endif
struct mg_resolve_async_request {
char name[1024];
int query;
mg_resolve_callback_t callback;
void *data;
time_t timeout;
int max_retries;
enum mg_resolve_err err;
/* state */
time_t last_time;
int retries;
};
/*
* Find what nameserver to use.
*
* Return 0 if OK, -1 if error
*/
static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) {
int ret = -1;
#ifdef _WIN32
int i;
LONG err;
HKEY hKey, hSub;
wchar_t subkey[512], value[128],
*key = L"SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces";
if ((err = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hKey)) !=
ERROR_SUCCESS) {
fprintf(stderr, "cannot open reg key %S: %ld\n", key, err);
ret = -1;
} else {
for (ret = -1, i = 0; 1; i++) {
DWORD subkey_size = sizeof(subkey), type, len = sizeof(value);
if (RegEnumKeyExW(hKey, i, subkey, &subkey_size, NULL, NULL, NULL,
NULL) != ERROR_SUCCESS) {
break;
}
if (RegOpenKeyExW(hKey, subkey, 0, KEY_READ, &hSub) == ERROR_SUCCESS &&
((RegQueryValueExW(hSub, L"NameServer", 0, &type, (void *) value,
&len) == ERROR_SUCCESS &&
value[0] != '\0') ||
(RegQueryValueExW(hSub, L"DhcpNameServer", 0, &type, (void *) value,
&len) == ERROR_SUCCESS &&
value[0] != '\0'))) {
/*
* See https://github.com/cesanta/mongoose/issues/176
* The value taken from the registry can be empty, a single
* IP address, or multiple IP addresses separated by comma.
* If it's empty, check the next interface.
* If it's multiple IP addresses, take the first one.
*/
wchar_t *comma = wcschr(value, ',');
if (comma != NULL) {
*comma = '\0';
}
/* %S will convert wchar_t -> char */
snprintf(name, name_len, "%S", value);
ret = 0;
RegCloseKey(hSub);
break;
}
}
RegCloseKey(hKey);
}
#elif MG_ENABLE_FILESYSTEM && defined(MG_RESOLV_CONF_FILE_NAME)
FILE *fp;
char line[512];
if ((fp = mg_fopen(MG_RESOLV_CONF_FILE_NAME, "r")) == NULL) {
ret = -1;
} else {
/* Try to figure out what nameserver to use */
for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) {
unsigned int a, b, c, d;
if (sscanf(line, "nameserver %u.%u.%u.%u", &a, &b, &c, &d) == 4) {
snprintf(name, name_len, "%u.%u.%u.%u", a, b, c, d);
ret = 0;
break;
}
}
(void) fclose(fp);
}
#else
snprintf(name, name_len, "%s", MG_DEFAULT_NAMESERVER);
#endif /* _WIN32 */
return ret;
}
int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) {
#if MG_ENABLE_FILESYSTEM && defined(MG_HOSTS_FILE_NAME)
/* TODO(mkm) cache /etc/hosts */
FILE *fp;
char line[1024];
char *p;
char alias[256];
unsigned int a, b, c, d;
int len = 0;
if ((fp = mg_fopen(MG_HOSTS_FILE_NAME, "r")) == NULL) {
return -1;
}
for (; fgets(line, sizeof(line), fp) != NULL;) {
if (line[0] == '#') continue;
if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) {
/* TODO(mkm): handle ipv6 */
continue;
}
for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) {
if (strcmp(alias, name) == 0) {
usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d);
fclose(fp);
return 0;
}
}
}
fclose(fp);
#else
(void) name;
(void) usa;
#endif
return -1;
}
static void mg_resolve_async_eh(struct mg_connection *nc, int ev,
void *data MG_UD_ARG(void *user_data)) {
time_t now = (time_t) mg_time();
struct mg_resolve_async_request *req;
struct mg_dns_message *msg;
#if !MG_ENABLE_CALLBACK_USERDATA
void *user_data = nc->user_data;
#endif
if (ev != MG_EV_POLL) {
DBG(("ev=%d user_data=%p", ev, user_data));
}
req = (struct mg_resolve_async_request *) user_data;
if (req == NULL) {
return;
}
switch (ev) {
case MG_EV_POLL:
if (req->retries > req->max_retries) {
req->err = MG_RESOLVE_EXCEEDED_RETRY_COUNT;
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
break;
}
if (nc->flags & MG_F_CONNECTING) break;
/* fallthrough */
case MG_EV_CONNECT:
if (req->retries == 0 || now - req->last_time >= req->timeout) {
mg_send_dns_query(nc, req->name, req->query);
req->last_time = now;
req->retries++;
}
break;
case MG_EV_RECV:
msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg));
if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 &&
msg->num_answers > 0) {
req->callback(msg, req->data, MG_RESOLVE_OK);
nc->user_data = NULL;
MG_FREE(req);
} else {
req->err = MG_RESOLVE_NO_ANSWERS;
}
MG_FREE(msg);
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
break;
case MG_EV_SEND:
/*
* If a send error occurs, prevent closing of the connection by the core.
* We will retry after timeout.
*/
nc->flags &= ~MG_F_CLOSE_IMMEDIATELY;
mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len);
break;
case MG_EV_TIMER:
req->err = MG_RESOLVE_TIMEOUT;
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
break;
case MG_EV_CLOSE:
/* If we got here with request still not done, fire an error callback. */
if (req != NULL) {
char addr[32];
mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP);
#ifdef MG_LOG_DNS_FAILURES
LOG(LL_ERROR, ("Failed to resolve '%s', server %s", req->name, addr));
#endif
req->callback(NULL, req->data, req->err);
nc->user_data = NULL;
MG_FREE(req);
}
break;
}
}
int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
mg_resolve_callback_t cb, void *data) {
struct mg_resolve_async_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_resolve_async_opt(mgr, name, query, cb, data, opts);
}
int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
mg_resolve_callback_t cb, void *data,
struct mg_resolve_async_opts opts) {
struct mg_resolve_async_request *req;
struct mg_connection *dns_nc;
const char *nameserver = opts.nameserver;
char dns_server_buff[17], nameserver_url[26];
if (nameserver == NULL) {
nameserver = mgr->nameserver;
}
DBG(("%s %d %p", name, query, opts.dns_conn));
/* resolve with DNS */
req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req));
if (req == NULL) {
return -1;
}
strncpy(req->name, name, sizeof(req->name));
req->name[sizeof(req->name) - 1] = '\0';
req->query = query;
req->callback = cb;
req->data = data;
/* TODO(mkm): parse defaults out of resolve.conf */
req->max_retries = opts.max_retries ? opts.max_retries : 2;
req->timeout = opts.timeout ? opts.timeout : 5;
/* Lazily initialize dns server */
if (nameserver == NULL) {
if (mg_get_ip_address_of_nameserver(dns_server_buff,
sizeof(dns_server_buff)) != -1) {
nameserver = dns_server_buff;
} else {
nameserver = MG_DEFAULT_NAMESERVER;
}
}
snprintf(nameserver_url, sizeof(nameserver_url), "udp://%s:53", nameserver);
dns_nc = mg_connect(mgr, nameserver_url, MG_CB(mg_resolve_async_eh, NULL));
if (dns_nc == NULL) {
MG_FREE(req);
return -1;
}
dns_nc->user_data = req;
if (opts.dns_conn != NULL) {
*opts.dns_conn = dns_nc;
}
return 0;
}
void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver) {
MG_FREE((char *) mgr->nameserver);
mgr->nameserver = NULL;
if (nameserver != NULL) {
mgr->nameserver = strdup(nameserver);
}
}
#endif /* MG_ENABLE_ASYNC_RESOLVER */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_coap.c"
#endif
/*
* Copyright (c) 2015 Cesanta Software Limited
* All rights reserved
* This software is dual-licensed: 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. For the terms of this
* license, see <http://www.gnu.org/licenses/>.
*
* You are free to use this software under the terms of the GNU General
* Public License, 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.
*
* Alternatively, you can license this software under a commercial
* license, as set out in <https://www.cesanta.com/license>.
*/
/* Amalgamated: #include "mg_internal.h" */
/* Amalgamated: #include "mg_coap.h" */
#if MG_ENABLE_COAP
void mg_coap_free_options(struct mg_coap_message *cm) {
while (cm->options != NULL) {
struct mg_coap_option *next = cm->options->next;
MG_FREE(cm->options);
cm->options = next;
}
}
struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
uint32_t number, char *value,
size_t len) {
struct mg_coap_option *new_option =
(struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option));
new_option->number = number;
new_option->value.p = value;
new_option->value.len = len;
if (cm->options == NULL) {
cm->options = cm->optiomg_tail = new_option;
} else {
/*
* A very simple attention to help clients to compose options:
* CoAP wants to see options ASC ordered.
* Could be change by using sort in coap_compose
*/
if (cm->optiomg_tail->number <= new_option->number) {
/* if option is already ordered just add it */
cm->optiomg_tail = cm->optiomg_tail->next = new_option;
} else {
/* looking for appropriate position */
struct mg_coap_option *current_opt = cm->options;
struct mg_coap_option *prev_opt = 0;
while (current_opt != NULL) {
if (current_opt->number > new_option->number) {
break;
}
prev_opt = current_opt;
current_opt = current_opt->next;
}
if (prev_opt != NULL) {
prev_opt->next = new_option;
new_option->next = current_opt;
} else {
/* insert new_option to the beginning */
new_option->next = cm->options;
cm->options = new_option;
}
}
}
return new_option;
}
/*
* Fills CoAP header in mg_coap_message.
*
* Helper function.
*/
static char *coap_parse_header(char *ptr, struct mbuf *io,
struct mg_coap_message *cm) {
if (io->len < sizeof(uint32_t)) {
cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
return NULL;
}
/*
* Version (Ver): 2-bit unsigned integer. Indicates the CoAP version
* number. Implementations of this specification MUST set this field
* to 1 (01 binary). Other values are reserved for future versions.
* Messages with unknown version numbers MUST be silently ignored.
*/
if (((uint8_t) *ptr >> 6) != 1) {
cm->flags |= MG_COAP_IGNORE;
return NULL;
}
/*
* Type (T): 2-bit unsigned integer. Indicates if this message is of
* type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or
* Reset (3).
*/
cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4;
cm->flags |= MG_COAP_MSG_TYPE_FIELD;
/*
* Token Length (TKL): 4-bit unsigned integer. Indicates the length of
* the variable-length Token field (0-8 bytes). Lengths 9-15 are
* reserved, MUST NOT be sent, and MUST be processed as a message
* format error.
*/
cm->token.len = *ptr & 0x0F;
if (cm->token.len > 8) {
cm->flags |= MG_COAP_FORMAT_ERROR;
return NULL;
}
ptr++;
/*
* Code: 8-bit unsigned integer, split into a 3-bit class (most
* significant bits) and a 5-bit detail (least significant bits)
*/
cm->code_class = (uint8_t) *ptr >> 5;
cm->code_detail = *ptr & 0x1F;
cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD);
ptr++;
/* Message ID: 16-bit unsigned integer in network byte order. */
cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1);
cm->flags |= MG_COAP_MSG_ID_FIELD;
ptr += 2;
return ptr;
}
/*
* Fills token information in mg_coap_message.
*
* Helper function.
*/
static char *coap_get_token(char *ptr, struct mbuf *io,
struct mg_coap_message *cm) {
if (cm->token.len != 0) {
if (ptr + cm->token.len > io->buf + io->len) {
cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
return NULL;
} else {
cm->token.p = ptr;
ptr += cm->token.len;
cm->flags |= MG_COAP_TOKEN_FIELD;
}
}
return ptr;
}
/*
* Returns Option Delta or Length.
*
* Helper function.
*/
static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) {
int ret = 0;
if (*opt_info == 13) {
/*
* 13: An 8-bit unsigned integer follows the initial byte and
* indicates the Option Delta/Length minus 13.
*/
if (ptr < io->buf + io->len) {
*opt_info = (uint8_t) *ptr + 13;
ret = sizeof(uint8_t);
} else {
ret = -1; /* LCOV_EXCL_LINE */
}
} else if (*opt_info == 14) {
/*
* 14: A 16-bit unsigned integer in network byte order follows the
* initial byte and indicates the Option Delta/Length minus 269.
*/
if (ptr + sizeof(uint8_t) < io->buf + io->len) {
*opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269;
ret = sizeof(uint16_t);
} else {
ret = -1; /* LCOV_EXCL_LINE */
}
}
return ret;
}
/*
* Fills options in mg_coap_message.
*
* Helper function.
*
* General options format:
* +---------------+---------------+
* | Option Delta | Option Length | 1 byte
* +---------------+---------------+
* \ Option Delta (extended) \ 0-2 bytes
* +-------------------------------+
* / Option Length (extended) \ 0-2 bytes
* +-------------------------------+
* \ Option Value \ 0 or more bytes
* +-------------------------------+
*/
static char *coap_get_options(char *ptr, struct mbuf *io,
struct mg_coap_message *cm) {
uint16_t prev_opt = 0;
if (ptr == io->buf + io->len) {
/* end of packet, ok */
return NULL;
}
/* 0xFF is payload marker */
while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) {
uint16_t option_delta, option_lenght;
int optinfo_len;
/* Option Delta: 4-bit unsigned integer */
option_delta = ((uint8_t) *ptr & 0xF0) >> 4;
/* Option Length: 4-bit unsigned integer */
option_lenght = *ptr & 0x0F;
if (option_delta == 15 || option_lenght == 15) {
/*
* 15: Reserved for future use. If the field is set to this value,
* it MUST be processed as a message format error
*/
cm->flags |= MG_COAP_FORMAT_ERROR;
break;
}
ptr++;
/* check for extended option delta */
optinfo_len = coap_get_ext_opt(ptr, io, &option_delta);
if (optinfo_len == -1) {
cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
break; /* LCOV_EXCL_LINE */
}
ptr += optinfo_len;
/* check or extended option lenght */
optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght);
if (optinfo_len == -1) {
cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
break; /* LCOV_EXCL_LINE */
}
ptr += optinfo_len;
/*
* Instead of specifying the Option Number directly, the instances MUST
* appear in order of their Option Numbers and a delta encoding is used
* between them.
*/
option_delta += prev_opt;
mg_coap_add_option(cm, option_delta, ptr, option_lenght);
prev_opt = option_delta;
if (ptr + option_lenght > io->buf + io->len) {
cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
break; /* LCOV_EXCL_LINE */
}
ptr += option_lenght;
}
if ((cm->flags & MG_COAP_ERROR) != 0) {
mg_coap_free_options(cm);
return NULL;
}
cm->flags |= MG_COAP_OPTIOMG_FIELD;
if (ptr == io->buf + io->len) {
/* end of packet, ok */
return NULL;
}
ptr++;
return ptr;
}
uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) {
char *ptr;
memset(cm, 0, sizeof(*cm));
if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) {
return cm->flags;
}
if ((ptr = coap_get_token(ptr, io, cm)) == NULL) {
return cm->flags;
}
if ((ptr = coap_get_options(ptr, io, cm)) == NULL) {
return cm->flags;
}
/* the rest is payload */
cm->payload.len = io->len - (ptr - io->buf);
if (cm->payload.len != 0) {
cm->payload.p = ptr;
cm->flags |= MG_COAP_PAYLOAD_FIELD;
}
return cm->flags;
}
/*
* Calculates extended size of given Opt Number/Length in coap message.
*
* Helper function.
*/
static size_t coap_get_ext_opt_size(uint32_t value) {
int ret = 0;
if (value >= 13 && value <= 0xFF + 13) {
ret = sizeof(uint8_t);
} else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
ret = sizeof(uint16_t);
}
return ret;
}
/*
* Splits given Opt Number/Length into base and ext values.
*
* Helper function.
*/
static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) {
int ret = 0;
if (value < 13) {
*base = value;
} else if (value >= 13 && value <= 0xFF + 13) {
*base = 13;
*ext = value - 13;
ret = sizeof(uint8_t);
} else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
*base = 14;
*ext = value - 269;
ret = sizeof(uint16_t);
}
return ret;
}
/*
* Puts uint16_t (in network order) into given char stream.
*
* Helper function.
*/
static char *coap_add_uint16(char *ptr, uint16_t val) {
*ptr = val >> 8;
ptr++;
*ptr = val & 0x00FF;
ptr++;
return ptr;
}
/*
* Puts extended value of Opt Number/Length into given char stream.
*
* Helper function.
*/
static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) {
if (len == sizeof(uint8_t)) {
*ptr = (char) val;
ptr++;
} else if (len == sizeof(uint16_t)) {
ptr = coap_add_uint16(ptr, val);
}
return ptr;
}
/*
* Verifies given mg_coap_message and calculates message size for it.
*
* Helper function.
*/
static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm,
size_t *len) {
struct mg_coap_option *opt;
uint32_t prev_opt_number;
*len = 4; /* header */
if (cm->msg_type > MG_COAP_MSG_MAX) {
return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD;
}
if (cm->token.len > 8) {
return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD;
}
if (cm->code_class > 7) {
return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD;
}
if (cm->code_detail > 31) {
return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD;
}
*len += cm->token.len;
if (cm->payload.len != 0) {
*len += cm->payload.len + 1; /* ... + 1; add payload marker */
}
opt = cm->options;
prev_opt_number = 0;
while (opt != NULL) {
*len += 1; /* basic delta/length */
*len += coap_get_ext_opt_size(opt->number - prev_opt_number);
*len += coap_get_ext_opt_size((uint32_t) opt->value.len);
/*
* Current implementation performs check if
* option_number > previous option_number and produces an error
* TODO(alashkin): write design doc with limitations
* May be resorting is more suitable solution.
*/
if ((opt->next != NULL && opt->number > opt->next->number) ||
opt->value.len > 0xFFFF + 269 ||
opt->number - prev_opt_number > 0xFFFF + 269) {
return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD;
}
*len += opt->value.len;
prev_opt_number = opt->number;
opt = opt->next;
}
return 0;
}
uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) {
struct mg_coap_option *opt;
uint32_t res, prev_opt_number;
size_t prev_io_len, packet_size;
char *ptr;
res = coap_calculate_packet_size(cm, &packet_size);
if (res != 0) {
return res;
}
/* saving previous lenght to handle non-empty mbuf */
prev_io_len = io->len;
if (mbuf_append(io, NULL, packet_size) == 0) return MG_COAP_ERROR;
ptr = io->buf + prev_io_len;
/*
* since cm is verified, it is possible to use bits shift operator
* without additional zeroing of unused bits
*/
/* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */
*ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len);
ptr++;
/* code class: 3 bits, code detail: 5 bits */
*ptr = (cm->code_class << 5) | (cm->code_detail);
ptr++;
ptr = coap_add_uint16(ptr, cm->msg_id);
if (cm->token.len != 0) {
memcpy(ptr, cm->token.p, cm->token.len);
ptr += cm->token.len;
}
opt = cm->options;
prev_opt_number = 0;
while (opt != NULL) {
uint8_t delta_base = 0, length_base = 0;
uint16_t delta_ext = 0, length_ext = 0;
size_t opt_delta_len =
coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext);
size_t opt_lenght_len =
coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext);
*ptr = (delta_base << 4) | length_base;
ptr++;
ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len);
ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len);
if (opt->value.len != 0) {
memcpy(ptr, opt->value.p, opt->value.len);
ptr += opt->value.len;
}
prev_opt_number = opt->number;
opt = opt->next;
}
if (cm->payload.len != 0) {
*ptr = (char) -1;
ptr++;
memcpy(ptr, cm->payload.p, cm->payload.len);
}
return 0;
}
uint32_t mg_coap_send_message(struct mg_connection *nc,
struct mg_coap_message *cm) {
struct mbuf packet_out;
uint32_t compose_res;
mbuf_init(&packet_out, 0);
compose_res = mg_coap_compose(cm, &packet_out);
if (compose_res != 0) {
return compose_res; /* LCOV_EXCL_LINE */
}
mg_send(nc, packet_out.buf, (int) packet_out.len);
mbuf_free(&packet_out);
return 0;
}
uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) {
struct mg_coap_message cm;
memset(&cm, 0, sizeof(cm));
cm.msg_type = MG_COAP_MSG_ACK;
cm.msg_id = msg_id;
return mg_coap_send_message(nc, &cm);
}
static void coap_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct mbuf *io = &nc->recv_mbuf;
struct mg_coap_message cm;
uint32_t parse_res;
memset(&cm, 0, sizeof(cm));
nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
switch (ev) {
case MG_EV_RECV:
parse_res = mg_coap_parse(io, &cm);
if ((parse_res & MG_COAP_IGNORE) == 0) {
if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) {
/*
* Since we support UDP only
* MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR
*/
cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */
} /* LCOV_EXCL_LINE */
nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type,
&cm MG_UD_ARG(user_data));
}
mg_coap_free_options(&cm);
mbuf_remove(io, io->len);
break;
}
}
/*
* Attach built-in CoAP event handler to the given connection.
*
* The user-defined event handler will receive following extra events:
*
* - MG_EV_COAP_CON
* - MG_EV_COAP_NOC
* - MG_EV_COAP_ACK
* - MG_EV_COAP_RST
*/
int mg_set_protocol_coap(struct mg_connection *nc) {
/* supports UDP only */
if ((nc->flags & MG_F_UDP) == 0) {
return -1;
}
nc->proto_handler = coap_handler;
return 0;
}
#endif /* MG_ENABLE_COAP */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_sntp.c"
#endif
/*
* Copyright (c) 2016 Cesanta Software Limited
* All rights reserved
*/
/* Amalgamated: #include "mg_internal.h" */
/* Amalgamated: #include "mg_sntp.h" */
/* Amalgamated: #include "mg_util.h" */
#if MG_ENABLE_SNTP
#define SNTP_TIME_OFFSET 2208988800
#ifndef SNTP_TIMEOUT
#define SNTP_TIMEOUT 10
#endif
#ifndef SNTP_ATTEMPTS
#define SNTP_ATTEMPTS 3
#endif
static uint64_t mg_get_sec(uint64_t val) {
return (val & 0xFFFFFFFF00000000) >> 32;
}
static uint64_t mg_get_usec(uint64_t val) {
uint64_t tmp = (val & 0x00000000FFFFFFFF);
tmp *= 1000000;
tmp >>= 32;
return tmp;
}
static void mg_ntp_to_tv(uint64_t val, struct timeval *tv) {
uint64_t tmp;
tmp = mg_get_sec(val);
tmp -= SNTP_TIME_OFFSET;
tv->tv_sec = tmp;
tv->tv_usec = mg_get_usec(val);
}
static void mg_get_ntp_ts(const char *ntp, uint64_t *val) {
uint32_t tmp;
memcpy(&tmp, ntp, sizeof(tmp));
tmp = ntohl(tmp);
*val = (uint64_t) tmp << 32;
memcpy(&tmp, ntp + 4, sizeof(tmp));
tmp = ntohl(tmp);
*val |= tmp;
}
void mg_sntp_send_request(struct mg_connection *c) {
uint8_t buf[48] = {0};
/*
* header - 8 bit:
* LI (2 bit) - 3 (not in sync), VN (3 bit) - 4 (version),
* mode (3 bit) - 3 (client)
*/
buf[0] = (3 << 6) | (4 << 3) | 3;
/*
* Next fields should be empty in client request
* stratum, 8 bit
* poll interval, 8 bit
* rrecision, 8 bit
* root delay, 32 bit
* root dispersion, 32 bit
* ref id, 32 bit
* ref timestamp, 64 bit
* originate Timestamp, 64 bit
* receive Timestamp, 64 bit
*/
/*
* convert time to sntp format (sntp starts from 00:00:00 01.01.1900)
* according to rfc868 it is 2208988800L sec
* this information is used to correct roundtrip delay
* but if local clock is absolutely broken (and doesn't work even
* as simple timer), it is better to disable it
*/
#ifndef MG_SNTP_NO_DELAY_CORRECTION
uint32_t sec;
sec = htonl((uint32_t)(mg_time() + SNTP_TIME_OFFSET));
memcpy(&buf[40], &sec, sizeof(sec));
#endif
mg_send(c, buf, sizeof(buf));
}
#ifndef MG_SNTP_NO_DELAY_CORRECTION
static uint64_t mg_calculate_delay(uint64_t t1, uint64_t t2, uint64_t t3) {
/* roundloop delay = (T4 - T1) - (T3 - T2) */
uint64_t d1 = ((mg_time() + SNTP_TIME_OFFSET) * 1000000) -
(mg_get_sec(t1) * 1000000 + mg_get_usec(t1));
uint64_t d2 = (mg_get_sec(t3) * 1000000 + mg_get_usec(t3)) -
(mg_get_sec(t2) * 1000000 + mg_get_usec(t2));
return (d1 > d2) ? d1 - d2 : 0;
}
#endif
MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
struct mg_sntp_message *msg) {
uint8_t hdr;
uint64_t trsm_ts_T3, delay = 0;
int mode;
struct timeval tv;
if (len < 48) {
return -1;
}
hdr = buf[0];
if ((hdr & 0x38) >> 3 != 4) {
/* Wrong version */
return -1;
}
mode = hdr & 0x7;
if (mode != 4 && mode != 5) {
/* Not a server reply */
return -1;
}
memset(msg, 0, sizeof(*msg));
msg->kiss_of_death = (buf[1] == 0); /* Server asks to not send requests */
mg_get_ntp_ts(&buf[40], &trsm_ts_T3);
#ifndef MG_SNTP_NO_DELAY_CORRECTION
{
uint64_t orig_ts_T1, recv_ts_T2;
mg_get_ntp_ts(&buf[24], &orig_ts_T1);
mg_get_ntp_ts(&buf[32], &recv_ts_T2);
delay = mg_calculate_delay(orig_ts_T1, recv_ts_T2, trsm_ts_T3);
}
#endif
mg_ntp_to_tv(trsm_ts_T3, &tv);
msg->time = (double) tv.tv_sec + (((double) tv.tv_usec + delay) / 1000000.0);
return 0;
}
static void mg_sntp_handler(struct mg_connection *c, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct mbuf *io = &c->recv_mbuf;
struct mg_sntp_message msg;
c->handler(c, ev, ev_data MG_UD_ARG(user_data));
switch (ev) {
case MG_EV_RECV: {
if (mg_sntp_parse_reply(io->buf, io->len, &msg) < 0) {
DBG(("Invalid SNTP packet received (%d)", (int) io->len));
c->handler(c, MG_SNTP_MALFORMED_REPLY, NULL MG_UD_ARG(user_data));
} else {
c->handler(c, MG_SNTP_REPLY, (void *) &msg MG_UD_ARG(user_data));
}
mbuf_remove(io, io->len);
break;
}
}
}
int mg_set_protocol_sntp(struct mg_connection *c) {
if ((c->flags & MG_F_UDP) == 0) {
return -1;
}
c->proto_handler = mg_sntp_handler;
return 0;
}
struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr,
MG_CB(mg_event_handler_t event_handler,
void *user_data),
const char *sntp_server_name) {
struct mg_connection *c = NULL;
char url[100], *p_url = url;
const char *proto = "", *port = "", *tmp;
/* If port is not specified, use default (123) */
tmp = strchr(sntp_server_name, ':');
if (tmp != NULL && *(tmp + 1) == '/') {
tmp = strchr(tmp + 1, ':');
}
if (tmp == NULL) {
port = ":123";
}
/* Add udp:// if needed */
if (strncmp(sntp_server_name, "udp://", 6) != 0) {
proto = "udp://";
}
mg_asprintf(&p_url, sizeof(url), "%s%s%s", proto, sntp_server_name, port);
c = mg_connect(mgr, p_url, event_handler MG_UD_ARG(user_data));
if (c == NULL) {
goto cleanup;
}
mg_set_protocol_sntp(c);
cleanup:
if (p_url != url) {
MG_FREE(p_url);
}
return c;
}
struct sntp_data {
mg_event_handler_t hander;
int count;
};
static void mg_sntp_util_ev_handler(struct mg_connection *c, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
#if !MG_ENABLE_CALLBACK_USERDATA
void *user_data = c->user_data;
#endif
struct sntp_data *sd = (struct sntp_data *) user_data;
switch (ev) {
case MG_EV_CONNECT:
if (*(int *) ev_data != 0) {
mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
break;
}
/* fallthrough */
case MG_EV_TIMER:
if (sd->count <= SNTP_ATTEMPTS) {
mg_sntp_send_request(c);
mg_set_timer(c, mg_time() + 10);
sd->count++;
} else {
mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
c->flags |= MG_F_CLOSE_IMMEDIATELY;
}
break;
case MG_SNTP_MALFORMED_REPLY:
mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
c->flags |= MG_F_CLOSE_IMMEDIATELY;
break;
case MG_SNTP_REPLY:
mg_call(c, sd->hander, c->user_data, MG_SNTP_REPLY, ev_data);
c->flags |= MG_F_CLOSE_IMMEDIATELY;
break;
case MG_EV_CLOSE:
MG_FREE(user_data);
c->user_data = NULL;
break;
}
}
struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr,
mg_event_handler_t event_handler,
const char *sntp_server_name) {
struct mg_connection *c;
struct sntp_data *sd = (struct sntp_data *) MG_CALLOC(1, sizeof(*sd));
if (sd == NULL) {
return NULL;
}
c = mg_sntp_connect(mgr, MG_CB(mg_sntp_util_ev_handler, sd),
sntp_server_name);
if (c == NULL) {
MG_FREE(sd);
return NULL;
}
sd->hander = event_handler;
#if !MG_ENABLE_CALLBACK_USERDATA
c->user_data = sd;
#endif
return c;
}
#endif /* MG_ENABLE_SNTP */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mg_socks.c"
#endif
/*
* Copyright (c) 2017 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_SOCKS
/* Amalgamated: #include "mg_socks.h" */
/* Amalgamated: #include "mg_internal.h" */
/*
* https://www.ietf.org/rfc/rfc1928.txt paragraph 3, handle client handshake
*
* +----+----------+----------+
* |VER | NMETHODS | METHODS |
* +----+----------+----------+
* | 1 | 1 | 1 to 255 |
* +----+----------+----------+
*/
static void mg_socks5_handshake(struct mg_connection *c) {
struct mbuf *r = &c->recv_mbuf;
if (r->buf[0] != MG_SOCKS_VERSION) {
c->flags |= MG_F_CLOSE_IMMEDIATELY;
} else if (r->len > 2 && (size_t) r->buf[1] + 2 <= r->len) {
/* https://www.ietf.org/rfc/rfc1928.txt paragraph 3 */
unsigned char reply[2] = {MG_SOCKS_VERSION, MG_SOCKS_HANDSHAKE_FAILURE};
int i;
for (i = 2; i < r->buf[1] + 2; i++) {
/* TODO(lsm): support other auth methods */
if (r->buf[i] == MG_SOCKS_HANDSHAKE_NOAUTH) reply[1] = r->buf[i];
}
mbuf_remove(r, 2 + r->buf[1]);
mg_send(c, reply, sizeof(reply));
c->flags |= MG_SOCKS_HANDSHAKE_DONE; /* Mark handshake done */
}
}
static void disband(struct mg_connection *c) {
struct mg_connection *c2 = (struct mg_connection *) c->user_data;
if (c2 != NULL) {
c2->flags |= MG_F_SEND_AND_CLOSE;
c2->user_data = NULL;
}
c->flags |= MG_F_SEND_AND_CLOSE;
c->user_data = NULL;
}
static void relay_data(struct mg_connection *c) {
struct mg_connection *c2 = (struct mg_connection *) c->user_data;
if (c2 != NULL) {
mg_send(c2, c->recv_mbuf.buf, c->recv_mbuf.len);
mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len);
} else {
c->flags |= MG_F_SEND_AND_CLOSE;
}
}
static void serv_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_CLOSE) {
disband(c);
} else if (ev == MG_EV_RECV) {
relay_data(c);
} else if (ev == MG_EV_CONNECT) {
int res = *(int *) ev_data;
if (res != 0) LOG(LL_ERROR, ("connect error: %d", res));
}
}
static void mg_socks5_connect(struct mg_connection *c, const char *addr) {
struct mg_connection *serv = mg_connect(c->mgr, addr, serv_ev_handler);
serv->user_data = c;
c->user_data = serv;
}
/*
* Request, https://www.ietf.org/rfc/rfc1928.txt paragraph 4
*
* +----+-----+-------+------+----------+----------+
* |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
* +----+-----+-------+------+----------+----------+
* | 1 | 1 | X'00' | 1 | Variable | 2 |
* +----+-----+-------+------+----------+----------+
*/
static void mg_socks5_handle_request(struct mg_connection *c) {
struct mbuf *r = &c->recv_mbuf;
unsigned char *p = (unsigned char *) r->buf;
unsigned char addr_len = 4, reply = MG_SOCKS_SUCCESS;
int ver, cmd, atyp;
char addr[300];
if (r->len < 8) return; /* return if not fully buffered. min DST.ADDR is 2 */
ver = p[0];
cmd = p[1];
atyp = p[3];
/* TODO(lsm): support other commands */
if (ver != MG_SOCKS_VERSION || cmd != MG_SOCKS_CMD_CONNECT) {
reply = MG_SOCKS_CMD_NOT_SUPPORTED;
} else if (atyp == MG_SOCKS_ADDR_IPV4) {
addr_len = 4;
if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
snprintf(addr, sizeof(addr), "%d.%d.%d.%d:%d", p[4], p[5], p[6], p[7],
p[8] << 8 | p[9]);
mg_socks5_connect(c, addr);
} else if (atyp == MG_SOCKS_ADDR_IPV6) {
addr_len = 16;
if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
snprintf(addr, sizeof(addr), "[%x:%x:%x:%x:%x:%x:%x:%x]:%d",
p[4] << 8 | p[5], p[6] << 8 | p[7], p[8] << 8 | p[9],
p[10] << 8 | p[11], p[12] << 8 | p[13], p[14] << 8 | p[15],
p[16] << 8 | p[17], p[18] << 8 | p[19], p[20] << 8 | p[21]);
mg_socks5_connect(c, addr);
} else if (atyp == MG_SOCKS_ADDR_DOMAIN) {
addr_len = p[4] + 1;
if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
snprintf(addr, sizeof(addr), "%.*s:%d", p[4], p + 5,
p[4 + addr_len] << 8 | p[4 + addr_len + 1]);
mg_socks5_connect(c, addr);
} else {
reply = MG_SOCKS_ADDR_NOT_SUPPORTED;
}
/*
* Reply, https://www.ietf.org/rfc/rfc1928.txt paragraph 5
*
* +----+-----+-------+------+----------+----------+
* |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
* +----+-----+-------+------+----------+----------+
* | 1 | 1 | X'00' | 1 | Variable | 2 |
* +----+-----+-------+------+----------+----------+
*/
{
unsigned char buf[] = {MG_SOCKS_VERSION, reply, 0};
mg_send(c, buf, sizeof(buf));
}
mg_send(c, r->buf + 3, addr_len + 1 + 2);
mbuf_remove(r, 6 + addr_len); /* Remove request from the input stream */
c->flags |= MG_SOCKS_CONNECT_DONE; /* Mark ourselves as connected */
}
static void socks_handler(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_RECV) {
if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) mg_socks5_handshake(c);
if (c->flags & MG_SOCKS_HANDSHAKE_DONE &&
!(c->flags & MG_SOCKS_CONNECT_DONE)) {
mg_socks5_handle_request(c);
}
if (c->flags & MG_SOCKS_CONNECT_DONE) relay_data(c);
} else if (ev == MG_EV_CLOSE) {
disband(c);
}
(void) ev_data;
}
void mg_set_protocol_socks(struct mg_connection *c) {
c->proto_handler = socks_handler;
}
#endif
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/cc3200/cc3200_libc.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if CS_PLATFORM == CS_P_CC3200
/* Amalgamated: #include "common/mg_mem.h" */
#include <stdio.h>
#include <string.h>
#ifndef __TI_COMPILER_VERSION__
#include <reent.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#endif
#include <inc/hw_types.h>
#include <inc/hw_memmap.h>
#include <driverlib/prcm.h>
#include <driverlib/rom.h>
#include <driverlib/rom_map.h>
#include <driverlib/uart.h>
#include <driverlib/utils.h>
#define CONSOLE_UART UARTA0_BASE
#ifdef __TI_COMPILER_VERSION__
int asprintf(char **strp, const char *fmt, ...) {
va_list ap;
int len;
*strp = MG_MALLOC(BUFSIZ);
if (*strp == NULL) return -1;
va_start(ap, fmt);
len = vsnprintf(*strp, BUFSIZ, fmt, ap);
va_end(ap);
if (len > 0) {
*strp = MG_REALLOC(*strp, len + 1);
if (*strp == NULL) return -1;
}
if (len >= BUFSIZ) {
va_start(ap, fmt);
len = vsnprintf(*strp, len + 1, fmt, ap);
va_end(ap);
}
return len;
}
#if MG_TI_NO_HOST_INTERFACE
time_t HOSTtime() {
struct timeval tp;
gettimeofday(&tp, NULL);
return tp.tv_sec;
}
#endif
#endif /* __TI_COMPILER_VERSION__ */
void fprint_str(FILE *fp, const char *str) {
while (*str != '\0') {
if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r');
MAP_UARTCharPut(CONSOLE_UART, *str++);
}
}
void _exit(int status) {
fprint_str(stderr, "_exit\n");
/* cause an unaligned access exception, that will drop you into gdb */
*(int *) 1 = status;
while (1)
; /* avoid gcc warning because stdlib abort() has noreturn attribute */
}
void _not_implemented(const char *what) {
fprint_str(stderr, what);
fprint_str(stderr, " is not implemented\n");
_exit(42);
}
int _kill(int pid, int sig) {
(void) pid;
(void) sig;
_not_implemented("_kill");
return -1;
}
int _getpid() {
fprint_str(stderr, "_getpid is not implemented\n");
return 42;
}
int _isatty(int fd) {
/* 0, 1 and 2 are TTYs. */
return fd < 2;
}
#endif /* CS_PLATFORM == CS_P_CC3200 */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/msp432/msp432_libc.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if CS_PLATFORM == CS_P_MSP432
#include <ti/sysbios/BIOS.h>
#include <ti/sysbios/knl/Clock.h>
int gettimeofday(struct timeval *tp, void *tzp) {
uint32_t ticks = Clock_getTicks();
tp->tv_sec = ticks / 1000;
tp->tv_usec = (ticks % 1000) * 1000;
return 0;
}
#endif /* CS_PLATFORM == CS_P_MSP432 */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/nrf5/nrf5_libc.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \
defined(__ARMCC_VERSION)
int gettimeofday(struct timeval *tp, void *tzp) {
/* TODO */
tp->tv_sec = 0;
tp->tv_usec = 0;
return 0;
}
#endif
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_fs_slfs.h"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
#if defined(MG_FS_SLFS)
#include <stdio.h>
#ifndef __TI_COMPILER_VERSION__
#include <unistd.h>
#include <sys/stat.h>
#endif
#define MAX_OPEN_SLFS_FILES 8
/* Indirect libc interface - same functions, different names. */
int fs_slfs_open(const char *pathname, int flags, mode_t mode);
int fs_slfs_close(int fd);
ssize_t fs_slfs_read(int fd, void *buf, size_t count);
ssize_t fs_slfs_write(int fd, const void *buf, size_t count);
int fs_slfs_stat(const char *pathname, struct stat *s);
int fs_slfs_fstat(int fd, struct stat *s);
off_t fs_slfs_lseek(int fd, off_t offset, int whence);
int fs_slfs_unlink(const char *filename);
int fs_slfs_rename(const char *from, const char *to);
void fs_slfs_set_file_size(const char *name, size_t size);
void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token);
void fs_slfs_unset_file_flags(const char *name);
#endif /* defined(MG_FS_SLFS) */
#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_fs_slfs.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Standard libc interface to TI SimpleLink FS. */
#if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS)
/* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */
#include <errno.h>
#if CS_PLATFORM == CS_P_CC3200
#include <inc/hw_types.h>
#endif
/* Amalgamated: #include "common/cs_dbg.h" */
/* Amalgamated: #include "common/mg_mem.h" */
#if SL_MAJOR_VERSION_NUM < 2
int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) {
_i32 fh;
_i32 r = sl_FsOpen(fname, flags, (unsigned long *) token, &fh);
return (r < 0 ? r : fh);
}
#else /* SL_MAJOR_VERSION_NUM >= 2 */
int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) {
return sl_FsOpen(fname, flags, (unsigned long *) token);
}
#endif
/* From sl_fs.c */
int set_errno(int e);
const char *drop_dir(const char *fname, bool *is_slfs);
/*
* With SLFS, you have to pre-declare max file size. Yes. Really.
* 64K should be enough for everyone. Right?
*/
#ifndef FS_SLFS_MAX_FILE_SIZE
#define FS_SLFS_MAX_FILE_SIZE (64 * 1024)
#endif
struct sl_file_open_info {
char *name;
size_t size;
uint32_t flags;
uint32_t *token;
};
struct sl_fd_info {
_i32 fh;
_off_t pos;
size_t size;
};
static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES];
static struct sl_file_open_info s_sl_file_open_infos[MAX_OPEN_SLFS_FILES];
static struct sl_file_open_info *fs_slfs_find_foi(const char *name,
bool create);
static int sl_fs_to_errno(_i32 r) {
DBG(("SL error: %d", (int) r));
switch (r) {
case SL_FS_OK:
return 0;
case SL_ERROR_FS_FILE_NAME_EXIST:
return EEXIST;
case SL_ERROR_FS_WRONG_FILE_NAME:
return EINVAL;
case SL_ERROR_FS_NO_AVAILABLE_NV_INDEX:
case SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE:
return ENOSPC;
case SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM:
return ENOMEM;
case SL_ERROR_FS_FILE_NOT_EXISTS:
return ENOENT;
case SL_ERROR_FS_NOT_SUPPORTED:
return ENOTSUP;
}
return ENXIO;
}
int fs_slfs_open(const char *pathname, int flags, mode_t mode) {
int fd;
for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) {
if (s_sl_fds[fd].fh <= 0) break;
}
if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM);
struct sl_fd_info *fi = &s_sl_fds[fd];
/*
* Apply path manipulations again, in case we got here directly
* (via TI libc's "add_device").
*/
pathname = drop_dir(pathname, NULL);
_u32 am = 0;
fi->size = (size_t) -1;
int rw = (flags & 3);
size_t new_size = 0;
struct sl_file_open_info *foi =
fs_slfs_find_foi(pathname, false /* create */);
if (foi != NULL) {
LOG(LL_DEBUG, ("FOI for %s: %d 0x%x %p", pathname, (int) foi->size,
(unsigned int) foi->flags, foi->token));
}
if (rw == O_RDONLY) {
SlFsFileInfo_t sl_fi;
_i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
if (r == SL_FS_OK) {
fi->size = SL_FI_FILE_SIZE(sl_fi);
}
am = SL_FS_READ;
} else {
if (!(flags & O_TRUNC) || (flags & O_APPEND)) {
// FailFS files cannot be opened for append and will be truncated
// when opened for write.
return set_errno(ENOTSUP);
}
if (flags & O_CREAT) {
if (foi->size > 0) {
new_size = foi->size;
} else {
new_size = FS_SLFS_MAX_FILE_SIZE;
}
am = FS_MODE_OPEN_CREATE(new_size, 0);
} else {
am = SL_FS_WRITE;
}
#if SL_MAJOR_VERSION_NUM >= 2
am |= SL_FS_OVERWRITE;
#endif
}
uint32_t *token = NULL;
if (foi != NULL) {
am |= foi->flags;
token = foi->token;
}
fi->fh = slfs_open((_u8 *) pathname, am, token);
LOG(LL_DEBUG, ("sl_FsOpen(%s, 0x%x, %p) sz %u = %d", pathname, (int) am,
token, (unsigned int) new_size, (int) fi->fh));
int r;
if (fi->fh >= 0) {
fi->pos = 0;
r = fd;
} else {
r = set_errno(sl_fs_to_errno(fi->fh));
}
return r;
}
int fs_slfs_close(int fd) {
struct sl_fd_info *fi = &s_sl_fds[fd];
if (fi->fh <= 0) return set_errno(EBADF);
_i32 r = sl_FsClose(fi->fh, NULL, NULL, 0);
LOG(LL_DEBUG, ("sl_FsClose(%d) = %d", (int) fi->fh, (int) r));
s_sl_fds[fd].fh = -1;
return set_errno(sl_fs_to_errno(r));
}
ssize_t fs_slfs_read(int fd, void *buf, size_t count) {
struct sl_fd_info *fi = &s_sl_fds[fd];
if (fi->fh <= 0) return set_errno(EBADF);
/* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE.
*/
if (fi->pos == fi->size) return 0;
_i32 r = sl_FsRead(fi->fh, fi->pos, buf, count);
DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
(int) r));
if (r >= 0) {
fi->pos += r;
return r;
}
return set_errno(sl_fs_to_errno(r));
}
ssize_t fs_slfs_write(int fd, const void *buf, size_t count) {
struct sl_fd_info *fi = &s_sl_fds[fd];
if (fi->fh <= 0) return set_errno(EBADF);
_i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count);
DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
(int) r));
if (r >= 0) {
fi->pos += r;
return r;
}
return set_errno(sl_fs_to_errno(r));
}
int fs_slfs_stat(const char *pathname, struct stat *s) {
SlFsFileInfo_t sl_fi;
/*
* Apply path manipulations again, in case we got here directly
* (via TI libc's "add_device").
*/
pathname = drop_dir(pathname, NULL);
_i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
if (r == SL_FS_OK) {
s->st_mode = S_IFREG | 0666;
s->st_nlink = 1;
s->st_size = SL_FI_FILE_SIZE(sl_fi);
return 0;
}
return set_errno(sl_fs_to_errno(r));
}
int fs_slfs_fstat(int fd, struct stat *s) {
struct sl_fd_info *fi = &s_sl_fds[fd];
if (fi->fh <= 0) return set_errno(EBADF);
s->st_mode = 0666;
s->st_mode = S_IFREG | 0666;
s->st_nlink = 1;
s->st_size = fi->size;
return 0;
}
off_t fs_slfs_lseek(int fd, off_t offset, int whence) {
if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF);
switch (whence) {
case SEEK_SET:
s_sl_fds[fd].pos = offset;
break;
case SEEK_CUR:
s_sl_fds[fd].pos += offset;
break;
case SEEK_END:
return set_errno(ENOTSUP);
}
return 0;
}
int fs_slfs_unlink(const char *pathname) {
/*
* Apply path manipulations again, in case we got here directly
* (via TI libc's "add_device").
*/
pathname = drop_dir(pathname, NULL);
return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) pathname, 0)));
}
int fs_slfs_rename(const char *from, const char *to) {
return set_errno(ENOTSUP);
}
static struct sl_file_open_info *fs_slfs_find_foi(const char *name,
bool create) {
int i = 0;
for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
if (s_sl_file_open_infos[i].name != NULL &&
strcmp(drop_dir(s_sl_file_open_infos[i].name, NULL), name) == 0) {
break;
}
}
if (i != MAX_OPEN_SLFS_FILES) return &s_sl_file_open_infos[i];
if (!create) return NULL;
for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
if (s_sl_file_open_infos[i].name == NULL) break;
}
if (i == MAX_OPEN_SLFS_FILES) {
i = 0; /* Evict a random slot. */
}
if (s_sl_file_open_infos[i].name != NULL) {
free(s_sl_file_open_infos[i].name);
}
s_sl_file_open_infos[i].name = strdup(name);
return &s_sl_file_open_infos[i];
}
void fs_slfs_set_file_size(const char *name, size_t size) {
struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */);
foi->size = size;
}
void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token) {
struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */);
foi->flags = flags;
foi->token = token;
}
void fs_slfs_unset_file_flags(const char *name) {
struct sl_file_open_info *foi = fs_slfs_find_foi(name, false /* create */);
if (foi == NULL) return;
free(foi->name);
memset(foi, 0, sizeof(*foi));
}
#endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_fs.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if MG_NET_IF == MG_NET_IF_SIMPLELINK && \
(defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS))
int set_errno(int e) {
errno = e;
return (e == 0 ? 0 : -1);
}
const char *drop_dir(const char *fname, bool *is_slfs) {
if (is_slfs != NULL) {
*is_slfs = (strncmp(fname, "SL:", 3) == 0);
if (*is_slfs) fname += 3;
}
/* Drop "./", if any */
if (fname[0] == '.' && fname[1] == '/') {
fname += 2;
}
/*
* Drop / if it is the only one in the path.
* This allows use of /pretend/directories but serves /file.txt as normal.
*/
if (fname[0] == '/' && strchr(fname + 1, '/') == NULL) {
fname++;
}
return fname;
}
#if !defined(MG_FS_NO_VFS)
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __TI_COMPILER_VERSION__
#include <file.h>
#endif
/* Amalgamated: #include "common/cs_dbg.h" */
/* Amalgamated: #include "common/platform.h" */
#ifdef CC3200_FS_SPIFFS
/* Amalgamated: #include "cc3200_fs_spiffs.h" */
#endif
#ifdef MG_FS_SLFS
/* Amalgamated: #include "sl_fs_slfs.h" */
#endif
#define NUM_SYS_FDS 3
#define SPIFFS_FD_BASE 10
#define SLFS_FD_BASE 100
#if !defined(MG_UART_CHAR_PUT) && !defined(MG_UART_WRITE)
#if CS_PLATFORM == CS_P_CC3200
#include <inc/hw_types.h>
#include <inc/hw_memmap.h>
#include <driverlib/rom.h>
#include <driverlib/rom_map.h>
#include <driverlib/uart.h>
#define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c);
#else
#define MG_UART_WRITE(fd, buf, len)
#endif /* CS_PLATFORM == CS_P_CC3200 */
#endif /* !MG_UART_CHAR_PUT */
enum fd_type {
FD_INVALID,
FD_SYS,
#ifdef CC3200_FS_SPIFFS
FD_SPIFFS,
#endif
#ifdef MG_FS_SLFS
FD_SLFS
#endif
};
static int fd_type(int fd) {
if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS;
#ifdef CC3200_FS_SPIFFS
if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) {
return FD_SPIFFS;
}
#endif
#ifdef MG_FS_SLFS
if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) {
return FD_SLFS;
}
#endif
return FD_INVALID;
}
#if MG_TI_NO_HOST_INTERFACE
int open(const char *pathname, unsigned flags, int mode) {
#else
int _open(const char *pathname, int flags, mode_t mode) {
#endif
int fd = -1;
bool is_sl;
const char *fname = drop_dir(pathname, &is_sl);
if (is_sl) {
#ifdef MG_FS_SLFS
fd = fs_slfs_open(fname, flags, mode);
if (fd >= 0) fd += SLFS_FD_BASE;
#endif
} else {
#ifdef CC3200_FS_SPIFFS
fd = fs_spiffs_open(fname, flags, mode);
if (fd >= 0) fd += SPIFFS_FD_BASE;
#endif
}
LOG(LL_DEBUG,
("open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname));
return fd;
}
int _stat(const char *pathname, struct stat *st) {
int res = -1;
bool is_sl;
const char *fname = drop_dir(pathname, &is_sl);
memset(st, 0, sizeof(*st));
/* Simulate statting the root directory. */
if (fname[0] == '\0' || strcmp(fname, ".") == 0) {
st->st_ino = 0;
st->st_mode = S_IFDIR | 0777;
st->st_nlink = 1;
st->st_size = 0;
return 0;
}
if (is_sl) {
#ifdef MG_FS_SLFS
res = fs_slfs_stat(fname, st);
#endif
} else {
#ifdef CC3200_FS_SPIFFS
res = fs_spiffs_stat(fname, st);
#endif
}
LOG(LL_DEBUG, ("stat(%s) = %d; fname = %s", pathname, res, fname));
return res;
}
#if MG_TI_NO_HOST_INTERFACE
int close(int fd) {
#else
int _close(int fd) {
#endif
int r = -1;
switch (fd_type(fd)) {
case FD_INVALID:
r = set_errno(EBADF);
break;
case FD_SYS:
r = set_errno(EACCES);
break;
#ifdef CC3200_FS_SPIFFS
case FD_SPIFFS:
r = fs_spiffs_close(fd - SPIFFS_FD_BASE);
break;
#endif
#ifdef MG_FS_SLFS
case FD_SLFS:
r = fs_slfs_close(fd - SLFS_FD_BASE);
break;
#endif
}
DBG(("close(%d) = %d", fd, r));
return r;
}
#if MG_TI_NO_HOST_INTERFACE
off_t lseek(int fd, off_t offset, int whence) {
#else
off_t _lseek(int fd, off_t offset, int whence) {
#endif
int r = -1;
switch (fd_type(fd)) {
case FD_INVALID:
r = set_errno(EBADF);
break;
case FD_SYS:
r = set_errno(ESPIPE);
break;
#ifdef CC3200_FS_SPIFFS
case FD_SPIFFS:
r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence);
break;
#endif
#ifdef MG_FS_SLFS
case FD_SLFS:
r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence);
break;
#endif
}
DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r));
return r;
}
int _fstat(int fd, struct stat *s) {
int r = -1;
memset(s, 0, sizeof(*s));
switch (fd_type(fd)) {
case FD_INVALID:
r = set_errno(EBADF);
break;
case FD_SYS: {
/* Create barely passable stats for STD{IN,OUT,ERR}. */
memset(s, 0, sizeof(*s));
s->st_ino = fd;
s->st_mode = S_IFCHR | 0666;
r = 0;
break;
}
#ifdef CC3200_FS_SPIFFS
case FD_SPIFFS:
r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s);
break;
#endif
#ifdef MG_FS_SLFS
case FD_SLFS:
r = fs_slfs_fstat(fd - SLFS_FD_BASE, s);
break;
#endif
}
DBG(("fstat(%d) = %d", fd, r));
return r;
}
#if MG_TI_NO_HOST_INTERFACE
int read(int fd, char *buf, unsigned count) {
#else
ssize_t _read(int fd, void *buf, size_t count) {
#endif
int r = -1;
switch (fd_type(fd)) {
case FD_INVALID:
r = set_errno(EBADF);
break;
case FD_SYS: {
if (fd != 0) {
r = set_errno(EACCES);
break;
}
/* Should we allow reading from stdin = uart? */
r = set_errno(ENOTSUP);
break;
}
#ifdef CC3200_FS_SPIFFS
case FD_SPIFFS:
r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count);
break;
#endif
#ifdef MG_FS_SLFS
case FD_SLFS:
r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count);
break;
#endif
}
DBG(("read(%d, %u) = %d", fd, count, r));
return r;
}
#if MG_TI_NO_HOST_INTERFACE
int write(int fd, const char *buf, unsigned count) {
#else
ssize_t _write(int fd, const void *buf, size_t count) {
#endif
int r = -1;
switch (fd_type(fd)) {
case FD_INVALID:
r = set_errno(EBADF);
break;
case FD_SYS: {
if (fd == 0) {
r = set_errno(EACCES);
break;
}
#ifdef MG_UART_WRITE
MG_UART_WRITE(fd, buf, count);
#elif defined(MG_UART_CHAR_PUT)
{
size_t i;
for (i = 0; i < count; i++) {
const char c = ((const char *) buf)[i];
if (c == '\n') MG_UART_CHAR_PUT(fd, '\r');
MG_UART_CHAR_PUT(fd, c);
}
}
#endif
r = count;
break;
}
#ifdef CC3200_FS_SPIFFS
case FD_SPIFFS:
r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count);
break;
#endif
#ifdef MG_FS_SLFS
case FD_SLFS:
r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count);
break;
#endif
}
return r;
}
/*
* On Newlib we override rename directly too, because the default
* implementation using _link and _unlink doesn't work for us.
*/
#if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION)
int rename(const char *frompath, const char *topath) {
int r = -1;
bool is_sl_from, is_sl_to;
const char *from = drop_dir(frompath, &is_sl_from);
const char *to = drop_dir(topath, &is_sl_to);
if (is_sl_from || is_sl_to) {
set_errno(ENOTSUP);
} else {
#ifdef CC3200_FS_SPIFFS
r = fs_spiffs_rename(from, to);
#endif
}
DBG(("rename(%s, %s) = %d", from, to, r));
return r;
}
#endif /* MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) */
#if MG_TI_NO_HOST_INTERFACE
int unlink(const char *pathname) {
#else
int _unlink(const char *pathname) {
#endif
int r = -1;
bool is_sl;
const char *fname = drop_dir(pathname, &is_sl);
if (is_sl) {
#ifdef MG_FS_SLFS
r = fs_slfs_unlink(fname);
#endif
} else {
#ifdef CC3200_FS_SPIFFS
r = fs_spiffs_unlink(fname);
#endif
}
DBG(("unlink(%s) = %d, fname = %s", pathname, r, fname));
return r;
}
#ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */
DIR *opendir(const char *dir_name) {
DIR *r = NULL;
bool is_sl;
drop_dir(dir_name, &is_sl);
if (is_sl) {
r = NULL;
set_errno(ENOTSUP);
} else {
r = fs_spiffs_opendir(dir_name);
}
DBG(("opendir(%s) = %p", dir_name, r));
return r;
}
struct dirent *readdir(DIR *dir) {
struct dirent *res = fs_spiffs_readdir(dir);
DBG(("readdir(%p) = %p", dir, res));
return res;
}
int closedir(DIR *dir) {
int res = fs_spiffs_closedir(dir);
DBG(("closedir(%p) = %d", dir, res));
return res;
}
int rmdir(const char *path) {
return fs_spiffs_rmdir(path);
}
int mkdir(const char *path, mode_t mode) {
(void) path;
(void) mode;
/* for spiffs supports only root dir, which comes from mongoose as '.' */
return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR;
}
#endif
int sl_fs_init(void) {
int ret = 1;
#ifdef __TI_COMPILER_VERSION__
#ifdef MG_FS_SLFS
#pragma diag_push
#pragma diag_suppress 169 /* Nothing we can do about the prototype mismatch. \
*/
ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read,
fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink,
fs_slfs_rename) == 0);
#pragma diag_pop
#endif
#endif
return ret;
}
#endif /* !defined(MG_FS_NO_VFS) */
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && (defined(MG_FS_SLFS) || \
defined(MG_FS_SPIFFS)) */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_socket.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if MG_NET_IF == MG_NET_IF_SIMPLELINK
#include <errno.h>
#include <stdio.h>
/* Amalgamated: #include "common/platform.h" */
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
int res;
struct in_addr *in = (struct in_addr *) src;
if (af != AF_INET) {
errno = ENOTSUP;
return NULL;
}
res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0),
SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2),
SL_IPV4_BYTE(in->s_addr, 3));
return res > 0 ? dst : NULL;
}
char *inet_ntoa(struct in_addr n) {
static char a[16];
return (char *) inet_ntop(AF_INET, &n, a, sizeof(a));
}
int inet_pton(int af, const char *src, void *dst) {
uint32_t a0, a1, a2, a3;
uint8_t *db = (uint8_t *) dst;
if (af != AF_INET) {
errno = ENOTSUP;
return 0;
}
if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) {
return 0;
}
*db = a3;
*(db + 1) = a2;
*(db + 2) = a1;
*(db + 3) = a0;
return 1;
}
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_mg_task.c"
#endif
#if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI)
/* Amalgamated: #include "mg_task.h" */
#include <oslib/osi.h>
enum mg_q_msg_type {
MG_Q_MSG_CB,
};
struct mg_q_msg {
enum mg_q_msg_type type;
void (*cb)(struct mg_mgr *mgr, void *arg);
void *arg;
};
static OsiMsgQ_t s_mg_q;
static void mg_task(void *arg);
bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) {
if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) {
return false;
}
if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size,
(void *) mg_init, priority, NULL) != OSI_OK) {
return false;
}
return true;
}
static void mg_task(void *arg) {
struct mg_mgr mgr;
mg_init_cb mg_init = (mg_init_cb) arg;
mg_mgr_init(&mgr, NULL);
mg_init(&mgr);
while (1) {
struct mg_q_msg msg;
mg_mgr_poll(&mgr, 1);
if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue;
switch (msg.type) {
case MG_Q_MSG_CB: {
msg.cb(&mgr, msg.arg);
}
}
}
}
void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) {
struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg};
osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT);
}
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) \
*/
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_net_if.h"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
/* Amalgamated: #include "mongoose/src/net_if.h" */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifndef MG_ENABLE_NET_IF_SIMPLELINK
#define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK
#endif
extern const struct mg_iface_vtable mg_simplelink_iface_vtable;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_net_if.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Amalgamated: #include "common/platforms/simplelink/sl_net_if.h" */
#if MG_ENABLE_NET_IF_SIMPLELINK
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/util.h" */
#define MG_TCP_RECV_BUFFER_SIZE 1024
#define MG_UDP_RECV_BUFFER_SIZE 1500
static sock_t mg_open_listening_socket(struct mg_connection *nc,
union socket_address *sa, int type,
int proto);
static void mg_set_non_blocking_mode(sock_t sock) {
SlSockNonblocking_t opt;
#if SL_MAJOR_VERSION_NUM < 2
opt.NonblockingEnabled = 1;
#else
opt.NonBlockingEnabled = 1;
#endif
sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt));
}
static int mg_is_error(int n) {
return (n < 0 && n != SL_ERROR_BSD_EALREADY && n != SL_ERROR_BSD_EAGAIN);
}
static void mg_sl_if_connect_tcp(struct mg_connection *nc,
const union socket_address *sa) {
int proto = 0;
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
#endif
sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto);
if (sock < 0) {
nc->err = sock;
goto out;
}
mg_sock_set(nc, sock);
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
nc->err = sl_set_ssl_opts(sock, nc);
if (nc->err != 0) goto out;
#endif
nc->err = sl_Connect(sock, &sa->sa, sizeof(sa->sin));
out:
DBG(("%p to %s:%d sock %d %d err %d", nc, inet_ntoa(sa->sin.sin_addr),
ntohs(sa->sin.sin_port), nc->sock, proto, nc->err));
}
static void mg_sl_if_connect_udp(struct mg_connection *nc) {
sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
nc->err = sock;
return;
}
mg_sock_set(nc, sock);
nc->err = 0;
}
static int mg_sl_if_listen_tcp(struct mg_connection *nc,
union socket_address *sa) {
int proto = 0;
if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
sock_t sock = mg_open_listening_socket(nc, sa, SOCK_STREAM, proto);
if (sock < 0) return sock;
mg_sock_set(nc, sock);
return 0;
}
static int mg_sl_if_listen_udp(struct mg_connection *nc,
union socket_address *sa) {
sock_t sock = mg_open_listening_socket(nc, sa, SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET) return (errno ? errno : 1);
mg_sock_set(nc, sock);
return 0;
}
static int mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf,
size_t len) {
int n = (int) sl_Send(nc->sock, buf, len, 0);
if (n < 0 && !mg_is_error(n)) n = 0;
return n;
}
static int mg_sl_if_udp_send(struct mg_connection *nc, const void *buf,
size_t len) {
int n = sl_SendTo(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
if (n < 0 && !mg_is_error(n)) n = 0;
return n;
}
static int mg_sl_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len) {
int n = sl_Recv(nc->sock, buf, len, 0);
if (n == 0) {
/* Orderly shutdown of the socket, try flushing output. */
nc->flags |= MG_F_SEND_AND_CLOSE;
} else if (n < 0 && !mg_is_error(n)) {
n = 0;
}
return n;
}
static int mg_sl_if_udp_recv(struct mg_connection *nc, void *buf, size_t len,
union socket_address *sa, size_t *sa_len) {
SlSocklen_t sa_len_t = *sa_len;
int n = sl_RecvFrom(nc->sock, buf, MG_UDP_RECV_BUFFER_SIZE, 0,
(SlSockAddr_t *) sa, &sa_len_t);
*sa_len = sa_len_t;
if (n < 0 && !mg_is_error(n)) n = 0;
return n;
}
static int mg_sl_if_create_conn(struct mg_connection *nc) {
(void) nc;
return 1;
}
void mg_sl_if_destroy_conn(struct mg_connection *nc) {
if (nc->sock == INVALID_SOCKET) return;
/* For UDP, only close outgoing sockets or listeners. */
if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
sl_Close(nc->sock);
}
nc->sock = INVALID_SOCKET;
}
static int mg_accept_conn(struct mg_connection *lc) {
struct mg_connection *nc;
union socket_address sa;
socklen_t sa_len = sizeof(sa);
sock_t sock = sl_Accept(lc->sock, &sa.sa, &sa_len);
if (sock < 0) {
DBG(("%p: failed to accept: %d", lc, sock));
return 0;
}
nc = mg_if_accept_new_conn(lc);
if (nc == NULL) {
sl_Close(sock);
return 0;
}
DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
ntohs(sa.sin.sin_port)));
mg_sock_set(nc, sock);
mg_if_accept_tcp_cb(nc, &sa, sa_len);
return 1;
}
/* 'sa' must be an initialized address to bind to */
static sock_t mg_open_listening_socket(struct mg_connection *nc,
union socket_address *sa, int type,
int proto) {
int r;
socklen_t sa_len =
(sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
sock_t sock = sl_Socket(sa->sa.sa_family, type, proto);
if (sock < 0) return sock;
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
if ((r = sl_set_ssl_opts(sock, nc)) < 0) goto clean;
#endif
if ((r = sl_Bind(sock, &sa->sa, sa_len)) < 0) goto clean;
if (type != SOCK_DGRAM) {
if ((r = sl_Listen(sock, SOMAXCONN)) < 0) goto clean;
}
mg_set_non_blocking_mode(sock);
clean:
if (r < 0) {
sl_Close(sock);
sock = r;
}
return sock;
}
#define _MG_F_FD_CAN_READ 1
#define _MG_F_FD_CAN_WRITE 1 << 1
#define _MG_F_FD_ERROR 1 << 2
void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock,
fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
if (!mg_if_poll(nc, now)) return;
if (nc->flags & MG_F_CONNECTING) {
if ((nc->flags & MG_F_UDP) || nc->err != SL_ERROR_BSD_EALREADY) {
mg_if_connect_cb(nc, nc->err);
} else {
/* In SimpleLink, to get status of non-blocking connect() we need to wait
* until socket is writable and repeat the call to sl_Connect again,
* which will now return the real status. */
if (fd_flags & _MG_F_FD_CAN_WRITE) {
nc->err = sl_Connect(nc->sock, &nc->sa.sa, sizeof(nc->sa.sin));
DBG(("%p conn res=%d", nc, nc->err));
if (nc->err == SL_ERROR_BSD_ESECSNOVERIFY ||
/* TODO(rojer): Provide API to set the date for verification. */
nc->err == SL_ERROR_BSD_ESECDATEERROR
#if SL_MAJOR_VERSION_NUM >= 2
/* Per SWRU455, this error does not mean verification failed,
* it only means that the cert used is not present in the trusted
* root CA catalog. Which is perfectly fine. */
||
nc->err == SL_ERROR_BSD_ESECUNKNOWNROOTCA
#endif
) {
nc->err = 0;
}
mg_if_connect_cb(nc, nc->err);
}
}
/* Ignore read/write in further processing, we've handled it. */
fd_flags &= ~(_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE);
}
if (fd_flags & _MG_F_FD_CAN_READ) {
if (nc->flags & MG_F_UDP) {
mg_if_can_recv_cb(nc);
} else {
if (nc->flags & MG_F_LISTENING) {
mg_accept_conn(nc);
} else {
mg_if_can_recv_cb(nc);
}
}
}
if (fd_flags & _MG_F_FD_CAN_WRITE) {
mg_if_can_send_cb(nc);
}
DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
(int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
}
/* Associate a socket to a connection. */
void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock) {
mg_set_non_blocking_mode(sock);
nc->sock = sock;
DBG(("%p %d", nc, sock));
}
void mg_sl_if_init(struct mg_iface *iface) {
(void) iface;
DBG(("%p using sl_Select()", iface->mgr));
}
void mg_sl_if_free(struct mg_iface *iface) {
(void) iface;
}
void mg_sl_if_add_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_sl_if_remove_conn(struct mg_connection *nc) {
(void) nc;
}
time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms) {
struct mg_mgr *mgr = iface->mgr;
double now = mg_time();
double min_timer;
struct mg_connection *nc, *tmp;
struct SlTimeval_t tv;
SlFdSet_t read_set, write_set, err_set;
sock_t max_fd = INVALID_SOCKET;
int num_fds, num_ev = 0, num_timers = 0;
SL_SOCKET_FD_ZERO(&read_set);
SL_SOCKET_FD_ZERO(&write_set);
SL_SOCKET_FD_ZERO(&err_set);
/*
* Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
* e.g. timer-only "connections".
*/
min_timer = 0;
for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
tmp = nc->next;
if (nc->sock != INVALID_SOCKET) {
num_fds++;
if (!(nc->flags & MG_F_WANT_WRITE) &&
nc->recv_mbuf.len < nc->recv_mbuf_limit &&
(!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
SL_SOCKET_FD_SET(nc->sock, &read_set);
if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
}
if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
(nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
SL_SOCKET_FD_SET(nc->sock, &write_set);
SL_SOCKET_FD_SET(nc->sock, &err_set);
if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
}
}
if (nc->ev_timer_time > 0) {
if (num_timers == 0 || nc->ev_timer_time < min_timer) {
min_timer = nc->ev_timer_time;
}
num_timers++;
}
}
/*
* If there is a timer to be fired earlier than the requested timeout,
* adjust the timeout.
*/
if (num_timers > 0) {
double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
if (timer_timeout_ms < timeout_ms) {
timeout_ms = timer_timeout_ms;
}
}
if (timeout_ms < 0) timeout_ms = 0;
tv.tv_sec = timeout_ms / 1000;
tv.tv_usec = (timeout_ms % 1000) * 1000;
if (num_fds > 0) {
num_ev = sl_Select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
}
now = mg_time();
DBG(("sl_Select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev,
num_fds, timeout_ms));
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
int fd_flags = 0;
if (nc->sock != INVALID_SOCKET) {
if (num_ev > 0) {
fd_flags =
(SL_SOCKET_FD_ISSET(nc->sock, &read_set) &&
(!(nc->flags & MG_F_UDP) || nc->listener == NULL)
? _MG_F_FD_CAN_READ
: 0) |
(SL_SOCKET_FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE
: 0) |
(SL_SOCKET_FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
}
/* SimpleLink does not report UDP sockets as writable. */
if (nc->flags & MG_F_UDP && nc->send_mbuf.len > 0) {
fd_flags |= _MG_F_FD_CAN_WRITE;
}
}
tmp = nc->next;
mg_mgr_handle_conn(nc, fd_flags, now);
}
return now;
}
void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote,
union socket_address *sa) {
/* SimpleLink does not provide a way to get socket's peer address after
* accept or connect. Address should have been preserved in the connection,
* so we do our best here by using it. */
if (remote) memcpy(sa, &nc->sa, sizeof(*sa));
}
void sl_restart_cb(struct mg_mgr *mgr) {
/*
* SimpleLink has been restarted, meaning all sockets have been invalidated.
* We try our best - we'll restart the listeners, but for outgoing
* connections we have no option but to terminate.
*/
struct mg_connection *nc;
for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
if (nc->sock == INVALID_SOCKET) continue; /* Could be a timer */
if (nc->flags & MG_F_LISTENING) {
DBG(("restarting %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
ntohs(nc->sa.sin.sin_port)));
int res = (nc->flags & MG_F_UDP ? mg_sl_if_listen_udp(nc, &nc->sa)
: mg_sl_if_listen_tcp(nc, &nc->sa));
if (res == 0) continue;
/* Well, we tried and failed. Fall through to closing. */
}
nc->sock = INVALID_SOCKET;
DBG(("terminating %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
ntohs(nc->sa.sin.sin_port)));
/* TODO(rojer): Outgoing UDP? */
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
}
/* clang-format off */
#define MG_SL_IFACE_VTABLE \
{ \
mg_sl_if_init, \
mg_sl_if_free, \
mg_sl_if_add_conn, \
mg_sl_if_remove_conn, \
mg_sl_if_poll, \
mg_sl_if_listen_tcp, \
mg_sl_if_listen_udp, \
mg_sl_if_connect_tcp, \
mg_sl_if_connect_udp, \
mg_sl_if_tcp_send, \
mg_sl_if_udp_send, \
mg_sl_if_tcp_recv, \
mg_sl_if_udp_recv, \
mg_sl_if_create_conn, \
mg_sl_if_destroy_conn, \
mg_sl_if_sock_set, \
mg_sl_if_get_conn_addr, \
}
/* clang-format on */
const struct mg_iface_vtable mg_simplelink_iface_vtable = MG_SL_IFACE_VTABLE;
#if MG_NET_IF == MG_NET_IF_SIMPLELINK
const struct mg_iface_vtable mg_default_iface_vtable = MG_SL_IFACE_VTABLE;
#endif
#endif /* MG_ENABLE_NET_IF_SIMPLELINK */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_ssl_if.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
/* Amalgamated: #include "common/mg_mem.h" */
#ifndef MG_SSL_IF_SIMPLELINK_SLFS_PREFIX
#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "SL:"
#endif
#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN \
(sizeof(MG_SSL_IF_SIMPLELINK_SLFS_PREFIX) - 1)
struct mg_ssl_if_ctx {
char *ssl_cert;
char *ssl_key;
char *ssl_ca_cert;
char *ssl_server_name;
};
void mg_ssl_if_init() {
}
enum mg_ssl_if_result mg_ssl_if_conn_init(
struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
const char **err_msg) {
struct mg_ssl_if_ctx *ctx =
(struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
if (ctx == NULL) {
MG_SET_PTRPTR(err_msg, "Out of memory");
return MG_SSL_ERROR;
}
nc->ssl_if_data = ctx;
if (params->cert != NULL || params->key != NULL) {
if (params->cert != NULL && params->key != NULL) {
ctx->ssl_cert = strdup(params->cert);
ctx->ssl_key = strdup(params->key);
} else {
MG_SET_PTRPTR(err_msg, "Both cert and key are required.");
return MG_SSL_ERROR;
}
}
if (params->ca_cert != NULL && strcmp(params->ca_cert, "*") != 0) {
ctx->ssl_ca_cert = strdup(params->ca_cert);
}
/* TODO(rojer): cipher_suites. */
if (params->server_name != NULL) {
ctx->ssl_server_name = strdup(params->server_name);
}
return MG_SSL_OK;
}
enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
struct mg_connection *lc) {
/* SimpleLink does everything for us, nothing for us to do. */
(void) nc;
(void) lc;
return MG_SSL_OK;
}
enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
/* SimpleLink has already performed the handshake, nothing to do. */
return MG_SSL_OK;
}
int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) {
/* SimpelLink handles TLS, so this is just a pass-through. */
int n = nc->iface->vtable->tcp_recv(nc, buf, len);
if (n == 0) nc->flags |= MG_F_WANT_READ;
return n;
}
int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) {
/* SimpelLink handles TLS, so this is just a pass-through. */
return nc->iface->vtable->tcp_send(nc, buf, len);
}
void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
/* Nothing to do */
(void) nc;
}
void mg_ssl_if_conn_free(struct mg_connection *nc) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
if (ctx == NULL) return;
nc->ssl_if_data = NULL;
MG_FREE(ctx->ssl_cert);
MG_FREE(ctx->ssl_key);
MG_FREE(ctx->ssl_ca_cert);
MG_FREE(ctx->ssl_server_name);
memset(ctx, 0, sizeof(*ctx));
MG_FREE(ctx);
}
bool pem_to_der(const char *pem_file, const char *der_file) {
bool ret = false;
FILE *pf = NULL, *df = NULL;
bool writing = false;
pf = fopen(pem_file, "r");
if (pf == NULL) goto clean;
remove(der_file);
fs_slfs_set_file_size(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, 2048);
df = fopen(der_file, "w");
fs_slfs_unset_file_flags(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN);
if (df == NULL) goto clean;
while (1) {
char pem_buf[70];
char der_buf[48];
if (!fgets(pem_buf, sizeof(pem_buf), pf)) break;
if (writing) {
if (strstr(pem_buf, "-----END ") != NULL) {
ret = true;
break;
}
int l = 0;
while (!isspace((unsigned int) pem_buf[l])) l++;
int der_len = 0;
cs_base64_decode((const unsigned char *) pem_buf, sizeof(pem_buf),
der_buf, &der_len);
if (der_len <= 0) break;
if (fwrite(der_buf, 1, der_len, df) != der_len) break;
} else if (strstr(pem_buf, "-----BEGIN ") != NULL) {
writing = true;
}
}
clean:
if (pf != NULL) fclose(pf);
if (df != NULL) {
fclose(df);
if (!ret) remove(der_file);
}
return ret;
}
#if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS)
/* If the file's extension is .pem, convert it to DER format and put on SLFS. */
static char *sl_pem2der(const char *pem_file) {
const char *pem_ext = strstr(pem_file, ".pem");
if (pem_ext == NULL || *(pem_ext + 4) != '\0') {
return strdup(pem_file);
}
char *der_file = NULL;
/* DER file must be located on SLFS, add prefix. */
int l = mg_asprintf(&der_file, 0, MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "%.*s.der",
(int) (pem_ext - pem_file), pem_file);
if (der_file == NULL) return NULL;
bool result = false;
cs_stat_t st;
if (mg_stat(der_file, &st) != 0) {
result = pem_to_der(pem_file, der_file);
LOG(LL_DEBUG, ("%s -> %s = %d", pem_file, der_file, result));
} else {
/* File exists, assume it's already been converted. */
result = true;
}
if (result) {
/* Strip the SL: prefix we added since NWP does not expect it. */
memmove(der_file, der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN,
l - 2 /* including \0 */);
} else {
MG_FREE(der_file);
der_file = NULL;
}
return der_file;
}
#else
static char *sl_pem2der(const char *pem_file) {
return strdup(pem_file);
}
#endif
int sl_set_ssl_opts(int sock, struct mg_connection *nc) {
int err;
const struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
DBG(("%p ssl ctx: %p", nc, ctx));
if (ctx == NULL) return 0;
DBG(("%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"),
(ctx->ssl_key ? ctx->ssl_cert : "-"),
(ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"),
(ctx->ssl_server_name ? ctx->ssl_server_name : "-")));
if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) {
char *ssl_cert = sl_pem2der(ctx->ssl_cert), *ssl_key = NULL;
if (ssl_cert != NULL) {
err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert,
strlen(ssl_cert));
MG_FREE(ssl_cert);
LOG(LL_DEBUG, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err));
ssl_key = sl_pem2der(ctx->ssl_key);
if (ssl_key != NULL) {
err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key,
strlen(ssl_key));
MG_FREE(ssl_key);
LOG(LL_DEBUG, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err));
} else {
err = -1;
}
} else {
err = -1;
}
if (err != 0) return err;
}
if (ctx->ssl_ca_cert != NULL) {
if (ctx->ssl_ca_cert[0] != '\0') {
char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert);
if (ssl_ca_cert != NULL) {
err =
sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME,
ssl_ca_cert, strlen(ssl_ca_cert));
LOG(LL_DEBUG, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err));
} else {
err = -1;
}
MG_FREE(ssl_ca_cert);
if (err != 0) return err;
}
}
if (ctx->ssl_server_name != NULL) {
err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
SL_SO_SECURE_DOMAIN_NAME_VERIFICATION,
ctx->ssl_server_name, strlen(ctx->ssl_server_name));
DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err));
/* Domain name verificationw as added in a NWP service pack, older
* versions return SL_ERROR_BSD_ENOPROTOOPT. There isn't much we can do
* about it,
* so we ignore the error. */
if (err != 0 && err != SL_ERROR_BSD_ENOPROTOOPT) return err;
}
return 0;
}
#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/lwip/mg_lwip_net_if.h"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
#define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
#ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
#define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
#endif
#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
#include <stdint.h>
extern const struct mg_iface_vtable mg_lwip_iface_vtable;
struct mg_lwip_conn_state {
struct mg_connection *nc;
struct mg_connection *lc;
union {
struct tcp_pcb *tcp;
struct udp_pcb *udp;
} pcb;
err_t err;
size_t num_sent; /* Number of acknowledged bytes to be reported to the core */
struct pbuf *rx_chain; /* Chain of incoming data segments. */
size_t rx_offset; /* Offset within the first pbuf (if partially consumed) */
/* Last SSL write size, for retries. */
int last_ssl_write_size;
/* Whether MG_SIG_RECV is already pending for this connection */
int recv_pending;
/* Whether the connection is about to close, just `rx_chain` needs to drain */
int draining_rx_chain;
};
enum mg_sig_type {
MG_SIG_CONNECT_RESULT = 1,
MG_SIG_RECV = 2,
MG_SIG_CLOSE_CONN = 3,
MG_SIG_TOMBSTONE = 4,
MG_SIG_ACCEPT = 5,
};
void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc);
/* To be implemented by the platform. */
void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr);
#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
#endif /* CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/lwip/mg_lwip_net_if.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
/* Amalgamated: #include "common/mg_mem.h" */
#include <lwip/init.h>
#include <lwip/pbuf.h>
#include <lwip/tcp.h>
#include <lwip/tcpip.h>
#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
#include <lwip/priv/tcp_priv.h> /* For tcp_seg */
#include <lwip/priv/tcpip_priv.h> /* For tcpip_api_call */
#else
#include <lwip/tcp_impl.h>
#endif
#include <lwip/udp.h>
/* Amalgamated: #include "common/cs_dbg.h" */
/*
* Newest versions of LWIP have ip_2_ip4, older have ipX_2_ip,
* even older have nothing.
*/
#ifndef ip_2_ip4
#ifdef ipX_2_ip
#define ip_2_ip4(addr) ipX_2_ip(addr)
#else
#define ip_2_ip4(addr) (addr)
#endif
#endif
/*
* Depending on whether Mongoose is compiled with ipv6 support, use right
* lwip functions
*/
#if MG_ENABLE_IPV6
#define TCP_NEW tcp_new_ip6
#define TCP_BIND tcp_bind_ip6
#define UDP_BIND udp_bind_ip6
#define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x))
#define SET_ADDR(dst, src) \
memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \
sizeof((dst)->sin6.sin6_addr.s6_addr))
#else
#define TCP_NEW tcp_new
#define TCP_BIND tcp_bind
#define UDP_BIND udp_bind
#define IPADDR_NTOA ipaddr_ntoa
#define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = ip_2_ip4(src)->addr
#endif
#if !NO_SYS
#if LWIP_TCPIP_CORE_LOCKING
/* With locking tcpip_api_call is just a function call wrapped in lock/unlock,
* so we can get away with just casting. */
void mg_lwip_netif_run_on_tcpip(void (*fn)(void *), void *arg) {
tcpip_api_call((tcpip_api_call_fn) fn, (struct tcpip_api_call_data *) arg);
}
#else
static sys_sem_t s_tcpip_call_lock_sem = NULL;
static sys_sem_t s_tcpip_call_sync_sem = NULL;
struct mg_lwip_netif_tcpip_call_ctx {
void (*fn)(void *);
void *arg;
};
static void xxx_tcpip(void *arg) {
struct mg_lwip_netif_tcpip_call_ctx *ctx =
(struct mg_lwip_netif_tcpip_call_ctx *) arg;
ctx->fn(ctx->arg);
sys_sem_signal(&s_tcpip_call_sync_sem);
}
void mg_lwip_netif_run_on_tcpip(void (*fn)(void *), void *arg) {
struct mg_lwip_netif_tcpip_call_ctx ctx = {.fn = fn, .arg = arg};
sys_arch_sem_wait(&s_tcpip_call_lock_sem, 0);
tcpip_send_msg_wait_sem(xxx_tcpip, &ctx, &s_tcpip_call_sync_sem);
sys_sem_signal(&s_tcpip_call_lock_sem);
}
#endif
#else
#define mg_lwip_netif_run_on_tcpip(fn, arg) (fn)(arg)
#endif
void mg_lwip_if_init(struct mg_iface *iface);
void mg_lwip_if_free(struct mg_iface *iface);
void mg_lwip_if_add_conn(struct mg_connection *nc);
void mg_lwip_if_remove_conn(struct mg_connection *nc);
time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms);
// If compiling for Mongoose OS.
#ifdef MGOS
extern void mgos_lock();
extern void mgos_unlock();
#else
#define mgos_lock()
#define mgos_unlock()
#endif
static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p);
#if LWIP_TCP_KEEPALIVE
void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle,
int interval, int count) {
if (nc->sock == INVALID_SOCKET || nc->flags & MG_F_UDP) {
return;
}
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct tcp_pcb *tpcb = cs->pcb.tcp;
if (idle > 0 && interval > 0 && count > 0) {
tpcb->keep_idle = idle * 1000;
tpcb->keep_intvl = interval * 1000;
tpcb->keep_cnt = count;
tpcb->so_options |= SOF_KEEPALIVE;
} else {
tpcb->so_options &= ~SOF_KEEPALIVE;
}
}
#elif !defined(MG_NO_LWIP_TCP_KEEPALIVE)
#warning LWIP TCP keepalive is disabled. Please consider enabling it.
#endif /* LWIP_TCP_KEEPALIVE */
static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err) {
struct mg_connection *nc = (struct mg_connection *) arg;
DBG(("%p connect to %s:%u = %d", nc, IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)),
tpcb->remote_port, err));
if (nc == NULL) {
tcp_abort(tpcb);
return ERR_ARG;
}
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
cs->err = err;
#if LWIP_TCP_KEEPALIVE
if (err == 0) mg_lwip_set_keepalive_params(nc, 60, 10, 6);
#endif
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
return ERR_OK;
}
static void mg_lwip_tcp_error_cb(void *arg, err_t err) {
struct mg_connection *nc = (struct mg_connection *) arg;
DBG(("%p conn error %d", nc, err));
if (nc == NULL || (nc->flags & MG_F_CLOSE_IMMEDIATELY)) return;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
cs->pcb.tcp = NULL; /* Has already been deallocated */
if (nc->flags & MG_F_CONNECTING) {
cs->err = err;
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
} else {
mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
}
}
static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb,
struct pbuf *p, err_t err) {
struct mg_connection *nc = (struct mg_connection *) arg;
struct mg_lwip_conn_state *cs =
(nc ? (struct mg_lwip_conn_state *) nc->sock : NULL);
DBG(("%p %p %p %p %u %d", nc, cs, tpcb, p, (p != NULL ? p->tot_len : 0),
err));
if (p == NULL) {
if (nc != NULL && !(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
if (cs->rx_chain != NULL) {
/*
* rx_chain still contains non-consumed data, don't close the
* connection
*/
cs->draining_rx_chain = 1;
} else {
mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
}
} else {
/* Tombstoned connection, do nothing. */
}
return ERR_OK;
} else if (nc == NULL) {
tcp_abort(tpcb);
return ERR_ARG;
}
/*
* If we get a chain of more than one segment at once, we need to bump
* refcount on the subsequent bufs to make them independent.
*/
if (p->next != NULL) {
struct pbuf *q = p->next;
for (; q != NULL; q = q->next) pbuf_ref(q);
}
mgos_lock();
if (cs->rx_chain == NULL) {
cs->rx_offset = 0;
} else if (pbuf_clen(cs->rx_chain) >= 4) {
/* ESP SDK has a limited pool of 5 pbufs. We must not hog them all or RX
* will be completely blocked. We already have at least 4 in the chain,
* this one is the last, so we have to make a copy and release this one. */
struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
if (np != NULL) {
pbuf_copy(np, p);
pbuf_free(p);
p = np;
}
}
mg_lwip_recv_common(nc, p);
mgos_unlock();
(void) err;
return ERR_OK;
}
static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb,
u16_t num_sent) {
struct mg_connection *nc = (struct mg_connection *) arg;
DBG(("%p %p %u %p %p", nc, tpcb, num_sent, tpcb->unsent, tpcb->unacked));
if (nc == NULL) return ERR_OK;
if ((nc->flags & MG_F_SEND_AND_CLOSE) && !(nc->flags & MG_F_WANT_WRITE) &&
nc->send_mbuf.len == 0 && tpcb->unsent == NULL && tpcb->unacked == NULL) {
mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
}
if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) {
mg_lwip_mgr_schedule_poll(nc->mgr);
}
(void) num_sent;
return ERR_OK;
}
struct mg_lwip_if_connect_tcp_ctx {
struct mg_connection *nc;
const union socket_address *sa;
};
static void mg_lwip_if_connect_tcp_tcpip(void *arg) {
struct mg_lwip_if_connect_tcp_ctx *ctx =
(struct mg_lwip_if_connect_tcp_ctx *) arg;
struct mg_connection *nc = ctx->nc;
const union socket_address *sa = ctx->sa;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct tcp_pcb *tpcb = TCP_NEW();
cs->pcb.tcp = tpcb;
ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
u16_t port = ntohs(sa->sin.sin_port);
tcp_arg(tpcb, nc);
tcp_err(tpcb, mg_lwip_tcp_error_cb);
tcp_sent(tpcb, mg_lwip_tcp_sent_cb);
tcp_recv(tpcb, mg_lwip_tcp_recv_cb);
cs->err = TCP_BIND(tpcb, IP_ADDR_ANY, 0 /* any port */);
DBG(("%p tcp_bind = %d", nc, cs->err));
if (cs->err != ERR_OK) {
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
return;
}
cs->err = tcp_connect(tpcb, ip, port, mg_lwip_tcp_conn_cb);
DBG(("%p tcp_connect %p = %d", nc, tpcb, cs->err));
if (cs->err != ERR_OK) {
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
return;
}
}
void mg_lwip_if_connect_tcp(struct mg_connection *nc,
const union socket_address *sa) {
struct mg_lwip_if_connect_tcp_ctx ctx = {.nc = nc, .sa = sa};
mg_lwip_netif_run_on_tcpip(mg_lwip_if_connect_tcp_tcpip, &ctx);
}
/*
* Lwip included in the SDKs for nRF5x chips has different type for the
* callback of `udp_recv()`
*/
#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
const ip_addr_t *addr, u16_t port)
#else
static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
ip_addr_t *addr, u16_t port)
#endif
{
struct mg_connection *nc = (struct mg_connection *) arg;
DBG(("%p %s:%u %p %u %u", nc, IPADDR_NTOA(addr), port, p, p->ref, p->len));
/* Put address in a separate pbuf and tack it onto the packet. */
struct pbuf *sap =
pbuf_alloc(PBUF_RAW, sizeof(union socket_address), PBUF_RAM);
if (sap == NULL) {
pbuf_free(p);
return;
}
union socket_address *sa = (union socket_address *) sap->payload;
#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
sa->sin.sin_addr.s_addr = ip_2_ip4(addr)->addr;
#else
sa->sin.sin_addr.s_addr = addr->addr;
#endif
sa->sin.sin_port = htons(port);
/* Logic in the recv handler requires that there be exactly one data pbuf. */
p = pbuf_coalesce(p, PBUF_RAW);
pbuf_chain(sap, p);
mgos_lock();
mg_lwip_recv_common(nc, sap);
mgos_unlock();
(void) pcb;
}
static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (cs->rx_chain == NULL) {
cs->rx_chain = p;
} else {
pbuf_chain(cs->rx_chain, p);
}
if (!cs->recv_pending) {
cs->recv_pending = 1;
mg_lwip_post_signal(MG_SIG_RECV, nc);
}
}
static int mg_lwip_if_udp_recv(struct mg_connection *nc, void *buf, size_t len,
union socket_address *sa, size_t *sa_len) {
/*
* For UDP, RX chain consists of interleaved address and packet bufs:
* Address pbuf followed by exactly one data pbuf (recv_cb took care of that).
*/
int res = 0;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (nc->sock == INVALID_SOCKET) return -1;
mgos_lock();
if (cs->rx_chain != NULL) {
struct pbuf *ap = cs->rx_chain;
struct pbuf *dp = ap->next;
cs->rx_chain = pbuf_dechain(dp);
res = MIN(dp->len, len);
pbuf_copy_partial(dp, buf, res, 0);
pbuf_free(dp);
pbuf_copy_partial(ap, sa, MIN(*sa_len, ap->len), 0);
pbuf_free(ap);
}
mgos_unlock();
return res;
}
static void mg_lwip_if_connect_udp_tcpip(void *arg) {
struct mg_connection *nc = (struct mg_connection *) arg;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct udp_pcb *upcb = udp_new();
cs->err = UDP_BIND(upcb, IP_ADDR_ANY, 0 /* any port */);
DBG(("%p udp_bind %p = %d", nc, upcb, cs->err));
if (cs->err == ERR_OK) {
udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
cs->pcb.udp = upcb;
} else {
udp_remove(upcb);
}
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
}
void mg_lwip_if_connect_udp(struct mg_connection *nc) {
mg_lwip_netif_run_on_tcpip(mg_lwip_if_connect_udp_tcpip, nc);
}
static void tcp_close_tcpip(void *arg) {
tcp_close((struct tcp_pcb *) arg);
}
void mg_lwip_handle_accept(struct mg_connection *nc) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (cs->pcb.tcp == NULL) return;
union socket_address sa;
struct tcp_pcb *tpcb = cs->pcb.tcp;
SET_ADDR(&sa, &tpcb->remote_ip);
sa.sin.sin_port = htons(tpcb->remote_port);
mg_if_accept_tcp_cb(nc, &sa, sizeof(sa.sin));
}
static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err) {
struct mg_connection *lc = (struct mg_connection *) arg, *nc;
struct mg_lwip_conn_state *lcs, *cs;
struct tcp_pcb_listen *lpcb;
LOG(LL_DEBUG,
("%p conn %p from %s:%u", lc, newtpcb,
IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port));
if (lc == NULL) {
tcp_abort(newtpcb);
return ERR_ABRT;
}
lcs = (struct mg_lwip_conn_state *) lc->sock;
lpcb = (struct tcp_pcb_listen *) lcs->pcb.tcp;
#if TCP_LISTEN_BACKLOG
tcp_accepted(lpcb);
#endif
nc = mg_if_accept_new_conn(lc);
if (nc == NULL) {
tcp_abort(newtpcb);
return ERR_ABRT;
}
cs = (struct mg_lwip_conn_state *) nc->sock;
cs->lc = lc;
cs->pcb.tcp = newtpcb;
/* We need to set up callbacks before returning because data may start
* arriving immediately. */
tcp_arg(newtpcb, nc);
tcp_err(newtpcb, mg_lwip_tcp_error_cb);
tcp_sent(newtpcb, mg_lwip_tcp_sent_cb);
tcp_recv(newtpcb, mg_lwip_tcp_recv_cb);
#if LWIP_TCP_KEEPALIVE
mg_lwip_set_keepalive_params(nc, 60, 10, 6);
#endif
mg_lwip_post_signal(MG_SIG_ACCEPT, nc);
(void) err;
(void) lpcb;
return ERR_OK;
}
struct mg_lwip_if_listen_ctx {
struct mg_connection *nc;
union socket_address *sa;
int ret;
};
static void mg_lwip_if_listen_tcp_tcpip(void *arg) {
struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg;
struct mg_connection *nc = ctx->nc;
union socket_address *sa = ctx->sa;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct tcp_pcb *tpcb = TCP_NEW();
ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
u16_t port = ntohs(sa->sin.sin_port);
cs->err = TCP_BIND(tpcb, ip, port);
DBG(("%p tcp_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
if (cs->err != ERR_OK) {
tcp_close(tpcb);
ctx->ret = -1;
return;
}
tcp_arg(tpcb, nc);
tpcb = tcp_listen(tpcb);
cs->pcb.tcp = tpcb;
tcp_accept(tpcb, mg_lwip_accept_cb);
ctx->ret = 0;
}
int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa};
mg_lwip_netif_run_on_tcpip(mg_lwip_if_listen_tcp_tcpip, &ctx);
return ctx.ret;
}
static void mg_lwip_if_listen_udp_tcpip(void *arg) {
struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg;
struct mg_connection *nc = ctx->nc;
union socket_address *sa = ctx->sa;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct udp_pcb *upcb = udp_new();
ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
u16_t port = ntohs(sa->sin.sin_port);
cs->err = UDP_BIND(upcb, ip, port);
DBG(("%p udb_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
if (cs->err != ERR_OK) {
udp_remove(upcb);
ctx->ret = -1;
} else {
udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
cs->pcb.udp = upcb;
ctx->ret = 0;
}
}
int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa};
mg_lwip_netif_run_on_tcpip(mg_lwip_if_listen_udp_tcpip, &ctx);
return ctx.ret;
}
struct mg_lwip_tcp_write_ctx {
struct mg_connection *nc;
const void *data;
uint16_t len;
int ret;
};
static void tcp_output_tcpip(void *arg) {
tcp_output((struct tcp_pcb *) arg);
}
static void mg_lwip_tcp_write_tcpip(void *arg) {
struct mg_lwip_tcp_write_ctx *ctx = (struct mg_lwip_tcp_write_ctx *) arg;
struct mg_connection *nc = ctx->nc;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct tcp_pcb *tpcb = cs->pcb.tcp;
size_t len = MIN(tpcb->mss, MIN(ctx->len, tpcb->snd_buf));
size_t unsent, unacked;
if (len == 0) {
DBG(("%p no buf avail %u %u %p %p", tpcb, tpcb->snd_buf, tpcb->snd_queuelen,
tpcb->unsent, tpcb->unacked));
mg_lwip_netif_run_on_tcpip(tcp_output_tcpip, tpcb);
ctx->ret = 0;
return;
}
unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
/*
* On ESP8266 we only allow one TCP segment in flight at any given time.
* This may increase latency and reduce efficiency of tcp windowing,
* but memory is scarce and precious on that platform so we do this to
* reduce footprint.
*/
#if CS_PLATFORM == CS_P_ESP8266
if (unacked > 0) {
ctx->ret = 0;
return;
}
len = MIN(len, (TCP_MSS - unsent));
#endif
cs->err = tcp_write(tpcb, ctx->data, len, TCP_WRITE_FLAG_COPY);
unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
DBG(("%p tcp_write %u = %d, %u %u", tpcb, len, cs->err, unsent, unacked));
if (cs->err != ERR_OK) {
/*
* We ignore ERR_MEM because memory will be freed up when the data is sent
* and we'll retry.
*/
ctx->ret = (cs->err == ERR_MEM ? 0 : -1);
return;
}
ctx->ret = len;
(void) unsent;
(void) unacked;
}
int mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
struct mg_lwip_tcp_write_ctx ctx = {.nc = nc, .data = buf, .len = len};
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (nc->sock == INVALID_SOCKET) return -1;
struct tcp_pcb *tpcb = cs->pcb.tcp;
if (tpcb == NULL) return -1;
if (tpcb->snd_buf <= 0) return 0;
mg_lwip_netif_run_on_tcpip(mg_lwip_tcp_write_tcpip, &ctx);
return ctx.ret;
}
struct udp_sendto_ctx {
struct udp_pcb *upcb;
struct pbuf *p;
ip_addr_t *ip;
uint16_t port;
int ret;
};
static void udp_sendto_tcpip(void *arg) {
struct udp_sendto_ctx *ctx = (struct udp_sendto_ctx *) arg;
ctx->ret = udp_sendto(ctx->upcb, ctx->p, ctx->ip, ctx->port);
}
static int mg_lwip_if_udp_send(struct mg_connection *nc, const void *data,
size_t len) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (nc->sock == INVALID_SOCKET || cs->pcb.udp == NULL) return -1;
struct udp_pcb *upcb = cs->pcb.udp;
struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
#if defined(LWIP_IPV4) && LWIP_IPV4 && defined(LWIP_IPV6) && LWIP_IPV6
ip_addr_t ip = {.u_addr.ip4.addr = nc->sa.sin.sin_addr.s_addr, .type = 0};
#else
ip_addr_t ip = {.addr = nc->sa.sin.sin_addr.s_addr};
#endif
u16_t port = ntohs(nc->sa.sin.sin_port);
if (p == NULL) return 0;
memcpy(p->payload, data, len);
struct udp_sendto_ctx ctx = {.upcb = upcb, .p = p, .ip = &ip, .port = port};
mg_lwip_netif_run_on_tcpip(udp_sendto_tcpip, &ctx);
cs->err = ctx.ret;
pbuf_free(p);
return (cs->err == ERR_OK ? (int) len : -2);
}
static int mg_lwip_if_can_send(struct mg_connection *nc,
struct mg_lwip_conn_state *cs) {
int can_send = 0;
if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) {
/* We have stuff to send, but can we? */
if (nc->flags & MG_F_UDP) {
/* UDP is always ready for sending. */
can_send = (cs->pcb.udp != NULL);
} else {
can_send = (cs->pcb.tcp != NULL && cs->pcb.tcp->snd_buf > 0);
/* See comment above. */
#if CS_PLATFORM == CS_P_ESP8266
if (cs->pcb.tcp->unacked != NULL) can_send = 0;
#endif
}
}
return can_send;
}
struct tcp_recved_ctx {
struct tcp_pcb *tpcb;
size_t len;
};
void tcp_recved_tcpip(void *arg) {
struct tcp_recved_ctx *ctx = (struct tcp_recved_ctx *) arg;
if (ctx->tpcb != NULL) tcp_recved(ctx->tpcb, ctx->len);
}
static int mg_lwip_if_tcp_recv(struct mg_connection *nc, void *buf,
size_t len) {
int res = 0;
char *bufp = buf;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (nc->sock == INVALID_SOCKET) return -1;
mgos_lock();
while (cs->rx_chain != NULL && len > 0) {
struct pbuf *seg = cs->rx_chain;
size_t seg_len = (seg->len - cs->rx_offset);
size_t copy_len = MIN(len, seg_len);
pbuf_copy_partial(seg, bufp, copy_len, cs->rx_offset);
len -= copy_len;
res += copy_len;
bufp += copy_len;
cs->rx_offset += copy_len;
if (cs->rx_offset == cs->rx_chain->len) {
cs->rx_chain = pbuf_dechain(cs->rx_chain);
pbuf_free(seg);
cs->rx_offset = 0;
}
}
mgos_unlock();
if (res > 0) {
struct tcp_recved_ctx ctx = {.tpcb = cs->pcb.tcp, .len = res};
mg_lwip_netif_run_on_tcpip(tcp_recved_tcpip, &ctx);
}
return res;
}
int mg_lwip_if_create_conn(struct mg_connection *nc) {
struct mg_lwip_conn_state *cs =
(struct mg_lwip_conn_state *) MG_CALLOC(1, sizeof(*cs));
if (cs == NULL) return 0;
cs->nc = nc;
nc->sock = (intptr_t) cs;
return 1;
}
static void udp_remove_tcpip(void *arg) {
udp_remove((struct udp_pcb *) arg);
}
void mg_lwip_if_destroy_conn(struct mg_connection *nc) {
if (nc->sock == INVALID_SOCKET) return;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (!(nc->flags & MG_F_UDP)) {
struct tcp_pcb *tpcb = cs->pcb.tcp;
if (tpcb != NULL) {
tcp_arg(tpcb, NULL);
DBG(("%p tcp_close %p", nc, tpcb));
tcp_arg(tpcb, NULL);
mg_lwip_netif_run_on_tcpip(tcp_close_tcpip, tpcb);
}
while (cs->rx_chain != NULL) {
struct pbuf *seg = cs->rx_chain;
cs->rx_chain = pbuf_dechain(cs->rx_chain);
pbuf_free(seg);
}
memset(cs, 0, sizeof(*cs));
MG_FREE(cs);
} else if (nc->listener == NULL) {
/* Only close outgoing UDP pcb or listeners. */
struct udp_pcb *upcb = cs->pcb.udp;
if (upcb != NULL) {
DBG(("%p udp_remove %p", nc, upcb));
mg_lwip_netif_run_on_tcpip(udp_remove_tcpip, upcb);
}
memset(cs, 0, sizeof(*cs));
MG_FREE(cs);
}
nc->sock = INVALID_SOCKET;
}
void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote,
union socket_address *sa) {
memset(sa, 0, sizeof(*sa));
if (nc == NULL || nc->sock == INVALID_SOCKET) return;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (nc->flags & MG_F_UDP) {
struct udp_pcb *upcb = cs->pcb.udp;
if (remote) {
memcpy(sa, &nc->sa, sizeof(*sa));
} else if (upcb != NULL) {
sa->sin.sin_port = htons(upcb->local_port);
SET_ADDR(sa, &upcb->local_ip);
}
} else {
struct tcp_pcb *tpcb = cs->pcb.tcp;
if (remote) {
memcpy(sa, &nc->sa, sizeof(*sa));
} else if (tpcb != NULL) {
sa->sin.sin_port = htons(tpcb->local_port);
SET_ADDR(sa, &tpcb->local_ip);
}
}
}
void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock) {
nc->sock = sock;
}
/* clang-format off */
#define MG_LWIP_IFACE_VTABLE \
{ \
mg_lwip_if_init, \
mg_lwip_if_free, \
mg_lwip_if_add_conn, \
mg_lwip_if_remove_conn, \
mg_lwip_if_poll, \
mg_lwip_if_listen_tcp, \
mg_lwip_if_listen_udp, \
mg_lwip_if_connect_tcp, \
mg_lwip_if_connect_udp, \
mg_lwip_if_tcp_send, \
mg_lwip_if_udp_send, \
mg_lwip_if_tcp_recv, \
mg_lwip_if_udp_recv, \
mg_lwip_if_create_conn, \
mg_lwip_if_destroy_conn, \
mg_lwip_if_sock_set, \
mg_lwip_if_get_conn_addr, \
}
/* clang-format on */
const struct mg_iface_vtable mg_lwip_iface_vtable = MG_LWIP_IFACE_VTABLE;
#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
const struct mg_iface_vtable mg_default_iface_vtable = MG_LWIP_IFACE_VTABLE;
#endif
#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/lwip/mg_lwip_ev_mgr.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
#ifndef MG_SIG_QUEUE_LEN
#define MG_SIG_QUEUE_LEN 32
#endif
struct mg_ev_mgr_lwip_signal {
int sig;
struct mg_connection *nc;
};
struct mg_ev_mgr_lwip_data {
struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN];
int sig_queue_len;
int start_index;
};
void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc) {
struct mg_ev_mgr_lwip_data *md =
(struct mg_ev_mgr_lwip_data *) nc->iface->data;
mgos_lock();
if (md->sig_queue_len >= MG_SIG_QUEUE_LEN) {
mgos_unlock();
return;
}
int end_index = (md->start_index + md->sig_queue_len) % MG_SIG_QUEUE_LEN;
md->sig_queue[end_index].sig = sig;
md->sig_queue[end_index].nc = nc;
md->sig_queue_len++;
mg_lwip_mgr_schedule_poll(nc->mgr);
mgos_unlock();
}
void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr) {
struct mg_ev_mgr_lwip_data *md =
(struct mg_ev_mgr_lwip_data *) mgr->ifaces[MG_MAIN_IFACE]->data;
while (md->sig_queue_len > 0) {
mgos_lock();
int i = md->start_index;
int sig = md->sig_queue[i].sig;
struct mg_connection *nc = md->sig_queue[i].nc;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
md->start_index = (i + 1) % MG_SIG_QUEUE_LEN;
md->sig_queue_len--;
mgos_unlock();
if (nc->iface == NULL || nc->mgr == NULL) continue;
switch (sig) {
case MG_SIG_CONNECT_RESULT: {
mg_if_connect_cb(nc, cs->err);
break;
}
case MG_SIG_CLOSE_CONN: {
mg_close_conn(nc);
break;
}
case MG_SIG_RECV: {
cs->recv_pending = 0;
mg_if_can_recv_cb(nc);
mbuf_trim(&nc->recv_mbuf);
break;
}
case MG_SIG_TOMBSTONE: {
break;
}
case MG_SIG_ACCEPT: {
mg_lwip_handle_accept(nc);
break;
}
}
}
}
void mg_lwip_if_init(struct mg_iface *iface) {
LOG(LL_INFO, ("Mongoose %s, LwIP %u.%u.%u", MG_VERSION, LWIP_VERSION_MAJOR,
LWIP_VERSION_MINOR, LWIP_VERSION_REVISION));
iface->data = MG_CALLOC(1, sizeof(struct mg_ev_mgr_lwip_data));
#if !NO_SYS && !LWIP_TCPIP_CORE_LOCKING
sys_sem_new(&s_tcpip_call_lock_sem, 1);
sys_sem_new(&s_tcpip_call_sync_sem, 0);
#endif
}
void mg_lwip_if_free(struct mg_iface *iface) {
MG_FREE(iface->data);
iface->data = NULL;
}
void mg_lwip_if_add_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_lwip_if_remove_conn(struct mg_connection *nc) {
struct mg_ev_mgr_lwip_data *md =
(struct mg_ev_mgr_lwip_data *) nc->iface->data;
/* Walk the queue and null-out further signals for this conn. */
for (int i = 0; i < MG_SIG_QUEUE_LEN; i++) {
if (md->sig_queue[i].nc == nc) {
md->sig_queue[i].sig = MG_SIG_TOMBSTONE;
}
}
}
time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms) {
struct mg_mgr *mgr = iface->mgr;
int n = 0;
double now = mg_time();
struct mg_connection *nc, *tmp;
double min_timer = 0;
int num_timers = 0;
#if 0
DBG(("begin poll @%u", (unsigned int) (now * 1000)));
#endif
mg_ev_mgr_lwip_process_signals(mgr);
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
tmp = nc->next;
n++;
if (!mg_if_poll(nc, now)) continue;
if (nc->sock != INVALID_SOCKET &&
!(nc->flags & (MG_F_UDP | MG_F_LISTENING)) && cs->pcb.tcp != NULL &&
cs->pcb.tcp->unsent != NULL) {
mg_lwip_netif_run_on_tcpip(tcp_output_tcpip, cs->pcb.tcp);
}
if (nc->ev_timer_time > 0) {
if (num_timers == 0 || nc->ev_timer_time < min_timer) {
min_timer = nc->ev_timer_time;
}
num_timers++;
}
if (nc->sock != INVALID_SOCKET) {
if (mg_lwip_if_can_send(nc, cs)) {
mg_if_can_send_cb(nc);
mbuf_trim(&nc->send_mbuf);
}
if (cs->rx_chain != NULL) {
mg_if_can_recv_cb(nc);
} else if (cs->draining_rx_chain) {
/*
* If the connection is about to close, and rx_chain is finally empty,
* send the MG_SIG_CLOSE_CONN signal
*/
mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
}
}
}
#if 0
DBG(("end poll @%u, %d conns, %d timers (min %u), next in %d ms",
(unsigned int) (now * 1000), n, num_timers,
(unsigned int) (min_timer * 1000), timeout_ms));
#endif
(void) timeout_ms;
return now;
}
#endif /* MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/wince/wince_libc.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef WINCE
const char *strerror(int err) {
/*
* TODO(alashkin): there is no strerror on WinCE;
* look for similar wce_xxxx function
*/
static char buf[10];
snprintf(buf, sizeof(buf), "%d", err);
return buf;
}
int open(const char *filename, int oflag, int pmode) {
/*
* TODO(alashkin): mg_open function is not used in mongoose
* but exists in documentation as utility function
* Shall we delete it at all or implement for WinCE as well?
*/
DebugBreak();
return 0; /* for compiler */
}
int _wstati64(const wchar_t *path, cs_stat_t *st) {
DWORD fa = GetFileAttributesW(path);
if (fa == INVALID_FILE_ATTRIBUTES) {
return -1;
}
memset(st, 0, sizeof(*st));
if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) {
HANDLE h;
FILETIME ftime;
st->st_mode |= _S_IFREG;
h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE) {
return -1;
}
st->st_size = GetFileSize(h, NULL);
GetFileTime(h, NULL, NULL, &ftime);
st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime +
((uint64_t) ftime.dwHighDateTime << 32)) /
10000000.0) -
11644473600);
CloseHandle(h);
} else {
st->st_mode |= _S_IFDIR;
}
return 0;
}
/* Windows CE doesn't have neither gmtime nor strftime */
static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
FILETIME ft;
SYSTEMTIME systime;
if (t != NULL) {
uint64_t filetime = (*t + 11644473600) * 10000000;
ft.dwLowDateTime = filetime & 0xFFFFFFFF;
ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32;
FileTimeToSystemTime(&ft, &systime);
} else {
GetSystemTime(&systime);
}
/* There is no PRIu16 in WinCE SDK */
snprintf(buf, buf_len, "%d.%d.%d %d:%d:%d GMT", (int) systime.wYear,
(int) systime.wMonth, (int) systime.wDay, (int) systime.wHour,
(int) systime.wMinute, (int) systime.wSecond);
}
#endif
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/pic32/pic32_net_if.h"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
#define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
/* Amalgamated: #include "mongoose/src/net_if.h" */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifndef MG_ENABLE_NET_IF_PIC32
#define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32
#endif
extern const struct mg_iface_vtable mg_pic32_iface_vtable;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/pic32/pic32_net_if.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if MG_ENABLE_NET_IF_PIC32
int mg_pic32_if_create_conn(struct mg_connection *nc) {
(void) nc;
return 1;
}
void mg_pic32_if_recved(struct mg_connection *nc, size_t len) {
(void) nc;
(void) len;
}
void mg_pic32_if_add_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_pic32_if_init(struct mg_iface *iface) {
(void) iface;
(void) mg_get_errno(); /* Shutup compiler */
}
void mg_pic32_if_free(struct mg_iface *iface) {
(void) iface;
}
void mg_pic32_if_remove_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_pic32_if_destroy_conn(struct mg_connection *nc) {
if (nc->sock == INVALID_SOCKET) return;
/* For UDP, only close outgoing sockets or listeners. */
if (!(nc->flags & MG_F_UDP)) {
/* Close TCP */
TCPIP_TCP_Close((TCP_SOCKET) nc->sock);
} else if (nc->listener == NULL) {
/* Only close outgoing UDP or listeners. */
TCPIP_UDP_Close((UDP_SOCKET) nc->sock);
}
nc->sock = INVALID_SOCKET;
}
int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
nc->sock = TCPIP_UDP_ServerOpen(
sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
: IP_ADDRESS_TYPE_IPV6,
ntohs(sa->sin.sin_port),
sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
if (nc->sock == INVALID_SOCKET) {
return -1;
}
return 0;
}
void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf,
size_t len) {
mbuf_append(&nc->send_mbuf, buf, len);
}
void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf,
size_t len) {
mbuf_append(&nc->send_mbuf, buf, len);
}
int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
nc->sock = TCPIP_TCP_ServerOpen(
sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
: IP_ADDRESS_TYPE_IPV6,
ntohs(sa->sin.sin_port),
sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
memcpy(&nc->sa, sa, sizeof(*sa));
if (nc->sock == INVALID_SOCKET) {
return -1;
}
return 0;
}
static int mg_accept_conn(struct mg_connection *lc) {
struct mg_connection *nc;
TCP_SOCKET_INFO si;
union socket_address sa;
nc = mg_if_accept_new_conn(lc);
if (nc == NULL) {
return 0;
}
nc->sock = lc->sock;
nc->flags &= ~MG_F_LISTENING;
if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->sock, &si)) {
return 0;
}
if (si.addressType == IP_ADDRESS_TYPE_IPV4) {
sa.sin.sin_family = AF_INET;
sa.sin.sin_port = htons(si.remotePort);
sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val;
} else {
/* TODO(alashkin): do something with _potential_ IPv6 */
memset(&sa, 0, sizeof(sa));
}
mg_if_accept_tcp_cb(nc, (union socket_address *) &sa, sizeof(sa));
return mg_pic32_if_listen_tcp(lc, &lc->sa) >= 0;
}
char *inet_ntoa(struct in_addr in) {
static char addr[17];
snprintf(addr, sizeof(addr), "%d.%d.%d.%d", (int) in.S_un.S_un_b.s_b1,
(int) in.S_un.S_un_b.s_b2, (int) in.S_un.S_un_b.s_b3,
(int) in.S_un.S_un_b.s_b4);
return addr;
}
static void mg_handle_send(struct mg_connection *nc) {
uint16_t bytes_written = 0;
if (nc->flags & MG_F_UDP) {
if (!TCPIP_UDP_RemoteBind(
(UDP_SOCKET) nc->sock,
nc->sa.sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
: IP_ADDRESS_TYPE_IPV6,
ntohs(nc->sa.sin.sin_port), (IP_MULTI_ADDRESS *) &nc->sa.sin)) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return;
}
bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->sock, 0);
if (bytes_written >= nc->send_mbuf.len) {
if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->sock,
(uint8_t *) nc->send_mbuf.buf,
nc->send_mbuf.len) != nc->send_mbuf.len) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
bytes_written = 0;
}
}
} else {
bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->sock);
if (bytes_written != 0) {
if (bytes_written > nc->send_mbuf.len) {
bytes_written = nc->send_mbuf.len;
}
if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->sock,
(uint8_t *) nc->send_mbuf.buf,
bytes_written) != bytes_written) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
bytes_written = 0;
}
}
}
mg_if_sent_cb(nc, bytes_written);
}
static void mg_handle_recv(struct mg_connection *nc) {
uint16_t bytes_read = 0;
uint8_t *buf = NULL;
if (nc->flags & MG_F_UDP) {
bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->sock);
if (bytes_read != 0 &&
(nc->recv_mbuf_limit == -1 ||
nc->recv_mbuf.len + bytes_read < nc->recv_mbuf_limit)) {
buf = (uint8_t *) MG_MALLOC(bytes_read);
if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->sock, buf, bytes_read) !=
bytes_read) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
bytes_read = 0;
MG_FREE(buf);
}
}
} else {
bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->sock);
if (bytes_read != 0) {
if (nc->recv_mbuf_limit != -1 &&
nc->recv_mbuf_limit - nc->recv_mbuf.len > bytes_read) {
bytes_read = nc->recv_mbuf_limit - nc->recv_mbuf.len;
}
buf = (uint8_t *) MG_MALLOC(bytes_read);
if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->sock, buf, bytes_read) !=
bytes_read) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
MG_FREE(buf);
bytes_read = 0;
}
}
}
if (bytes_read != 0) {
mg_if_recv_tcp_cb(nc, buf, bytes_read, 1 /* own */);
}
}
time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms) {
struct mg_mgr *mgr = iface->mgr;
double now = mg_time();
struct mg_connection *nc, *tmp;
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
tmp = nc->next;
if (nc->flags & MG_F_CONNECTING) {
/* processing connections */
if (nc->flags & MG_F_UDP ||
TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
mg_if_connect_cb(nc, 0);
}
} else if (nc->flags & MG_F_LISTENING) {
if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
/* accept new connections */
mg_accept_conn(nc);
}
} else {
if (nc->send_mbuf.len != 0) {
mg_handle_send(nc);
}
if (nc->recv_mbuf_limit == -1 ||
nc->recv_mbuf.len < nc->recv_mbuf_limit) {
mg_handle_recv(nc);
}
}
}
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
tmp = nc->next;
if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
(nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
mg_close_conn(nc);
}
}
return now;
}
void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock) {
nc->sock = sock;
}
void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote,
union socket_address *sa) {
/* TODO(alaskin): not implemented yet */
}
void mg_pic32_if_connect_tcp(struct mg_connection *nc,
const union socket_address *sa) {
nc->sock = TCPIP_TCP_ClientOpen(
sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
: IP_ADDRESS_TYPE_IPV6,
ntohs(sa->sin.sin_port), (IP_MULTI_ADDRESS *) &sa->sin);
nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
}
void mg_pic32_if_connect_udp(struct mg_connection *nc) {
nc->sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL);
nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
}
/* clang-format off */
#define MG_PIC32_IFACE_VTABLE \
{ \
mg_pic32_if_init, \
mg_pic32_if_free, \
mg_pic32_if_add_conn, \
mg_pic32_if_remove_conn, \
mg_pic32_if_poll, \
mg_pic32_if_listen_tcp, \
mg_pic32_if_listen_udp, \
mg_pic32_if_connect_tcp, \
mg_pic32_if_connect_udp, \
mg_pic32_if_tcp_send, \
mg_pic32_if_udp_send, \
mg_pic32_if_recved, \
mg_pic32_if_create_conn, \
mg_pic32_if_destroy_conn, \
mg_pic32_if_sock_set, \
mg_pic32_if_get_conn_addr, \
}
/* clang-format on */
const struct mg_iface_vtable mg_pic32_iface_vtable = MG_PIC32_IFACE_VTABLE;
#if MG_NET_IF == MG_NET_IF_PIC32
const struct mg_iface_vtable mg_default_iface_vtable = MG_PIC32_IFACE_VTABLE;
#endif
#endif /* MG_ENABLE_NET_IF_PIC32 */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/windows/windows_direct.c"
#endif
/*
* Copyright (c) 2014-2018 Cesanta Software Limited
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef _WIN32
int rmdir(const char *dirname) {
return _rmdir(dirname);
}
unsigned int sleep(unsigned int seconds) {
Sleep(seconds * 1000);
return 0;
}
#endif /* _WIN32 */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_896_0 |
crossvul-cpp_data_bad_344_3 | /*
* card-tcos.c: Support for TCOS cards
*
* Copyright (C) 2011 Peter Koch <pk@opensc-project.org>
* Copyright (C) 2002 g10 Code GmbH
* Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static struct sc_atr_table tcos_atrs[] = {
/* Infineon SLE44 */
{ "3B:BA:13:00:81:31:86:5D:00:64:05:0A:02:01:31:80:90:00:8B", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66S */
{ "3B:BA:14:00:81:31:86:5D:00:64:05:14:02:02:31:80:90:00:91", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX320P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:60:02:03:31:80:90:00:66", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX322P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:7B:02:03:31:80:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Philips P5CT072 */
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:03:01:31:C0:73:F7:01:D0:00:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:04:0F:31:C0:73:F7:01:D0:00:90:00:74", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
/* Philips P5CT080 */
{ "3B:BF:B6:00:81:31:FE:5D:00:64:04:28:03:02:31:C0:73:F7:01:D0:00:90:00:67", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
static struct sc_card_operations tcos_ops;
static struct sc_card_driver tcos_drv = {
"TCOS 3.0",
"tcos",
&tcos_ops,
NULL, 0, NULL
};
static const struct sc_card_operations *iso_ops = NULL;
typedef struct tcos_data_st {
unsigned int pad_flags;
unsigned int next_sign;
} tcos_data;
static int tcos_finish(sc_card_t *card)
{
free(card->drv_data);
return 0;
}
static int tcos_match_card(sc_card_t *card)
{
int i;
i = _sc_match_atr(card, tcos_atrs, &card->type);
if (i < 0)
return 0;
return 1;
}
static int tcos_init(sc_card_t *card)
{
unsigned long flags;
tcos_data *data = malloc(sizeof(tcos_data));
if (!data) return SC_ERROR_OUT_OF_MEMORY;
card->name = "TCOS";
card->drv_data = (void *)data;
card->cla = 0x00;
flags = SC_ALGORITHM_RSA_RAW;
flags |= SC_ALGORITHM_RSA_PAD_PKCS1;
flags |= SC_ALGORITHM_RSA_HASH_NONE;
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 768, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
if (card->type == SC_CARD_TYPE_TCOS_V3) {
card->caps |= SC_CARD_CAP_APDU_EXT;
_sc_card_add_rsa_alg(card, 1280, flags, 0);
_sc_card_add_rsa_alg(card, 1536, flags, 0);
_sc_card_add_rsa_alg(card, 1792, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
return 0;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static int tcos_construct_fci(const sc_file_t *file,
u8 *out, size_t *outlen)
{
u8 *p = out;
u8 buf[64];
size_t n;
/* FIXME: possible buffer overflow */
*p++ = 0x6F; /* FCI */
p++;
/* File size */
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x81, buf, 2, p, 16, &p);
/* File descriptor */
n = 0;
buf[n] = file->shareable ? 0x40 : 0;
switch (file->type) {
case SC_FILE_TYPE_WORKING_EF:
break;
case SC_FILE_TYPE_DF:
buf[0] |= 0x38;
break;
default:
return SC_ERROR_NOT_SUPPORTED;
}
buf[n++] |= file->ef_structure & 7;
if ( (file->ef_structure & 7) > 1) {
/* record structured file */
buf[n++] = 0x41; /* indicate 3rd byte */
buf[n++] = file->record_length;
}
sc_asn1_put_tag(0x82, buf, n, p, 8, &p);
/* File identifier */
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, 16, &p);
/* Directory name */
if (file->type == SC_FILE_TYPE_DF) {
if (file->namelen) {
sc_asn1_put_tag(0x84, file->name, file->namelen,
p, 16, &p);
}
else {
/* TCOS needs one, so we use a faked one */
snprintf ((char *) buf, sizeof(buf)-1, "foo-%lu",
(unsigned long) time (NULL));
sc_asn1_put_tag(0x84, buf, strlen ((char *) buf), p, 16, &p);
}
}
/* File descriptor extension */
if (file->prop_attr_len && file->prop_attr) {
n = file->prop_attr_len;
memcpy(buf, file->prop_attr, n);
}
else {
n = 0;
buf[n++] = 0x01; /* not invalidated, permanent */
if (file->type == SC_FILE_TYPE_WORKING_EF)
buf[n++] = 0x00; /* generic data file */
}
sc_asn1_put_tag(0x85, buf, n, p, 16, &p);
/* Security attributes */
if (file->sec_attr_len && file->sec_attr) {
memcpy(buf, file->sec_attr, file->sec_attr_len);
n = file->sec_attr_len;
}
else {
/* no attributes given - fall back to default one */
memcpy (buf+ 0, "\xa4\x00\x00\x00\xff\xff", 6); /* select */
memcpy (buf+ 6, "\xb0\x00\x00\x00\xff\xff", 6); /* read bin */
memcpy (buf+12, "\xd6\x00\x00\x00\xff\xff", 6); /* upd bin */
memcpy (buf+18, "\x60\x00\x00\x00\xff\xff", 6); /* admin grp*/
n = 24;
}
sc_asn1_put_tag(0x86, buf, n, p, sizeof (buf), &p);
/* fixup length of FCI */
out[1] = p - out - 2;
*outlen = p - out;
return 0;
}
static int tcos_create_file(sc_card_t *card, sc_file_t *file)
{
int r;
size_t len;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_apdu_t apdu;
len = SC_MAX_APDU_BUFFER_SIZE;
r = tcos_construct_fci(file, sbuf, &len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "tcos_construct_fci() failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00);
apdu.cla |= 0x80; /* this is an proprietary extension */
apdu.lc = len;
apdu.datalen = len;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static unsigned int map_operations (int commandbyte )
{
unsigned int op = (unsigned int)-1;
switch ( (commandbyte & 0xfe) ) {
case 0xe2: /* append record */ op = SC_AC_OP_UPDATE; break;
case 0x24: /* change password */ op = SC_AC_OP_UPDATE; break;
case 0xe0: /* create */ op = SC_AC_OP_CREATE; break;
case 0xe4: /* delete */ op = SC_AC_OP_DELETE; break;
case 0xe8: /* exclude sfi */ op = SC_AC_OP_WRITE; break;
case 0x82: /* external auth */ op = SC_AC_OP_READ; break;
case 0xe6: /* include sfi */ op = SC_AC_OP_WRITE; break;
case 0x88: /* internal auth */ op = SC_AC_OP_READ; break;
case 0x04: /* invalidate */ op = SC_AC_OP_INVALIDATE; break;
case 0x2a: /* perform sec. op */ op = SC_AC_OP_SELECT; break;
case 0xb0: /* read binary */ op = SC_AC_OP_READ; break;
case 0xb2: /* read record */ op = SC_AC_OP_READ; break;
case 0x44: /* rehabilitate */ op = SC_AC_OP_REHABILITATE; break;
case 0xa4: /* select */ op = SC_AC_OP_SELECT; break;
case 0xee: /* set permanent */ op = SC_AC_OP_CREATE; break;
case 0x2c: /* unblock password */op = SC_AC_OP_WRITE; break;
case 0xd6: /* update binary */ op = SC_AC_OP_WRITE; break;
case 0xdc: /* update record */ op = SC_AC_OP_WRITE; break;
case 0x20: /* verify password */ op = SC_AC_OP_SELECT; break;
case 0x60: /* admin group */ op = SC_AC_OP_CREATE; break;
}
return op;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static void parse_sec_attr(sc_card_t *card,
sc_file_t *file, const u8 *buf, size_t len)
{
unsigned int op;
/* list directory is not covered by ACLs - so always add an entry */
sc_file_add_acl_entry (file, SC_AC_OP_LIST_FILES,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
/* FIXME: check for what LOCK is used */
sc_file_add_acl_entry (file, SC_AC_OP_LOCK,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
for (; len >= 6; len -= 6, buf += 6) {
/* FIXME: temporary hacks */
if (!memcmp(buf, "\xa4\x00\x00\x00\xff\xff", 6)) /* select */
sc_file_add_acl_entry (file, SC_AC_OP_SELECT,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\xb0\x00\x00\x00\xff\xff", 6)) /*read*/
sc_file_add_acl_entry (file, SC_AC_OP_READ,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\xd6\x00\x00\x00\xff\xff", 6)) /*upd*/
sc_file_add_acl_entry (file, SC_AC_OP_UPDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\x60\x00\x00\x00\xff\xff", 6)) {/*adm */
sc_file_add_acl_entry (file, SC_AC_OP_WRITE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_CREATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_INVALIDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_REHABILITATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
}
else {
/* the first byte tells use the command or the
command group. We have to mask bit 0
because this one distinguish between AND/OR
combination of PINs*/
op = map_operations (buf[0]);
if (op == (unsigned int)-1)
{
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Unknown security command byte %02x\n",
buf[0]);
continue;
}
if (!buf[1])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_CHV, buf[1]);
if (!buf[2] && !buf[3])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_TERM,
(buf[2]<<8)|buf[3]);
}
}
}
static int tcos_select_file(sc_card_t *card,
const sc_path_t *in_path,
sc_file_t **file_out)
{
sc_context_t *ctx;
sc_apdu_t apdu;
sc_file_t *file=NULL;
u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
unsigned int i;
int r, pathlen;
assert(card != NULL && in_path != NULL);
ctx=card->ctx;
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS;
/* fall through */
case SC_PATH_TYPE_FROM_CURRENT:
apdu.p1 = 9;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
case SC_PATH_TYPE_PATH:
apdu.p1 = 8;
if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2;
if (pathlen == 0) apdu.p1 = 0;
break;
case SC_PATH_TYPE_PARENT:
apdu.p1 = 3;
pathlen = 0;
break;
default:
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 256;
} else {
apdu.resplen = 0;
apdu.le = 0;
apdu.p2 = 0x0C;
apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r);
if (apdu.resplen < 1 || apdu.resp[0] != 0x62){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
file = sc_file_new();
if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
*file_out = file;
file->path = *in_path;
for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){
int j, len=apdu.resp[i+1];
unsigned char type=apdu.resp[i], *d=apdu.resp+i+2;
switch (type) {
case 0x80:
case 0x81:
file->size=0;
for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j];
break;
case 0x82:
file->shareable = (d[0] & 0x40) ? 1 : 0;
file->ef_structure = d[0] & 7;
switch ((d[0]>>3) & 7) {
case 0: file->type = SC_FILE_TYPE_WORKING_EF; break;
case 7: file->type = SC_FILE_TYPE_DF; break;
default:
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
break;
case 0x83:
file->id = (d[0]<<8) | d[1];
break;
case 0x84:
memcpy(file->name, d, len);
file->namelen = len;
break;
case 0x86:
sc_file_set_sec_attr(file, d, len);
break;
default:
if (len>0) sc_file_set_prop_attr(file, d, len);
}
}
file->magic = SC_FILE_MAGIC;
parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len);
return 0;
}
static int tcos_list_files(sc_card_t *card, u8 *buf, size_t buflen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE], p1;
int r, count = 0;
assert(card != NULL);
ctx = card->ctx;
for (p1=1; p1<=2; p1++) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, p1, 0);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1==0x6A && (apdu.sw2==0x82 || apdu.sw2==0x88)) continue;
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "List Dir failed");
if (apdu.resplen > buflen) return SC_ERROR_BUFFER_TOO_SMALL;
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"got %"SC_FORMAT_LEN_SIZE_T"u %s-FileIDs\n",
apdu.resplen / 2, p1 == 1 ? "DF" : "EF");
memcpy(buf, apdu.resp, apdu.resplen);
buf += apdu.resplen;
buflen -= apdu.resplen;
count += apdu.resplen;
}
return count;
}
static int tcos_delete_file(sc_card_t *card, const sc_path_t *path)
{
int r;
u8 sbuf[2];
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (path->type != SC_PATH_TYPE_FILE_ID && path->len != 2) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File type has to be SC_PATH_TYPE_FILE_ID\n");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
sbuf[0] = path->value[0];
sbuf[1] = path->value[1];
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p;
int r, default_key, tcos3;
tcos_data *data;
assert(card != NULL && env != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
if (se_num || (env->operation!=SC_SEC_OPERATION_DECIPHER && env->operation!=SC_SEC_OPERATION_SIGN)){
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
if(!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT))
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"No Key-Reference in SecEnvironment\n");
else
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Key-Reference %02X (len=%"SC_FORMAT_LEN_SIZE_T"u)\n",
env->key_ref[0], env->key_ref_len);
/* Key-Reference 0x80 ?? */
default_key= !(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len==1 && env->key_ref[0]==0x80);
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"TCOS3:%d PKCS1:%d\n", tcos3,
!!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
data->pad_flags = env->algorithm_flags;
data->next_sign = default_key;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, tcos3 ? 0x41 : 0xC1, 0xB8);
p = sbuf;
*p++=0x80; *p++=0x01; *p++=tcos3 ? 0x0A : 0x10;
if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) {
*p++ = (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) ? 0x83 : 0x84;
*p++ = env->key_ref_len;
memcpy(p, env->key_ref, env->key_ref_len);
p += env->key_ref_len;
}
apdu.data = sbuf;
apdu.lc = apdu.datalen = (p - sbuf);
r=sc_transmit_apdu(card, &apdu);
if (r) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"%s: APDU transmit failed", sc_strerror(r));
return r;
}
if (apdu.sw1==0x6A && (apdu.sw2==0x81 || apdu.sw2==0x88)) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Detected Signature-Only key\n");
if (env->operation==SC_SEC_OPERATION_SIGN && default_key) return SC_SUCCESS;
}
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_restore_security_env(sc_card_t *card, int se_num)
{
return 0;
}
static int tcos_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen)
{
size_t i, dlen=datalen;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
int tcos3, r;
assert(card != NULL && data != NULL && out != NULL);
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
if (datalen > 255) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
if(((tcos_data *)card->drv_data)->next_sign){
if(datalen>48){
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Data to be signed is too long (TCOS supports max. 48 bytes)\n");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A);
memcpy(sbuf, data, datalen);
dlen=datalen;
} else {
int keylen= tcos3 ? 256 : 128;
sc_format_apdu(card, &apdu, keylen>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
}
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = tcos3 ? 256 : 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (tcos3 && apdu.p1==0x80 && apdu.sw1==0x6A && apdu.sw2==0x87) {
int keylen=128;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
}
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len = apdu.resplen>outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
tcos_data *data;
int tcos3, r;
assert(card != NULL && crgram != NULL && out != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_NORMAL);
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"TCOS3:%d PKCS1:%d\n",tcos3,
!!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = crgram_len;
apdu.data = sbuf;
apdu.lc = apdu.datalen = crgram_len+1;
sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02);
memcpy(sbuf+1, crgram, crgram_len);
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen;
unsigned int offset=0;
if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2){
offset=2; while(offset<len && apdu.resp[offset]!=0) ++offset;
offset=(offset<len-1) ? offset+1 : 0;
}
memcpy(out, apdu.resp+offset, len-offset);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
/* Issue the SET PERMANENT command. With ENABLE_NULLPIN set the
NullPIN method will be activated, otherwise the permanent operation
will be done on the active file. */
static int tcos_setperm(sc_card_t *card, int enable_nullpin)
{
int r;
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xEE, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 0;
apdu.datalen = 0;
apdu.data = NULL;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial)
{
int r;
if (!serial)
return SC_ERROR_INVALID_ARGUMENTS;
/* see if we have cached serial number */
if (card->serialnr.len) {
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
card->serialnr.len = sizeof card->serialnr.value;
r = sc_parse_ef_gdo(card, card->serialnr.value, &card->serialnr.len, NULL, 0);
if (r < 0) {
card->serialnr.len = 0;
return r;
}
/* copy and return serial number */
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
static int tcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
switch (cmd) {
case SC_CARDCTL_TCOS_SETPERM:
return tcos_setperm(card, !!ptr);
case SC_CARDCTL_GET_SERIALNR:
return tcos_get_serialnr(card, (sc_serial_number_t *)ptr);
}
return SC_ERROR_NOT_SUPPORTED;
}
struct sc_card_driver * sc_get_tcos_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL) iso_ops = iso_drv->ops;
tcos_ops = *iso_drv->ops;
tcos_ops.match_card = tcos_match_card;
tcos_ops.init = tcos_init;
tcos_ops.finish = tcos_finish;
tcos_ops.create_file = tcos_create_file;
tcos_ops.set_security_env = tcos_set_security_env;
tcos_ops.select_file = tcos_select_file;
tcos_ops.list_files = tcos_list_files;
tcos_ops.delete_file = tcos_delete_file;
tcos_ops.set_security_env = tcos_set_security_env;
tcos_ops.compute_signature = tcos_compute_signature;
tcos_ops.decipher = tcos_decipher;
tcos_ops.restore_security_env = tcos_restore_security_env;
tcos_ops.card_ctl = tcos_card_ctl;
return &tcos_drv;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_344_3 |
crossvul-cpp_data_good_927_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% EEEEE N N H H AAA N N CCCC EEEEE %
% E NN N H H A A NN N C E %
% EEE N N N HHHHH AAAAA N N N C EEE %
% E N NN H H A A N NN C E %
% EEEEE N N H H A A N N CCCC EEEEE %
% %
% %
% MagickCore Image Enhancement 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/accelerate-private.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/fx.h"
#include "MagickCore/gem.h"
#include "MagickCore/gem-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/histogram.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resample.h"
#include "MagickCore/resample-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/threshold.h"
#include "MagickCore/token.h"
#include "MagickCore/xml-tree.h"
#include "MagickCore/xml-tree-private.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A u t o G a m m a I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AutoGammaImage() extract the 'mean' from the image and adjust the image
% to try make set its gamma appropriatally.
%
% The format of the AutoGammaImage method is:
%
% MagickBooleanType AutoGammaImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: The image to auto-level
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType AutoGammaImage(Image *image,
ExceptionInfo *exception)
{
double
gamma,
log_mean,
mean,
sans;
MagickStatusType
status;
register ssize_t
i;
log_mean=log(0.5);
if (image->channel_mask == DefaultChannels)
{
/*
Apply gamma correction equally across all given channels.
*/
(void) GetImageMean(image,&mean,&sans,exception);
gamma=log(mean*QuantumScale)/log_mean;
return(LevelImage(image,0.0,(double) QuantumRange,gamma,exception));
}
/*
Auto-gamma each channel separately.
*/
status=MagickTrue;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
ChannelType
channel_mask;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
channel_mask=SetImageChannelMask(image,(ChannelType) (1UL << i));
status=GetImageMean(image,&mean,&sans,exception);
gamma=log(mean*QuantumScale)/log_mean;
status&=LevelImage(image,0.0,(double) QuantumRange,gamma,exception);
(void) SetImageChannelMask(image,channel_mask);
if (status == MagickFalse)
break;
}
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A u t o L e v e l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AutoLevelImage() adjusts the levels of a particular image channel by
% scaling the minimum and maximum values to the full quantum range.
%
% The format of the LevelImage method is:
%
% MagickBooleanType AutoLevelImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: The image to auto-level
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType AutoLevelImage(Image *image,
ExceptionInfo *exception)
{
return(MinMaxStretchImage(image,0.0,0.0,1.0,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B r i g h t n e s s C o n t r a s t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BrightnessContrastImage() changes the brightness and/or contrast of an
% image. It converts the brightness and contrast parameters into slope and
% intercept and calls a polynomical function to apply to the image.
%
% The format of the BrightnessContrastImage method is:
%
% MagickBooleanType BrightnessContrastImage(Image *image,
% const double brightness,const double contrast,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o brightness: the brightness percent (-100 .. 100).
%
% o contrast: the contrast percent (-100 .. 100).
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType BrightnessContrastImage(Image *image,
const double brightness,const double contrast,ExceptionInfo *exception)
{
#define BrightnessContastImageTag "BrightnessContast/Image"
double
alpha,
coefficients[2],
intercept,
slope;
MagickBooleanType
status;
/*
Compute slope and intercept.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
alpha=contrast;
slope=tan((double) (MagickPI*(alpha/100.0+1.0)/4.0));
if (slope < 0.0)
slope=0.0;
intercept=brightness/100.0+((100-brightness)/200.0)*(1.0-slope);
coefficients[0]=slope;
coefficients[1]=intercept;
status=FunctionImage(image,PolynomialFunction,2,coefficients,exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C L A H E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CLAHEImage() is a variant of adaptive histogram equalization in which the
% contrast amplification is limited, so as to reduce this problem of noise
% amplification.
%
% Adapted from implementation by Karel Zuiderveld, karel@cv.ruu.nl in
% "Graphics Gems IV", Academic Press, 1994.
%
% The format of the CLAHEImage method is:
%
% MagickBooleanType CLAHEImage(Image *image,const size_t width,
% const size_t height,const size_t number_bins,const double clip_limit,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width: the width of the tile divisions to use in horizontal direction.
%
% o height: the height of the tile divisions to use in vertical direction.
%
% o number_bins: number of bins for histogram ("dynamic range").
%
% o clip_limit: contrast limit for localised changes in contrast. A limit
% less than 1 results in standard non-contrast limited AHE.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef struct _RangeInfo
{
unsigned short
min,
max;
} RangeInfo;
static void ClipCLAHEHistogram(const double clip_limit,const size_t number_bins,
size_t *histogram)
{
#define NumberCLAHEGrays (65536)
register ssize_t
i;
size_t
cumulative_excess,
previous_excess,
step;
ssize_t
excess;
/*
Compute total number of excess pixels.
*/
cumulative_excess=0;
for (i=0; i < (ssize_t) number_bins; i++)
{
excess=(ssize_t) histogram[i]-(ssize_t) clip_limit;
if (excess > 0)
cumulative_excess+=excess;
}
/*
Clip histogram and redistribute excess pixels across all bins.
*/
step=cumulative_excess/number_bins;
excess=(ssize_t) (clip_limit-step);
for (i=0; i < (ssize_t) number_bins; i++)
{
if ((double) histogram[i] > clip_limit)
histogram[i]=(size_t) clip_limit;
else
if ((ssize_t) histogram[i] > excess)
{
cumulative_excess-=histogram[i]-excess;
histogram[i]=(size_t) clip_limit;
}
else
{
cumulative_excess-=step;
histogram[i]+=step;
}
}
/*
Redistribute remaining excess.
*/
do
{
register size_t
*p;
size_t
*q;
previous_excess=cumulative_excess;
p=histogram;
q=histogram+number_bins;
while ((cumulative_excess != 0) && (p < q))
{
step=number_bins/cumulative_excess;
if (step < 1)
step=1;
for (p=histogram; (p < q) && (cumulative_excess != 0); p+=step)
if ((double) *p < clip_limit)
{
(*p)++;
cumulative_excess--;
}
p++;
}
} while ((cumulative_excess != 0) && (cumulative_excess < previous_excess));
}
static void GenerateCLAHEHistogram(const RectangleInfo *clahe_info,
const RectangleInfo *tile_info,const size_t number_bins,
const unsigned short *lut,const unsigned short *pixels,size_t *histogram)
{
register const unsigned short
*p;
register ssize_t
i;
/*
Classify the pixels into a gray histogram.
*/
for (i=0; i < (ssize_t) number_bins; i++)
histogram[i]=0L;
p=pixels;
for (i=0; i < (ssize_t) tile_info->height; i++)
{
const unsigned short
*q;
q=p+tile_info->width;
while (p < q)
histogram[lut[*p++]]++;
q+=clahe_info->width;
p=q-tile_info->width;
}
}
static void InterpolateCLAHE(const RectangleInfo *clahe_info,const size_t *Q12,
const size_t *Q22,const size_t *Q11,const size_t *Q21,
const RectangleInfo *tile,const unsigned short *lut,unsigned short *pixels)
{
ssize_t
y;
unsigned short
intensity;
/*
Bilinear interpolate four tiles to eliminate boundary artifacts.
*/
for (y=(ssize_t) tile->height; y > 0; y--)
{
register ssize_t
x;
for (x=(ssize_t) tile->width; x > 0; x--)
{
intensity=lut[*pixels];
*pixels++=(unsigned short ) (PerceptibleReciprocal((double) tile->width*
tile->height)*(y*(x*Q12[intensity]+(tile->width-x)*Q22[intensity])+
(tile->height-y)*(x*Q11[intensity]+(tile->width-x)*Q21[intensity])));
}
pixels+=(clahe_info->width-tile->width);
}
}
static void GenerateCLAHELut(const RangeInfo *range_info,
const size_t number_bins,unsigned short *lut)
{
ssize_t
i;
unsigned short
delta;
/*
Scale input image [intensity min,max] to [0,number_bins-1].
*/
delta=(unsigned short) ((range_info->max-range_info->min)/number_bins+1);
for (i=(ssize_t) range_info->min; i <= (ssize_t) range_info->max; i++)
lut[i]=(unsigned short) ((i-range_info->min)/delta);
}
static void MapCLAHEHistogram(const RangeInfo *range_info,
const size_t number_bins,const size_t number_pixels,size_t *histogram)
{
double
scale,
sum;
register ssize_t
i;
/*
Rescale histogram to range [min-intensity .. max-intensity].
*/
scale=(double) (range_info->max-range_info->min)/number_pixels;
sum=0.0;
for (i=0; i < (ssize_t) number_bins; i++)
{
sum+=histogram[i];
histogram[i]=(size_t) (range_info->min+scale*sum);
if (histogram[i] > range_info->max)
histogram[i]=range_info->max;
}
}
static MagickBooleanType CLAHE(const RectangleInfo *clahe_info,
const RectangleInfo *tile_info,const RangeInfo *range_info,
const size_t number_bins,const double clip_limit,unsigned short *pixels)
{
MemoryInfo
*tile_cache;
register unsigned short
*p;
size_t
limit,
*tiles;
ssize_t
y;
unsigned short
lut[NumberCLAHEGrays];
/*
Constrast limited adapted histogram equalization.
*/
if (clip_limit == 1.0)
return(MagickTrue);
tile_cache=AcquireVirtualMemory((size_t) clahe_info->x*clahe_info->y,
number_bins*sizeof(*tiles));
if (tile_cache == (MemoryInfo *) NULL)
return(MagickFalse);
tiles=(size_t *) GetVirtualMemoryBlob(tile_cache);
limit=(size_t) (clip_limit*(tile_info->width*tile_info->height)/number_bins);
if (limit < 1UL)
limit=1UL;
/*
Generate greylevel mappings for each tile.
*/
GenerateCLAHELut(range_info,number_bins,lut);
p=pixels;
for (y=0; y < (ssize_t) clahe_info->y; y++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) clahe_info->x; x++)
{
size_t
*histogram;
histogram=tiles+(number_bins*(y*clahe_info->x+x));
GenerateCLAHEHistogram(clahe_info,tile_info,number_bins,lut,p,histogram);
ClipCLAHEHistogram((double) limit,number_bins,histogram);
MapCLAHEHistogram(range_info,number_bins,tile_info->width*
tile_info->height,histogram);
p+=tile_info->width;
}
p+=clahe_info->width*(tile_info->height-1);
}
/*
Interpolate greylevel mappings to get CLAHE image.
*/
p=pixels;
for (y=0; y <= (ssize_t) clahe_info->y; y++)
{
OffsetInfo
offset;
RectangleInfo
tile;
register ssize_t
x;
tile.height=tile_info->height;
tile.y=y-1;
offset.y=tile.y+1;
if (y == 0)
{
/*
Top row.
*/
tile.height=tile_info->height >> 1;
tile.y=0;
offset.y=0;
}
else
if (y == (ssize_t) clahe_info->y)
{
/*
Bottom row.
*/
tile.height=(tile_info->height+1) >> 1;
tile.y=clahe_info->y-1;
offset.y=tile.y;
}
for (x=0; x <= (ssize_t) clahe_info->x; x++)
{
tile.width=tile_info->width;
tile.x=x-1;
offset.x=tile.x+1;
if (x == 0)
{
/*
Left column.
*/
tile.width=tile_info->width >> 1;
tile.x=0;
offset.x=0;
}
else
if (x == (ssize_t) clahe_info->x)
{
/*
Right column.
*/
tile.width=(tile_info->width+1) >> 1;
tile.x=clahe_info->x-1;
offset.x=tile.x;
}
InterpolateCLAHE(clahe_info,
tiles+(number_bins*(tile.y*clahe_info->x+tile.x)), /* Q12 */
tiles+(number_bins*(tile.y*clahe_info->x+offset.x)), /* Q22 */
tiles+(number_bins*(offset.y*clahe_info->x+tile.x)), /* Q11 */
tiles+(number_bins*(offset.y*clahe_info->x+offset.x)), /* Q21 */
&tile,lut,p);
p+=tile.width;
}
p+=clahe_info->width*(tile.height-1);
}
tile_cache=RelinquishVirtualMemory(tile_cache);
return(MagickTrue);
}
MagickExport MagickBooleanType CLAHEImage(Image *image,const size_t width,
const size_t height,const size_t number_bins,const double clip_limit,
ExceptionInfo *exception)
{
#define CLAHEImageTag "CLAHE/Image"
CacheView
*image_view;
ColorspaceType
colorspace;
MagickBooleanType
status;
MagickOffsetType
progress;
MemoryInfo
*pixel_cache;
RangeInfo
range_info;
RectangleInfo
clahe_info,
tile_info;
size_t
n;
ssize_t
y;
unsigned short
*pixels;
/*
Configure CLAHE parameters.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
range_info.min=0;
range_info.max=NumberCLAHEGrays-1;
tile_info.width=width;
if (tile_info.width == 0)
tile_info.width=image->columns >> 3;
tile_info.height=height;
if (tile_info.height == 0)
tile_info.height=image->rows >> 3;
tile_info.x=0;
if ((image->columns % tile_info.width) != 0)
tile_info.x=(ssize_t) tile_info.width-(image->columns % tile_info.width);
tile_info.y=0;
if ((image->rows % tile_info.height) != 0)
tile_info.y=(ssize_t) tile_info.height-(image->rows % tile_info.height);
clahe_info.width=image->columns+tile_info.x;
clahe_info.height=image->rows+tile_info.y;
clahe_info.x=(ssize_t) clahe_info.width/tile_info.width;
clahe_info.y=(ssize_t) clahe_info.height/tile_info.height;
pixel_cache=AcquireVirtualMemory(clahe_info.width,clahe_info.height*
sizeof(*pixels));
if (pixel_cache == (MemoryInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
pixels=(unsigned short *) GetVirtualMemoryBlob(pixel_cache);
colorspace=image->colorspace;
if (TransformImageColorspace(image,LabColorspace,exception) == MagickFalse)
{
pixel_cache=RelinquishVirtualMemory(pixel_cache);
return(MagickFalse);
}
/*
Initialize CLAHE pixels.
*/
image_view=AcquireVirtualCacheView(image,exception);
progress=0;
status=MagickTrue;
n=0;
for (y=0; y < (ssize_t) clahe_info.height; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-(tile_info.x >> 1),y-
(tile_info.y >> 1),clahe_info.width,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) clahe_info.width; x++)
{
pixels[n++]=ScaleQuantumToShort(p[0]);
p+=GetPixelChannels(image);
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,CLAHEImageTag,progress,2*
GetPixelChannels(image));
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
status=CLAHE(&clahe_info,&tile_info,&range_info,number_bins == 0 ?
(size_t) 128 : MagickMin(number_bins,256),clip_limit,pixels);
if (status == MagickFalse)
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
/*
Push CLAHE pixels to CLAHE image.
*/
image_view=AcquireAuthenticCacheView(image,exception);
n=clahe_info.width*(tile_info.y >> 1);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
n+=tile_info.x >> 1;
for (x=0; x < (ssize_t) image->columns; x++)
{
q[0]=ScaleShortToQuantum(pixels[n++]);
q+=GetPixelChannels(image);
}
n+=(clahe_info.width-image->columns-(tile_info.x >> 1));
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,CLAHEImageTag,progress,2*
GetPixelChannels(image));
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
pixel_cache=RelinquishVirtualMemory(pixel_cache);
if (TransformImageColorspace(image,colorspace,exception) == MagickFalse)
status=MagickFalse;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l u t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClutImage() replaces each color value in the given image, by using it as an
% index to lookup a replacement color value in a Color Look UP Table in the
% form of an image. The values are extracted along a diagonal of the CLUT
% image so either a horizontal or vertial gradient image can be used.
%
% Typically this is used to either re-color a gray-scale image according to a
% color gradient in the CLUT image, or to perform a freeform histogram
% (level) adjustment according to the (typically gray-scale) gradient in the
% CLUT image.
%
% When the 'channel' mask includes the matte/alpha transparency channel but
% one image has no such channel it is assumed that that image is a simple
% gray-scale image that will effect the alpha channel values, either for
% gray-scale coloring (with transparent or semi-transparent colors), or
% a histogram adjustment of existing alpha channel values. If both images
% have matte channels, direct and normal indexing is applied, which is rarely
% used.
%
% The format of the ClutImage method is:
%
% MagickBooleanType ClutImage(Image *image,Image *clut_image,
% const PixelInterpolateMethod method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image, which is replaced by indexed CLUT values
%
% o clut_image: the color lookup table image for replacement color values.
%
% o method: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ClutImage(Image *image,const Image *clut_image,
const PixelInterpolateMethod method,ExceptionInfo *exception)
{
#define ClutImageTag "Clut/Image"
CacheView
*clut_view,
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
*clut_map;
register ssize_t
i;
ssize_t adjust,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(clut_image != (Image *) NULL);
assert(clut_image->signature == MagickCoreSignature);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
(IsGrayColorspace(clut_image->colorspace) == MagickFalse))
(void) SetImageColorspace(image,sRGBColorspace,exception);
clut_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*clut_map));
if (clut_map == (PixelInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
/*
Clut image.
*/
status=MagickTrue;
progress=0;
adjust=(ssize_t) (clut_image->interpolate == IntegerInterpolatePixel ? 0 : 1);
clut_view=AcquireVirtualCacheView(clut_image,exception);
for (i=0; i <= (ssize_t) MaxMap; i++)
{
GetPixelInfo(clut_image,clut_map+i);
status=InterpolatePixelInfo(clut_image,clut_view,method,
(double) i*(clut_image->columns-adjust)/MaxMap,(double) i*
(clut_image->rows-adjust)/MaxMap,clut_map+i,exception);
if (status == MagickFalse)
break;
}
clut_view=DestroyCacheView(clut_view);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
GetPixelInfo(image,&pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
PixelTrait
traits;
GetPixelInfoPixel(image,q,&pixel);
traits=GetPixelChannelTraits(image,RedPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
pixel.red=clut_map[ScaleQuantumToMap(ClampToQuantum(
pixel.red))].red;
traits=GetPixelChannelTraits(image,GreenPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
pixel.green=clut_map[ScaleQuantumToMap(ClampToQuantum(
pixel.green))].green;
traits=GetPixelChannelTraits(image,BluePixelChannel);
if ((traits & UpdatePixelTrait) != 0)
pixel.blue=clut_map[ScaleQuantumToMap(ClampToQuantum(
pixel.blue))].blue;
traits=GetPixelChannelTraits(image,BlackPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
pixel.black=clut_map[ScaleQuantumToMap(ClampToQuantum(
pixel.black))].black;
traits=GetPixelChannelTraits(image,AlphaPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
pixel.alpha=clut_map[ScaleQuantumToMap(ClampToQuantum(
pixel.alpha))].alpha;
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ClutImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
clut_map=(PixelInfo *) RelinquishMagickMemory(clut_map);
if ((clut_image->alpha_trait != UndefinedPixelTrait) &&
((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0))
(void) SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o l o r D e c i s i o n L i s t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ColorDecisionListImage() accepts a lightweight Color Correction Collection
% (CCC) file which solely contains one or more color corrections and applies
% the correction to the image. Here is a sample CCC file:
%
% <ColorCorrectionCollection xmlns="urn:ASC:CDL:v1.2">
% <ColorCorrection id="cc03345">
% <SOPNode>
% <Slope> 0.9 1.2 0.5 </Slope>
% <Offset> 0.4 -0.5 0.6 </Offset>
% <Power> 1.0 0.8 1.5 </Power>
% </SOPNode>
% <SATNode>
% <Saturation> 0.85 </Saturation>
% </SATNode>
% </ColorCorrection>
% </ColorCorrectionCollection>
%
% which includes the slop, offset, and power for each of the RGB channels
% as well as the saturation.
%
% The format of the ColorDecisionListImage method is:
%
% MagickBooleanType ColorDecisionListImage(Image *image,
% const char *color_correction_collection,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o color_correction_collection: the color correction collection in XML.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ColorDecisionListImage(Image *image,
const char *color_correction_collection,ExceptionInfo *exception)
{
#define ColorDecisionListCorrectImageTag "ColorDecisionList/Image"
typedef struct _Correction
{
double
slope,
offset,
power;
} Correction;
typedef struct _ColorCorrection
{
Correction
red,
green,
blue;
double
saturation;
} ColorCorrection;
CacheView
*image_view;
char
token[MagickPathExtent];
ColorCorrection
color_correction;
const char
*content,
*p;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
*cdl_map;
register ssize_t
i;
ssize_t
y;
XMLTreeInfo
*cc,
*ccc,
*sat,
*sop;
/*
Allocate and initialize cdl maps.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (color_correction_collection == (const char *) NULL)
return(MagickFalse);
ccc=NewXMLTree((const char *) color_correction_collection,exception);
if (ccc == (XMLTreeInfo *) NULL)
return(MagickFalse);
cc=GetXMLTreeChild(ccc,"ColorCorrection");
if (cc == (XMLTreeInfo *) NULL)
{
ccc=DestroyXMLTree(ccc);
return(MagickFalse);
}
color_correction.red.slope=1.0;
color_correction.red.offset=0.0;
color_correction.red.power=1.0;
color_correction.green.slope=1.0;
color_correction.green.offset=0.0;
color_correction.green.power=1.0;
color_correction.blue.slope=1.0;
color_correction.blue.offset=0.0;
color_correction.blue.power=1.0;
color_correction.saturation=0.0;
sop=GetXMLTreeChild(cc,"SOPNode");
if (sop != (XMLTreeInfo *) NULL)
{
XMLTreeInfo
*offset,
*power,
*slope;
slope=GetXMLTreeChild(sop,"Slope");
if (slope != (XMLTreeInfo *) NULL)
{
content=GetXMLTreeContent(slope);
p=(const char *) content;
for (i=0; (*p != '\0') && (i < 3); i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
switch (i)
{
case 0:
{
color_correction.red.slope=StringToDouble(token,(char **) NULL);
break;
}
case 1:
{
color_correction.green.slope=StringToDouble(token,
(char **) NULL);
break;
}
case 2:
{
color_correction.blue.slope=StringToDouble(token,
(char **) NULL);
break;
}
}
}
}
offset=GetXMLTreeChild(sop,"Offset");
if (offset != (XMLTreeInfo *) NULL)
{
content=GetXMLTreeContent(offset);
p=(const char *) content;
for (i=0; (*p != '\0') && (i < 3); i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
switch (i)
{
case 0:
{
color_correction.red.offset=StringToDouble(token,
(char **) NULL);
break;
}
case 1:
{
color_correction.green.offset=StringToDouble(token,
(char **) NULL);
break;
}
case 2:
{
color_correction.blue.offset=StringToDouble(token,
(char **) NULL);
break;
}
}
}
}
power=GetXMLTreeChild(sop,"Power");
if (power != (XMLTreeInfo *) NULL)
{
content=GetXMLTreeContent(power);
p=(const char *) content;
for (i=0; (*p != '\0') && (i < 3); i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
switch (i)
{
case 0:
{
color_correction.red.power=StringToDouble(token,(char **) NULL);
break;
}
case 1:
{
color_correction.green.power=StringToDouble(token,
(char **) NULL);
break;
}
case 2:
{
color_correction.blue.power=StringToDouble(token,
(char **) NULL);
break;
}
}
}
}
}
sat=GetXMLTreeChild(cc,"SATNode");
if (sat != (XMLTreeInfo *) NULL)
{
XMLTreeInfo
*saturation;
saturation=GetXMLTreeChild(sat,"Saturation");
if (saturation != (XMLTreeInfo *) NULL)
{
content=GetXMLTreeContent(saturation);
p=(const char *) content;
GetNextToken(p,&p,MagickPathExtent,token);
color_correction.saturation=StringToDouble(token,(char **) NULL);
}
}
ccc=DestroyXMLTree(ccc);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" Color Correction Collection:");
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.red.slope: %g",color_correction.red.slope);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.red.offset: %g",color_correction.red.offset);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.red.power: %g",color_correction.red.power);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.green.slope: %g",color_correction.green.slope);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.green.offset: %g",color_correction.green.offset);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.green.power: %g",color_correction.green.power);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.blue.slope: %g",color_correction.blue.slope);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.blue.offset: %g",color_correction.blue.offset);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.blue.power: %g",color_correction.blue.power);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.saturation: %g",color_correction.saturation);
}
cdl_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*cdl_map));
if (cdl_map == (PixelInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
for (i=0; i <= (ssize_t) MaxMap; i++)
{
cdl_map[i].red=(double) ScaleMapToQuantum((double)
(MaxMap*(pow(color_correction.red.slope*i/MaxMap+
color_correction.red.offset,color_correction.red.power))));
cdl_map[i].green=(double) ScaleMapToQuantum((double)
(MaxMap*(pow(color_correction.green.slope*i/MaxMap+
color_correction.green.offset,color_correction.green.power))));
cdl_map[i].blue=(double) ScaleMapToQuantum((double)
(MaxMap*(pow(color_correction.blue.slope*i/MaxMap+
color_correction.blue.offset,color_correction.blue.power))));
}
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Apply transfer function to colormap.
*/
double
luma;
luma=0.21267f*image->colormap[i].red+0.71526*image->colormap[i].green+
0.07217f*image->colormap[i].blue;
image->colormap[i].red=luma+color_correction.saturation*cdl_map[
ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red))].red-luma;
image->colormap[i].green=luma+color_correction.saturation*cdl_map[
ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green))].green-luma;
image->colormap[i].blue=luma+color_correction.saturation*cdl_map[
ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue))].blue-luma;
}
/*
Apply transfer function to image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
luma;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
luma=0.21267f*GetPixelRed(image,q)+0.71526*GetPixelGreen(image,q)+
0.07217f*GetPixelBlue(image,q);
SetPixelRed(image,ClampToQuantum(luma+color_correction.saturation*
(cdl_map[ScaleQuantumToMap(GetPixelRed(image,q))].red-luma)),q);
SetPixelGreen(image,ClampToQuantum(luma+color_correction.saturation*
(cdl_map[ScaleQuantumToMap(GetPixelGreen(image,q))].green-luma)),q);
SetPixelBlue(image,ClampToQuantum(luma+color_correction.saturation*
(cdl_map[ScaleQuantumToMap(GetPixelBlue(image,q))].blue-luma)),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ColorDecisionListCorrectImageTag,
progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
cdl_map=(PixelInfo *) RelinquishMagickMemory(cdl_map);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o n t r a s t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ContrastImage() enhances the intensity differences between the lighter and
% darker elements of the image. Set sharpen to a MagickTrue to increase the
% image contrast otherwise the contrast is reduced.
%
% The format of the ContrastImage method is:
%
% MagickBooleanType ContrastImage(Image *image,
% const MagickBooleanType sharpen,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o sharpen: Increase or decrease image contrast.
%
% o exception: return any errors or warnings in this structure.
%
*/
static void Contrast(const int sign,double *red,double *green,double *blue)
{
double
brightness,
hue,
saturation;
/*
Enhance contrast: dark color become darker, light color become lighter.
*/
assert(red != (double *) NULL);
assert(green != (double *) NULL);
assert(blue != (double *) NULL);
hue=0.0;
saturation=0.0;
brightness=0.0;
ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness);
brightness+=0.5*sign*(0.5*(sin((double) (MagickPI*(brightness-0.5)))+1.0)-
brightness);
if (brightness > 1.0)
brightness=1.0;
else
if (brightness < 0.0)
brightness=0.0;
ConvertHSBToRGB(hue,saturation,brightness,red,green,blue);
}
MagickExport MagickBooleanType ContrastImage(Image *image,
const MagickBooleanType sharpen,ExceptionInfo *exception)
{
#define ContrastImageTag "Contrast/Image"
CacheView
*image_view;
int
sign;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
if (AccelerateContrastImage(image,sharpen,exception) != MagickFalse)
return(MagickTrue);
#endif
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
sign=sharpen != MagickFalse ? 1 : -1;
if (image->storage_class == PseudoClass)
{
/*
Contrast enhance colormap.
*/
for (i=0; i < (ssize_t) image->colors; i++)
{
double
blue,
green,
red;
red=(double) image->colormap[i].red;
green=(double) image->colormap[i].green;
blue=(double) image->colormap[i].blue;
Contrast(sign,&red,&green,&blue);
image->colormap[i].red=(MagickRealType) red;
image->colormap[i].green=(MagickRealType) green;
image->colormap[i].blue=(MagickRealType) blue;
}
}
/*
Contrast enhance image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
blue,
green,
red;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
red=(double) GetPixelRed(image,q);
green=(double) GetPixelGreen(image,q);
blue=(double) GetPixelBlue(image,q);
Contrast(sign,&red,&green,&blue);
SetPixelRed(image,ClampToQuantum(red),q);
SetPixelGreen(image,ClampToQuantum(green),q);
SetPixelBlue(image,ClampToQuantum(blue),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ContrastImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o n t r a s t S t r e t c h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ContrastStretchImage() is a simple image enhancement technique that attempts
% to improve the contrast in an image by 'stretching' the range of intensity
% values it contains to span a desired range of values. It differs from the
% more sophisticated histogram equalization in that it can only apply a
% linear scaling function to the image pixel values. As a result the
% 'enhancement' is less harsh.
%
% The format of the ContrastStretchImage method is:
%
% MagickBooleanType ContrastStretchImage(Image *image,
% const char *levels,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o black_point: the black point.
%
% o white_point: the white point.
%
% o levels: Specify the levels where the black and white points have the
% range of 0 to number-of-pixels (e.g. 1%, 10x90%, etc.).
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ContrastStretchImage(Image *image,
const double black_point,const double white_point,ExceptionInfo *exception)
{
#define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color)))
#define ContrastStretchImageTag "ContrastStretch/Image"
CacheView
*image_view;
double
*black,
*histogram,
*stretch_map,
*white;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate histogram and stretch map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageGray(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace,exception);
black=(double *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*black));
white=(double *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*white));
histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*
sizeof(*histogram));
stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*
sizeof(*stretch_map));
if ((black == (double *) NULL) || (white == (double *) NULL) ||
(histogram == (double *) NULL) || (stretch_map == (double *) NULL))
{
if (stretch_map != (double *) NULL)
stretch_map=(double *) RelinquishMagickMemory(stretch_map);
if (histogram != (double *) NULL)
histogram=(double *) RelinquishMagickMemory(histogram);
if (white != (double *) NULL)
white=(double *) RelinquishMagickMemory(white);
if (black != (double *) NULL)
black=(double *) RelinquishMagickMemory(black);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
/*
Form histogram.
*/
status=MagickTrue;
(void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
pixel=GetPixelIntensity(image,p);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
if (image->channel_mask != DefaultChannels)
pixel=(double) p[i];
histogram[GetPixelChannels(image)*ScaleQuantumToMap(
ClampToQuantum(pixel))+i]++;
}
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
/*
Find the histogram boundaries by locating the black/white levels.
*/
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
intensity;
register ssize_t
j;
black[i]=0.0;
white[i]=MaxRange(QuantumRange);
intensity=0.0;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
if (intensity > black_point)
break;
}
black[i]=(double) j;
intensity=0.0;
for (j=(ssize_t) MaxMap; j != 0; j--)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
if (intensity > ((double) image->columns*image->rows-white_point))
break;
}
white[i]=(double) j;
}
histogram=(double *) RelinquishMagickMemory(histogram);
/*
Stretch the histogram to create the stretched image mapping.
*/
(void) memset(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*stretch_map));
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
register ssize_t
j;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
double
gamma;
gamma=PerceptibleReciprocal(white[i]-black[i]);
if (j < (ssize_t) black[i])
stretch_map[GetPixelChannels(image)*j+i]=0.0;
else
if (j > (ssize_t) white[i])
stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange;
else
if (black[i] != white[i])
stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum(
(double) (MaxMap*gamma*(j-black[i])));
}
}
if (image->storage_class == PseudoClass)
{
register ssize_t
j;
/*
Stretch-contrast colormap.
*/
for (j=0; j < (ssize_t) image->colors; j++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,RedPixelChannel);
image->colormap[j].red=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i];
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,GreenPixelChannel);
image->colormap[j].green=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i];
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,BluePixelChannel);
image->colormap[j].blue=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i];
}
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,AlphaPixelChannel);
image->colormap[j].alpha=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i];
}
}
}
/*
Stretch-contrast image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel = GetPixelChannelChannel(image,j);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (black[j] == white[j])
continue;
q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(q[j])+j]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ContrastStretchImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
stretch_map=(double *) RelinquishMagickMemory(stretch_map);
white=(double *) RelinquishMagickMemory(white);
black=(double *) RelinquishMagickMemory(black);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E n h a n c e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% EnhanceImage() applies a digital filter that improves the quality of a
% noisy image.
%
% The format of the EnhanceImage method is:
%
% Image *EnhanceImage(const 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 Image *EnhanceImage(const Image *image,ExceptionInfo *exception)
{
#define EnhanceImageTag "Enhance/Image"
#define EnhancePixel(weight) \
mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \
distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \
distance_squared=(4.0+mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \
distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \
distance_squared+=(7.0-mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \
distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \
distance_squared+=(5.0-mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \
distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \
distance_squared+=(5.0-mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \
distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \
distance_squared+=(5.0-mean)*distance*distance; \
if (distance_squared < 0.069) \
{ \
aggregate.red+=(weight)*GetPixelRed(image,r); \
aggregate.green+=(weight)*GetPixelGreen(image,r); \
aggregate.blue+=(weight)*GetPixelBlue(image,r); \
aggregate.black+=(weight)*GetPixelBlack(image,r); \
aggregate.alpha+=(weight)*GetPixelAlpha(image,r); \
total_weight+=(weight); \
} \
r+=GetPixelChannels(image);
CacheView
*enhance_view,
*image_view;
Image
*enhance_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Initialize enhanced image attributes.
*/
assert(image != (const 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);
enhance_image=CloneImage(image,0,0,MagickTrue,
exception);
if (enhance_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse)
{
enhance_image=DestroyImage(enhance_image);
return((Image *) NULL);
}
/*
Enhance image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
enhance_view=AcquireAuthenticCacheView(enhance_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,enhance_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
center;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception);
q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) GetPixelChannels(image)*(2*(image->columns+4)+2);
GetPixelInfo(image,&pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
double
distance,
distance_squared,
mean,
total_weight;
PixelInfo
aggregate;
register const Quantum
*magick_restrict r;
GetPixelInfo(image,&aggregate);
total_weight=0.0;
GetPixelInfoPixel(image,p+center,&pixel);
r=p;
EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0);
EnhancePixel(8.0); EnhancePixel(5.0);
r=p+GetPixelChannels(image)*(image->columns+4);
EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0);
EnhancePixel(20.0); EnhancePixel(8.0);
r=p+2*GetPixelChannels(image)*(image->columns+4);
EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0);
EnhancePixel(40.0); EnhancePixel(10.0);
r=p+3*GetPixelChannels(image)*(image->columns+4);
EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0);
EnhancePixel(20.0); EnhancePixel(8.0);
r=p+4*GetPixelChannels(image)*(image->columns+4);
EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0);
EnhancePixel(8.0); EnhancePixel(5.0);
if (total_weight > MagickEpsilon)
{
pixel.red=((aggregate.red+total_weight/2.0)/total_weight);
pixel.green=((aggregate.green+total_weight/2.0)/total_weight);
pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight);
pixel.black=((aggregate.black+total_weight/2.0)/total_weight);
pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight);
}
SetPixelViaPixelInfo(enhance_image,&pixel,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(enhance_image);
}
if (SyncCacheViewAuthenticPixels(enhance_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,EnhanceImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
enhance_view=DestroyCacheView(enhance_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
enhance_image=DestroyImage(enhance_image);
return(enhance_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E q u a l i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% EqualizeImage() applies a histogram equalization to the image.
%
% The format of the EqualizeImage method is:
%
% MagickBooleanType EqualizeImage(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 EqualizeImage(Image *image,
ExceptionInfo *exception)
{
#define EqualizeImageTag "Equalize/Image"
CacheView
*image_view;
double
black[CompositePixelChannel+1],
*equalize_map,
*histogram,
*map,
white[CompositePixelChannel+1];
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate and initialize histogram arrays.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
if (AccelerateEqualizeImage(image,exception) != MagickFalse)
return(MagickTrue);
#endif
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*
sizeof(*equalize_map));
histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*
sizeof(*histogram));
map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*sizeof(*map));
if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) ||
(map == (double *) NULL))
{
if (map != (double *) NULL)
map=(double *) RelinquishMagickMemory(map);
if (histogram != (double *) NULL)
histogram=(double *) RelinquishMagickMemory(histogram);
if (equalize_map != (double *) NULL)
equalize_map=(double *) RelinquishMagickMemory(equalize_map);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
/*
Form histogram.
*/
status=MagickTrue;
(void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
intensity;
intensity=(double) p[i];
if ((image->channel_mask & SyncChannels) != 0)
intensity=GetPixelIntensity(image,p);
histogram[GetPixelChannels(image)*ScaleQuantumToMap(
ClampToQuantum(intensity))+i]++;
}
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
/*
Integrate the histogram to get the equalization map.
*/
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
intensity;
register ssize_t
j;
intensity=0.0;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
map[GetPixelChannels(image)*j+i]=intensity;
}
}
(void) memset(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*equalize_map));
(void) memset(black,0,sizeof(*black));
(void) memset(white,0,sizeof(*white));
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
register ssize_t
j;
black[i]=map[i];
white[i]=map[GetPixelChannels(image)*MaxMap+i];
if (black[i] != white[i])
for (j=0; j <= (ssize_t) MaxMap; j++)
equalize_map[GetPixelChannels(image)*j+i]=(double)
ScaleMapToQuantum((double) ((MaxMap*(map[
GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i])));
}
histogram=(double *) RelinquishMagickMemory(histogram);
map=(double *) RelinquishMagickMemory(map);
if (image->storage_class == PseudoClass)
{
register ssize_t
j;
/*
Equalize colormap.
*/
for (j=0; j < (ssize_t) image->colors; j++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel = GetPixelChannelChannel(image,
RedPixelChannel);
if (black[channel] != white[channel])
image->colormap[j].red=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+
channel];
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel = GetPixelChannelChannel(image,
GreenPixelChannel);
if (black[channel] != white[channel])
image->colormap[j].green=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+
channel];
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel = GetPixelChannelChannel(image,
BluePixelChannel);
if (black[channel] != white[channel])
image->colormap[j].blue=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+
channel];
}
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel = GetPixelChannelChannel(image,
AlphaPixelChannel);
if (black[channel] != white[channel])
image->colormap[j].alpha=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+
channel];
}
}
}
/*
Equalize image.
*/
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel = GetPixelChannelChannel(image,j);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j]))
continue;
q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(q[j])+j]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,EqualizeImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
equalize_map=(double *) RelinquishMagickMemory(equalize_map);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G a m m a I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GammaImage() gamma-corrects a particular image channel. The same
% image viewed on different devices will have perceptual differences in the
% way the image's intensities are represented on the screen. Specify
% individual gamma levels for the red, green, and blue channels, or adjust
% all three with the gamma parameter. Values typically range from 0.8 to 2.3.
%
% You can also reduce the influence of a particular channel with a gamma
% value of 0.
%
% The format of the GammaImage method is:
%
% MagickBooleanType GammaImage(Image *image,const double gamma,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o level: the image gamma as a string (e.g. 1.6,1.2,1.0).
%
% o gamma: the image gamma.
%
*/
static inline double gamma_pow(const double value,const double gamma)
{
return(value < 0.0 ? value : pow(value,gamma));
}
MagickExport MagickBooleanType GammaImage(Image *image,const double gamma,
ExceptionInfo *exception)
{
#define GammaImageTag "Gamma/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
Quantum
*gamma_map;
register ssize_t
i;
ssize_t
y;
/*
Allocate and initialize gamma maps.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (gamma == 1.0)
return(MagickTrue);
gamma_map=(Quantum *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*gamma_map));
if (gamma_map == (Quantum *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
(void) memset(gamma_map,0,(MaxMap+1)*sizeof(*gamma_map));
if (gamma != 0.0)
for (i=0; i <= (ssize_t) MaxMap; i++)
gamma_map[i]=ScaleMapToQuantum((double) (MaxMap*pow((double) i/
MaxMap,1.0/gamma)));
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Gamma-correct colormap.
*/
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(double) gamma_map[ScaleQuantumToMap(
ClampToQuantum(image->colormap[i].red))];
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(double) gamma_map[ScaleQuantumToMap(
ClampToQuantum(image->colormap[i].green))];
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(double) gamma_map[ScaleQuantumToMap(
ClampToQuantum(image->colormap[i].blue))];
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(double) gamma_map[ScaleQuantumToMap(
ClampToQuantum(image->colormap[i].alpha))];
}
/*
Gamma-correct image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel = GetPixelChannelChannel(image,j);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[j]=gamma_map[ScaleQuantumToMap(ClampToQuantum((MagickRealType)
q[j]))];
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,GammaImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
gamma_map=(Quantum *) RelinquishMagickMemory(gamma_map);
if (image->gamma != 0.0)
image->gamma*=gamma;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G r a y s c a l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GrayscaleImage() converts the image to grayscale.
%
% The format of the GrayscaleImage method is:
%
% MagickBooleanType GrayscaleImage(Image *image,
% const PixelIntensityMethod method ,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o method: the pixel intensity method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GrayscaleImage(Image *image,
const PixelIntensityMethod method,ExceptionInfo *exception)
{
#define GrayscaleImageTag "Grayscale/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
{
if (SyncImage(image,exception) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
#if defined(MAGICKCORE_OPENCL_SUPPORT)
if (AccelerateGrayscaleImage(image,method,exception) != MagickFalse)
{
image->intensity=method;
image->type=GrayscaleType;
if ((method == Rec601LuminancePixelIntensityMethod) ||
(method == Rec709LuminancePixelIntensityMethod))
return(SetImageColorspace(image,LinearGRAYColorspace,exception));
return(SetImageColorspace(image,GRAYColorspace,exception));
}
#endif
/*
Grayscale image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
blue,
green,
red,
intensity;
red=(MagickRealType) GetPixelRed(image,q);
green=(MagickRealType) GetPixelGreen(image,q);
blue=(MagickRealType) GetPixelBlue(image,q);
intensity=0.0;
switch (method)
{
case AveragePixelIntensityMethod:
{
intensity=(red+green+blue)/3.0;
break;
}
case BrightnessPixelIntensityMethod:
{
intensity=MagickMax(MagickMax(red,green),blue);
break;
}
case LightnessPixelIntensityMethod:
{
intensity=(MagickMin(MagickMin(red,green),blue)+
MagickMax(MagickMax(red,green),blue))/2.0;
break;
}
case MSPixelIntensityMethod:
{
intensity=(MagickRealType) (((double) red*red+green*green+
blue*blue)/3.0);
break;
}
case Rec601LumaPixelIntensityMethod:
{
if (image->colorspace == RGBColorspace)
{
red=EncodePixelGamma(red);
green=EncodePixelGamma(green);
blue=EncodePixelGamma(blue);
}
intensity=0.298839*red+0.586811*green+0.114350*blue;
break;
}
case Rec601LuminancePixelIntensityMethod:
{
if (image->colorspace == sRGBColorspace)
{
red=DecodePixelGamma(red);
green=DecodePixelGamma(green);
blue=DecodePixelGamma(blue);
}
intensity=0.298839*red+0.586811*green+0.114350*blue;
break;
}
case Rec709LumaPixelIntensityMethod:
default:
{
if (image->colorspace == RGBColorspace)
{
red=EncodePixelGamma(red);
green=EncodePixelGamma(green);
blue=EncodePixelGamma(blue);
}
intensity=0.212656*red+0.715158*green+0.072186*blue;
break;
}
case Rec709LuminancePixelIntensityMethod:
{
if (image->colorspace == sRGBColorspace)
{
red=DecodePixelGamma(red);
green=DecodePixelGamma(green);
blue=DecodePixelGamma(blue);
}
intensity=0.212656*red+0.715158*green+0.072186*blue;
break;
}
case RMSPixelIntensityMethod:
{
intensity=(MagickRealType) (sqrt((double) red*red+green*green+
blue*blue)/sqrt(3.0));
break;
}
}
SetPixelGray(image,ClampToQuantum(intensity),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,GrayscaleImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
image->intensity=method;
image->type=GrayscaleType;
if ((method == Rec601LuminancePixelIntensityMethod) ||
(method == Rec709LuminancePixelIntensityMethod))
return(SetImageColorspace(image,LinearGRAYColorspace,exception));
return(SetImageColorspace(image,GRAYColorspace,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% H a l d C l u t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% HaldClutImage() applies a Hald color lookup table to the image. A Hald
% color lookup table is a 3-dimensional color cube mapped to 2 dimensions.
% Create it with the HALD coder. You can apply any color transformation to
% the Hald image and then use this method to apply the transform to the
% image.
%
% The format of the HaldClutImage method is:
%
% MagickBooleanType HaldClutImage(Image *image,Image *hald_image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image, which is replaced by indexed CLUT values
%
% o hald_image: the color lookup table image for replacement color values.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType HaldClutImage(Image *image,
const Image *hald_image,ExceptionInfo *exception)
{
#define HaldClutImageTag "Clut/Image"
typedef struct _HaldInfo
{
double
x,
y,
z;
} HaldInfo;
CacheView
*hald_view,
*image_view;
double
width;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
zero;
size_t
cube_size,
length,
level;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(hald_image != (Image *) NULL);
assert(hald_image->signature == MagickCoreSignature);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
/*
Hald clut image.
*/
status=MagickTrue;
progress=0;
length=(size_t) MagickMin((MagickRealType) hald_image->columns,
(MagickRealType) hald_image->rows);
for (level=2; (level*level*level) < length; level++) ;
level*=level;
cube_size=level*level;
width=(double) hald_image->columns;
GetPixelInfo(hald_image,&zero);
hald_view=AcquireVirtualCacheView(hald_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
offset;
HaldInfo
point;
PixelInfo
pixel,
pixel1,
pixel2,
pixel3,
pixel4;
point.x=QuantumScale*(level-1.0)*GetPixelRed(image,q);
point.y=QuantumScale*(level-1.0)*GetPixelGreen(image,q);
point.z=QuantumScale*(level-1.0)*GetPixelBlue(image,q);
offset=point.x+level*floor(point.y)+cube_size*floor(point.z);
point.x-=floor(point.x);
point.y-=floor(point.y);
point.z-=floor(point.z);
pixel1=zero;
status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
fmod(offset,width),floor(offset/width),&pixel1,exception);
if (status == MagickFalse)
break;
pixel2=zero;
status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception);
if (status == MagickFalse)
break;
pixel3=zero;
CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha,
point.y,&pixel3);
offset+=cube_size;
status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
fmod(offset,width),floor(offset/width),&pixel1,exception);
if (status == MagickFalse)
break;
status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception);
if (status == MagickFalse)
break;
pixel4=zero;
CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha,
point.y,&pixel4);
pixel=zero;
CompositePixelInfoAreaBlend(&pixel3,pixel3.alpha,&pixel4,pixel4.alpha,
point.z,&pixel);
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
SetPixelRed(image,ClampToQuantum(pixel.red),q);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
SetPixelGreen(image,ClampToQuantum(pixel.green),q);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
SetPixelBlue(image,ClampToQuantum(pixel.blue),q);
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelBlack(image,ClampToQuantum(pixel.black),q);
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,HaldClutImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
hald_view=DestroyCacheView(hald_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L e v e l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LevelImage() adjusts the levels of a particular image channel by
% scaling the colors falling between specified white and black points to
% the full available quantum range.
%
% The parameters provided represent the black, and white points. The black
% point specifies the darkest color in the image. Colors darker than the
% black point are set to zero. White point specifies the lightest color in
% the image. Colors brighter than the white point are set to the maximum
% quantum value.
%
% If a '!' flag is given, map black and white colors to the given levels
% rather than mapping those levels to black and white. See
% LevelizeImage() below.
%
% Gamma specifies a gamma correction to apply to the image.
%
% The format of the LevelImage method is:
%
% MagickBooleanType LevelImage(Image *image,const double black_point,
% const double white_point,const double gamma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o black_point: The level to map zero (black) to.
%
% o white_point: The level to map QuantumRange (white) to.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double LevelPixel(const double black_point,
const double white_point,const double gamma,const double pixel)
{
double
level_pixel,
scale;
scale=PerceptibleReciprocal(white_point-black_point);
level_pixel=QuantumRange*gamma_pow(scale*((double) pixel-black_point),
1.0/gamma);
return(level_pixel);
}
MagickExport MagickBooleanType LevelImage(Image *image,const double black_point,
const double white_point,const double gamma,ExceptionInfo *exception)
{
#define LevelImageTag "Level/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate and initialize levels map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Level colormap.
*/
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(double) ClampToQuantum(LevelPixel(black_point,
white_point,gamma,image->colormap[i].red));
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(double) ClampToQuantum(LevelPixel(black_point,
white_point,gamma,image->colormap[i].green));
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(double) ClampToQuantum(LevelPixel(black_point,
white_point,gamma,image->colormap[i].blue));
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(double) ClampToQuantum(LevelPixel(black_point,
white_point,gamma,image->colormap[i].alpha));
}
/*
Level image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel = GetPixelChannelChannel(image,j);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[j]=ClampToQuantum(LevelPixel(black_point,white_point,gamma,
(double) q[j]));
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,LevelImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
(void) ClampImage(image,exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L e v e l i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LevelizeImage() applies the reversed LevelImage() operation to just
% the specific channels specified. It compresses the full range of color
% values, so that they lie between the given black and white points. Gamma is
% applied before the values are mapped.
%
% LevelizeImage() can be called with by using a +level command line
% API option, or using a '!' on a -level or LevelImage() geometry string.
%
% It can be used to de-contrast a greyscale image to the exact levels
% specified. Or by using specific levels for each channel of an image you
% can convert a gray-scale image to any linear color gradient, according to
% those levels.
%
% The format of the LevelizeImage method is:
%
% MagickBooleanType LevelizeImage(Image *image,const double black_point,
% const double white_point,const double gamma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o black_point: The level to map zero (black) to.
%
% o white_point: The level to map QuantumRange (white) to.
%
% o gamma: adjust gamma by this factor before mapping values.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType LevelizeImage(Image *image,
const double black_point,const double white_point,const double gamma,
ExceptionInfo *exception)
{
#define LevelizeImageTag "Levelize/Image"
#define LevelizeValue(x) ClampToQuantum(((MagickRealType) gamma_pow((double) \
(QuantumScale*(x)),gamma))*(white_point-black_point)+black_point)
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate and initialize levels map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Level colormap.
*/
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(double) LevelizeValue(image->colormap[i].red);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(double) LevelizeValue(
image->colormap[i].green);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(double) LevelizeValue(image->colormap[i].blue);
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(double) LevelizeValue(
image->colormap[i].alpha);
}
/*
Level image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel = GetPixelChannelChannel(image,j);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[j]=LevelizeValue(q[j]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,LevelizeImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L e v e l I m a g e C o l o r s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LevelImageColors() maps the given color to "black" and "white" values,
% linearly spreading out the colors, and level values on a channel by channel
% bases, as per LevelImage(). The given colors allows you to specify
% different level ranges for each of the color channels separately.
%
% If the boolean 'invert' is set true the image values will modifyed in the
% reverse direction. That is any existing "black" and "white" colors in the
% image will become the color values given, with all other values compressed
% appropriatally. This effectivally maps a greyscale gradient into the given
% color gradient.
%
% The format of the LevelImageColors method is:
%
% MagickBooleanType LevelImageColors(Image *image,
% const PixelInfo *black_color,const PixelInfo *white_color,
% const MagickBooleanType invert,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o black_color: The color to map black to/from
%
% o white_point: The color to map white to/from
%
% o invert: if true map the colors (levelize), rather than from (level)
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType LevelImageColors(Image *image,
const PixelInfo *black_color,const PixelInfo *white_color,
const MagickBooleanType invert,ExceptionInfo *exception)
{
ChannelType
channel_mask;
MagickStatusType
status;
/*
Allocate and initialize levels map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
((IsGrayColorspace(black_color->colorspace) == MagickFalse) ||
(IsGrayColorspace(white_color->colorspace) == MagickFalse)))
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
if (invert == MagickFalse)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,RedChannel);
status&=LevelImage(image,black_color->red,white_color->red,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,GreenChannel);
status&=LevelImage(image,black_color->green,white_color->green,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,BlueChannel);
status&=LevelImage(image,black_color->blue,white_color->blue,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
{
channel_mask=SetImageChannelMask(image,BlackChannel);
status&=LevelImage(image,black_color->black,white_color->black,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
{
channel_mask=SetImageChannelMask(image,AlphaChannel);
status&=LevelImage(image,black_color->alpha,white_color->alpha,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
}
else
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,RedChannel);
status&=LevelizeImage(image,black_color->red,white_color->red,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,GreenChannel);
status&=LevelizeImage(image,black_color->green,white_color->green,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,BlueChannel);
status&=LevelizeImage(image,black_color->blue,white_color->blue,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
{
channel_mask=SetImageChannelMask(image,BlackChannel);
status&=LevelizeImage(image,black_color->black,white_color->black,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
{
channel_mask=SetImageChannelMask(image,AlphaChannel);
status&=LevelizeImage(image,black_color->alpha,white_color->alpha,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
}
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L i n e a r S t r e t c h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LinearStretchImage() discards any pixels below the black point and above
% the white point and levels the remaining pixels.
%
% The format of the LinearStretchImage method is:
%
% MagickBooleanType LinearStretchImage(Image *image,
% const double black_point,const double white_point,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o black_point: the black point.
%
% o white_point: the white point.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType LinearStretchImage(Image *image,
const double black_point,const double white_point,ExceptionInfo *exception)
{
#define LinearStretchImageTag "LinearStretch/Image"
CacheView
*image_view;
double
*histogram,
intensity;
MagickBooleanType
status;
ssize_t
black,
white,
y;
/*
Allocate histogram and linear map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*histogram));
if (histogram == (double *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
/*
Form histogram.
*/
(void) memset(histogram,0,(MaxMap+1)*sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
intensity=GetPixelIntensity(image,p);
histogram[ScaleQuantumToMap(ClampToQuantum(intensity))]++;
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
/*
Find the histogram boundaries by locating the black and white point levels.
*/
intensity=0.0;
for (black=0; black < (ssize_t) MaxMap; black++)
{
intensity+=histogram[black];
if (intensity >= black_point)
break;
}
intensity=0.0;
for (white=(ssize_t) MaxMap; white != 0; white--)
{
intensity+=histogram[white];
if (intensity >= white_point)
break;
}
histogram=(double *) RelinquishMagickMemory(histogram);
status=LevelImage(image,(double) ScaleMapToQuantum((MagickRealType) black),
(double) ScaleMapToQuantum((MagickRealType) white),1.0,exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M o d u l a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ModulateImage() lets you control the brightness, saturation, and hue
% of an image. Modulate represents the brightness, saturation, and hue
% as one parameter (e.g. 90,150,100). If the image colorspace is HSL, the
% modulation is lightness, saturation, and hue. For HWB, use blackness,
% whiteness, and hue. And for HCL, use chrome, luma, and hue.
%
% The format of the ModulateImage method is:
%
% MagickBooleanType ModulateImage(Image *image,const char *modulate,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o modulate: Define the percent change in brightness, saturation, and hue.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline void ModulateHCL(const double percent_hue,
const double percent_chroma,const double percent_luma,double *red,
double *green,double *blue)
{
double
hue,
luma,
chroma;
/*
Increase or decrease color luma, chroma, or hue.
*/
ConvertRGBToHCL(*red,*green,*blue,&hue,&chroma,&luma);
hue+=fmod((percent_hue-100.0),200.0)/200.0;
chroma*=0.01*percent_chroma;
luma*=0.01*percent_luma;
ConvertHCLToRGB(hue,chroma,luma,red,green,blue);
}
static inline void ModulateHCLp(const double percent_hue,
const double percent_chroma,const double percent_luma,double *red,
double *green,double *blue)
{
double
hue,
luma,
chroma;
/*
Increase or decrease color luma, chroma, or hue.
*/
ConvertRGBToHCLp(*red,*green,*blue,&hue,&chroma,&luma);
hue+=fmod((percent_hue-100.0),200.0)/200.0;
chroma*=0.01*percent_chroma;
luma*=0.01*percent_luma;
ConvertHCLpToRGB(hue,chroma,luma,red,green,blue);
}
static inline void ModulateHSB(const double percent_hue,
const double percent_saturation,const double percent_brightness,double *red,
double *green,double *blue)
{
double
brightness,
hue,
saturation;
/*
Increase or decrease color brightness, saturation, or hue.
*/
ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness);
hue+=fmod((percent_hue-100.0),200.0)/200.0;
saturation*=0.01*percent_saturation;
brightness*=0.01*percent_brightness;
ConvertHSBToRGB(hue,saturation,brightness,red,green,blue);
}
static inline void ModulateHSI(const double percent_hue,
const double percent_saturation,const double percent_intensity,double *red,
double *green,double *blue)
{
double
intensity,
hue,
saturation;
/*
Increase or decrease color intensity, saturation, or hue.
*/
ConvertRGBToHSI(*red,*green,*blue,&hue,&saturation,&intensity);
hue+=fmod((percent_hue-100.0),200.0)/200.0;
saturation*=0.01*percent_saturation;
intensity*=0.01*percent_intensity;
ConvertHSIToRGB(hue,saturation,intensity,red,green,blue);
}
static inline void ModulateHSL(const double percent_hue,
const double percent_saturation,const double percent_lightness,double *red,
double *green,double *blue)
{
double
hue,
lightness,
saturation;
/*
Increase or decrease color lightness, saturation, or hue.
*/
ConvertRGBToHSL(*red,*green,*blue,&hue,&saturation,&lightness);
hue+=fmod((percent_hue-100.0),200.0)/200.0;
saturation*=0.01*percent_saturation;
lightness*=0.01*percent_lightness;
ConvertHSLToRGB(hue,saturation,lightness,red,green,blue);
}
static inline void ModulateHSV(const double percent_hue,
const double percent_saturation,const double percent_value,double *red,
double *green,double *blue)
{
double
hue,
saturation,
value;
/*
Increase or decrease color value, saturation, or hue.
*/
ConvertRGBToHSV(*red,*green,*blue,&hue,&saturation,&value);
hue+=fmod((percent_hue-100.0),200.0)/200.0;
saturation*=0.01*percent_saturation;
value*=0.01*percent_value;
ConvertHSVToRGB(hue,saturation,value,red,green,blue);
}
static inline void ModulateHWB(const double percent_hue,
const double percent_whiteness,const double percent_blackness,double *red,
double *green,double *blue)
{
double
blackness,
hue,
whiteness;
/*
Increase or decrease color blackness, whiteness, or hue.
*/
ConvertRGBToHWB(*red,*green,*blue,&hue,&whiteness,&blackness);
hue+=fmod((percent_hue-100.0),200.0)/200.0;
blackness*=0.01*percent_blackness;
whiteness*=0.01*percent_whiteness;
ConvertHWBToRGB(hue,whiteness,blackness,red,green,blue);
}
static inline void ModulateLCHab(const double percent_luma,
const double percent_chroma,const double percent_hue,double *red,
double *green,double *blue)
{
double
hue,
luma,
chroma;
/*
Increase or decrease color luma, chroma, or hue.
*/
ConvertRGBToLCHab(*red,*green,*blue,&luma,&chroma,&hue);
luma*=0.01*percent_luma;
chroma*=0.01*percent_chroma;
hue+=fmod((percent_hue-100.0),200.0)/200.0;
ConvertLCHabToRGB(luma,chroma,hue,red,green,blue);
}
static inline void ModulateLCHuv(const double percent_luma,
const double percent_chroma,const double percent_hue,double *red,
double *green,double *blue)
{
double
hue,
luma,
chroma;
/*
Increase or decrease color luma, chroma, or hue.
*/
ConvertRGBToLCHuv(*red,*green,*blue,&luma,&chroma,&hue);
luma*=0.01*percent_luma;
chroma*=0.01*percent_chroma;
hue+=fmod((percent_hue-100.0),200.0)/200.0;
ConvertLCHuvToRGB(luma,chroma,hue,red,green,blue);
}
MagickExport MagickBooleanType ModulateImage(Image *image,const char *modulate,
ExceptionInfo *exception)
{
#define ModulateImageTag "Modulate/Image"
CacheView
*image_view;
ColorspaceType
colorspace;
const char
*artifact;
double
percent_brightness,
percent_hue,
percent_saturation;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickStatusType
flags;
register ssize_t
i;
ssize_t
y;
/*
Initialize modulate table.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (modulate == (char *) NULL)
return(MagickFalse);
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
flags=ParseGeometry(modulate,&geometry_info);
percent_brightness=geometry_info.rho;
percent_saturation=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
percent_saturation=100.0;
percent_hue=geometry_info.xi;
if ((flags & XiValue) == 0)
percent_hue=100.0;
colorspace=UndefinedColorspace;
artifact=GetImageArtifact(image,"modulate:colorspace");
if (artifact != (const char *) NULL)
colorspace=(ColorspaceType) ParseCommandOption(MagickColorspaceOptions,
MagickFalse,artifact);
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
double
blue,
green,
red;
/*
Modulate image colormap.
*/
red=(double) image->colormap[i].red;
green=(double) image->colormap[i].green;
blue=(double) image->colormap[i].blue;
switch (colorspace)
{
case HCLColorspace:
{
ModulateHCL(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HCLpColorspace:
{
ModulateHCLp(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSBColorspace:
{
ModulateHSB(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSIColorspace:
{
ModulateHSI(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSLColorspace:
default:
{
ModulateHSL(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSVColorspace:
{
ModulateHSV(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HWBColorspace:
{
ModulateHWB(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case LCHColorspace:
case LCHabColorspace:
{
ModulateLCHab(percent_brightness,percent_saturation,percent_hue,
&red,&green,&blue);
break;
}
case LCHuvColorspace:
{
ModulateLCHuv(percent_brightness,percent_saturation,percent_hue,
&red,&green,&blue);
break;
}
}
image->colormap[i].red=red;
image->colormap[i].green=green;
image->colormap[i].blue=blue;
}
/*
Modulate image.
*/
#if defined(MAGICKCORE_OPENCL_SUPPORT)
if (AccelerateModulateImage(image,percent_brightness,percent_hue,
percent_saturation,colorspace,exception) != MagickFalse)
return(MagickTrue);
#endif
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
blue,
green,
red;
red=(double) GetPixelRed(image,q);
green=(double) GetPixelGreen(image,q);
blue=(double) GetPixelBlue(image,q);
switch (colorspace)
{
case HCLColorspace:
{
ModulateHCL(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HCLpColorspace:
{
ModulateHCLp(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSBColorspace:
{
ModulateHSB(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSLColorspace:
default:
{
ModulateHSL(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSVColorspace:
{
ModulateHSV(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HWBColorspace:
{
ModulateHWB(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case LCHabColorspace:
{
ModulateLCHab(percent_brightness,percent_saturation,percent_hue,
&red,&green,&blue);
break;
}
case LCHColorspace:
case LCHuvColorspace:
{
ModulateLCHuv(percent_brightness,percent_saturation,percent_hue,
&red,&green,&blue);
break;
}
}
SetPixelRed(image,ClampToQuantum(red),q);
SetPixelGreen(image,ClampToQuantum(green),q);
SetPixelBlue(image,ClampToQuantum(blue),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ModulateImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% N e g a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% NegateImage() negates the colors in the reference image. The grayscale
% option means that only grayscale values within the image are negated.
%
% The format of the NegateImage method is:
%
% MagickBooleanType NegateImage(Image *image,
% const MagickBooleanType grayscale,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o grayscale: If MagickTrue, only negate grayscale pixels within the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType NegateImage(Image *image,
const MagickBooleanType grayscale,ExceptionInfo *exception)
{
#define NegateImageTag "Negate/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Negate colormap.
*/
if( grayscale != MagickFalse )
if ((image->colormap[i].red != image->colormap[i].green) ||
(image->colormap[i].green != image->colormap[i].blue))
continue;
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=QuantumRange-image->colormap[i].red;
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=QuantumRange-image->colormap[i].green;
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=QuantumRange-image->colormap[i].blue;
}
/*
Negate image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
if( grayscale != MagickFalse )
{
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
if (IsPixelGray(image,q) != MagickFalse)
{
q+=GetPixelChannels(image);
continue;
}
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel = GetPixelChannelChannel(image,j);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[j]=QuantumRange-q[j];
}
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,NegateImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(MagickTrue);
}
/*
Negate image.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel = GetPixelChannelChannel(image,j);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[j]=QuantumRange-q[j];
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,NegateImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% N o r m a l i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% The NormalizeImage() method enhances the contrast of a color image by
% mapping the darkest 2 percent of all pixel to black and the brightest
% 1 percent to white.
%
% The format of the NormalizeImage method is:
%
% MagickBooleanType NormalizeImage(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 NormalizeImage(Image *image,
ExceptionInfo *exception)
{
double
black_point,
white_point;
black_point=(double) image->columns*image->rows*0.0015;
white_point=(double) image->columns*image->rows*0.9995;
return(ContrastStretchImage(image,black_point,white_point,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S i g m o i d a l C o n t r a s t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SigmoidalContrastImage() adjusts the contrast of an image with a non-linear
% sigmoidal contrast algorithm. Increase the contrast of the image using a
% sigmoidal transfer function without saturating highlights or shadows.
% Contrast indicates how much to increase the contrast (0 is none; 3 is
% typical; 20 is pushing it); mid-point indicates where midtones fall in the
% resultant image (0 is white; 50% is middle-gray; 100% is black). Set
% sharpen to MagickTrue to increase the image contrast otherwise the contrast
% is reduced.
%
% The format of the SigmoidalContrastImage method is:
%
% MagickBooleanType SigmoidalContrastImage(Image *image,
% const MagickBooleanType sharpen,const char *levels,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o sharpen: Increase or decrease image contrast.
%
% o contrast: strength of the contrast, the larger the number the more
% 'threshold-like' it becomes.
%
% o midpoint: midpoint of the function as a color value 0 to QuantumRange.
%
% o exception: return any errors or warnings in this structure.
%
*/
/*
ImageMagick 6 has a version of this function which uses LUTs.
*/
/*
Sigmoidal function Sigmoidal with inflexion point moved to b and "slope
constant" set to a.
The first version, based on the hyperbolic tangent tanh, when combined with
the scaling step, is an exact arithmetic clone of the the sigmoid function
based on the logistic curve. The equivalence is based on the identity
1/(1+exp(-t)) = (1+tanh(t/2))/2
(http://de.wikipedia.org/wiki/Sigmoidfunktion) and the fact that the
scaled sigmoidal derivation is invariant under affine transformations of
the ordinate.
The tanh version is almost certainly more accurate and cheaper. The 0.5
factor in the argument is to clone the legacy ImageMagick behavior. The
reason for making the define depend on atanh even though it only uses tanh
has to do with the construction of the inverse of the scaled sigmoidal.
*/
#if defined(MAGICKCORE_HAVE_ATANH)
#define Sigmoidal(a,b,x) ( tanh((0.5*(a))*((x)-(b))) )
#else
#define Sigmoidal(a,b,x) ( 1.0/(1.0+exp((a)*((b)-(x)))) )
#endif
/*
Scaled sigmoidal function:
( Sigmoidal(a,b,x) - Sigmoidal(a,b,0) ) /
( Sigmoidal(a,b,1) - Sigmoidal(a,b,0) )
See http://osdir.com/ml/video.image-magick.devel/2005-04/msg00006.html and
http://www.cs.dartmouth.edu/farid/downloads/tutorials/fip.pdf. The limit
of ScaledSigmoidal as a->0 is the identity, but a=0 gives a division by
zero. This is fixed below by exiting immediately when contrast is small,
leaving the image (or colormap) unmodified. This appears to be safe because
the series expansion of the logistic sigmoidal function around x=b is
1/2-a*(b-x)/4+...
so that the key denominator s(1)-s(0) is about a/4 (a/2 with tanh).
*/
#define ScaledSigmoidal(a,b,x) ( \
(Sigmoidal((a),(b),(x))-Sigmoidal((a),(b),0.0)) / \
(Sigmoidal((a),(b),1.0)-Sigmoidal((a),(b),0.0)) )
/*
Inverse of ScaledSigmoidal, used for +sigmoidal-contrast. Because b
may be 0 or 1, the argument of the hyperbolic tangent (resp. logistic
sigmoidal) may be outside of the interval (-1,1) (resp. (0,1)), even
when creating a LUT from in gamut values, hence the branching. In
addition, HDRI may have out of gamut values.
InverseScaledSigmoidal is not a two-sided inverse of ScaledSigmoidal:
It is only a right inverse. This is unavoidable.
*/
static inline double InverseScaledSigmoidal(const double a,const double b,
const double x)
{
const double sig0=Sigmoidal(a,b,0.0);
const double sig1=Sigmoidal(a,b,1.0);
const double argument=(sig1-sig0)*x+sig0;
const double clamped=
(
#if defined(MAGICKCORE_HAVE_ATANH)
argument < -1+MagickEpsilon
?
-1+MagickEpsilon
:
( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument )
);
return(b+(2.0/a)*atanh(clamped));
#else
argument < MagickEpsilon
?
MagickEpsilon
:
( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument )
);
return(b-log(1.0/clamped-1.0)/a);
#endif
}
MagickExport MagickBooleanType SigmoidalContrastImage(Image *image,
const MagickBooleanType sharpen,const double contrast,const double midpoint,
ExceptionInfo *exception)
{
#define SigmoidalContrastImageTag "SigmoidalContrast/Image"
#define ScaledSig(x) ( ClampToQuantum(QuantumRange* \
ScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) )
#define InverseScaledSig(x) ( ClampToQuantum(QuantumRange* \
InverseScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) )
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Convenience macros.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
/*
Side effect: may clamp values unless contrast<MagickEpsilon, in which
case nothing is done.
*/
if (contrast < MagickEpsilon)
return(MagickTrue);
/*
Sigmoidal-contrast enhance colormap.
*/
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
if( sharpen != MagickFalse )
for (i=0; i < (ssize_t) image->colors; i++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(MagickRealType) ScaledSig(
image->colormap[i].red);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(MagickRealType) ScaledSig(
image->colormap[i].green);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(MagickRealType) ScaledSig(
image->colormap[i].blue);
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(MagickRealType) ScaledSig(
image->colormap[i].alpha);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(MagickRealType) InverseScaledSig(
image->colormap[i].red);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(MagickRealType) InverseScaledSig(
image->colormap[i].green);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(MagickRealType) InverseScaledSig(
image->colormap[i].blue);
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(MagickRealType) InverseScaledSig(
image->colormap[i].alpha);
}
}
/*
Sigmoidal-contrast enhance image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if( sharpen != MagickFalse )
q[i]=ScaledSig(q[i]);
else
q[i]=InverseScaledSig(q[i]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SigmoidalContrastImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_927_0 |
crossvul-cpp_data_bad_342_4 | /*
* PKCS15 emulation layer for EstEID card.
*
* Copyright (C) 2004, Martin Paljak <martin@martinpaljak.net>
* Copyright (C) 2004, Bud P. Bruegger <bud@comune.grosseto.it>
* Copyright (C) 2004, Antonino Iacono <ant_iacono@tin.it>
* Copyright (C) 2003, Olaf Kirch <okir@suse.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "common/compat_strlcpy.h"
#include "common/compat_strlcat.h"
#include "internal.h"
#include "opensc.h"
#include "pkcs15.h"
#include "esteid.h"
int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *, struct sc_aid *, sc_pkcs15emu_opt_t *);
static void
set_string (char **strp, const char *value)
{
if (*strp)
free (*strp);
*strp = value ? strdup (value) : NULL;
}
int
select_esteid_df (sc_card_t * card)
{
int r;
sc_path_t tmppath;
sc_format_path ("3F00EEEE", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "esteid select DF failed");
return r;
}
static int
sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
unsigned char buff[128];
int r, i;
size_t field_length = 0, modulus_length = 0;
sc_path_t tmppath;
set_string (&p15card->tokeninfo->label, "ID-kaart");
set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus");
/* Select application directory */
sc_format_path ("3f00eeee5044", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed");
/* read the serial (document number) */
r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed");
buff[r] = '\0';
set_string (&p15card->tokeninfo->serial_number, (const char *) buff);
p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION
| SC_PKCS15_TOKEN_EID_COMPLIANT
| SC_PKCS15_TOKEN_READONLY;
/* add certificates */
for (i = 0; i < 2; i++) {
static const char *esteid_cert_names[2] = {
"Isikutuvastus",
"Allkirjastamine"};
static char const *esteid_cert_paths[2] = {
"3f00eeeeaace",
"3f00eeeeddce"};
static int esteid_cert_ids[2] = {1, 2};
struct sc_pkcs15_cert_info cert_info;
struct sc_pkcs15_object cert_obj;
memset(&cert_info, 0, sizeof(cert_info));
memset(&cert_obj, 0, sizeof(cert_obj));
cert_info.id.value[0] = esteid_cert_ids[i];
cert_info.id.len = 1;
sc_format_path(esteid_cert_paths[i], &cert_info.path);
strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label));
r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
if (r < 0)
return SC_ERROR_INTERNAL;
if (i == 0) {
sc_pkcs15_cert_t *cert = NULL;
r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert);
if (r < 0)
return SC_ERROR_INTERNAL;
if (cert->key->algorithm == SC_ALGORITHM_EC)
field_length = cert->key->u.ec.params.field_length;
else
modulus_length = cert->key->u.rsa.modulus.len * 8;
if (r == SC_SUCCESS) {
static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }};
u8 *cn_name = NULL;
size_t cn_len = 0;
sc_pkcs15_get_name_from_dn(card->ctx, cert->subject,
cert->subject_len, &cn_oid, &cn_name, &cn_len);
if (cn_len > 0) {
char *token_name = malloc(cn_len+1);
if (token_name) {
memcpy(token_name, cn_name, cn_len);
token_name[cn_len] = '\0';
set_string(&p15card->tokeninfo->label, (const char*)token_name);
free(token_name);
}
}
free(cn_name);
sc_pkcs15_free_certificate(cert);
}
}
}
/* the file with key pin info (tries left) */
sc_format_path ("3f000016", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
if (r < 0)
return SC_ERROR_INTERNAL;
/* add pins */
for (i = 0; i < 3; i++) {
unsigned char tries_left;
static const char *esteid_pin_names[3] = {
"PIN1",
"PIN2",
"PUK" };
static const int esteid_pin_min[3] = {4, 5, 8};
static const int esteid_pin_ref[3] = {1, 2, 0};
static const int esteid_pin_authid[3] = {1, 2, 3};
static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN};
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
/* read the number of tries left for the PIN */
r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
if (r < 0)
return SC_ERROR_INTERNAL;
tries_left = buff[5];
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = esteid_pin_authid[i];
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = esteid_pin_ref[i];
pin_info.attrs.pin.flags = esteid_pin_flags[i];
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = esteid_pin_min[i];
pin_info.attrs.pin.stored_length = 12;
pin_info.attrs.pin.max_length = 12;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = (int)tries_left;
pin_info.max_tries = 3;
strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label));
pin_obj.flags = esteid_pin_flags[i];
/* Link normal PINs with PUK */
if (i < 2) {
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 3;
}
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
/* add private keys */
for (i = 0; i < 2; i++) {
static int prkey_pin[2] = {1, 2};
static const char *prkey_name[2] = {
"Isikutuvastus",
"Allkirjastamine"};
struct sc_pkcs15_prkey_info prkey_info;
struct sc_pkcs15_object prkey_obj;
memset(&prkey_info, 0, sizeof(prkey_info));
memset(&prkey_obj, 0, sizeof(prkey_obj));
prkey_info.id.len = 1;
prkey_info.id.value[0] = prkey_pin[i];
prkey_info.native = 1;
prkey_info.key_reference = i + 1;
prkey_info.field_length = field_length;
prkey_info.modulus_length = modulus_length;
if (i == 1)
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION;
else if(field_length > 0) // ECC has sign and derive usage
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE;
else
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT;
strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label));
prkey_obj.auth_id.len = 1;
prkey_obj.auth_id.value[0] = prkey_pin[i];
prkey_obj.user_consent = 0;
prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
if(field_length > 0)
r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info);
else
r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
return SC_SUCCESS;
}
static int esteid_detect_card(sc_pkcs15_card_t *p15card)
{
if (is_esteid_card(p15card->card))
return SC_SUCCESS;
else
return SC_ERROR_WRONG_CARD;
}
int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)
return sc_pkcs15emu_esteid_init(p15card);
else {
int r = esteid_detect_card(p15card);
if (r)
return SC_ERROR_WRONG_CARD;
return sc_pkcs15emu_esteid_init(p15card);
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_342_4 |
crossvul-cpp_data_bad_4787_20 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF PPPP X X %
% F P P X X %
% FFF PPPP X %
% F P X X %
% F P X X %
% %
% %
% Read/Write FlashPIX Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel.h"
#include "magick/pixel-accessor.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#if defined(MAGICKCORE_FPX_DELEGATE)
#if !defined(vms) && !defined(macintosh) && !defined(MAGICKCORE_WINDOWS_SUPPORT)
#include <fpxlib.h>
#else
#include "Fpxlib.h"
#endif
#endif
#if defined(MAGICKCORE_FPX_DELEGATE)
/*
Forward declarations.
*/
static MagickBooleanType
WriteFPXImage(const ImageInfo *,Image *);
#endif
#if defined(MAGICKCORE_FPX_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d F P X I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadFPXImage() reads a FlashPix image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image. This method was contributed by BillR@corbis.com.
%
% The format of the ReadFPXImage method is:
%
% Image *ReadFPXImage(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 *ReadFPXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
FPXColorspace
colorspace;
FPXImageComponentDesc
*alpha_component,
*blue_component,
*green_component,
*red_component;
FPXImageDesc
fpx_info;
FPXImageHandle
*flashpix;
FPXStatus
fpx_status;
FPXSummaryInformation
summary_info;
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*a,
*b,
*g,
*r;
size_t
memory_limit;
ssize_t
y;
unsigned char
*pixels;
unsigned int
height,
tile_width,
tile_height,
width;
size_t
scene;
/*
Open image.
*/
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);
}
(void) CloseBlob(image);
/*
Initialize FPX toolkit.
*/
fpx_status=FPX_InitSystem();
if (fpx_status != FPX_OK)
ThrowReaderException(CoderError,"UnableToInitializeFPXLibrary");
memory_limit=20000000;
fpx_status=FPX_SetToolkitMemoryLimit(&memory_limit);
if (fpx_status != FPX_OK)
{
FPX_ClearSystem();
ThrowReaderException(CoderError,"UnableToInitializeFPXLibrary");
}
tile_width=64;
tile_height=64;
flashpix=(FPXImageHandle *) NULL;
{
#if defined(macintosh)
FSSpec
fsspec;
FilenameToFSSpec(image->filename,&fsspec);
fpx_status=FPX_OpenImageByFilename((const FSSpec &) fsspec,(char *) NULL,
#else
fpx_status=FPX_OpenImageByFilename(image->filename,(char *) NULL,
#endif
&width,&height,&tile_width,&tile_height,&colorspace,&flashpix);
}
if (fpx_status == FPX_LOW_MEMORY_ERROR)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (fpx_status != FPX_OK)
{
FPX_ClearSystem();
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (colorspace.numberOfComponents == 0)
{
FPX_ClearSystem();
ThrowReaderException(CorruptImageError,"ImageTypeNotSupported");
}
if (image_info->view == (char *) NULL)
{
float
aspect_ratio;
/*
Get the aspect ratio.
*/
aspect_ratio=(float) width/height;
fpx_status=FPX_GetImageResultAspectRatio(flashpix,&aspect_ratio);
if (fpx_status != FPX_OK)
ThrowReaderException(DelegateError,"UnableToReadAspectRatio");
if (width != (size_t) floor((aspect_ratio*height)+0.5))
Swap(width,height);
}
fpx_status=FPX_GetSummaryInformation(flashpix,&summary_info);
if (fpx_status != FPX_OK)
{
FPX_ClearSystem();
ThrowReaderException(DelegateError,"UnableToReadSummaryInfo");
}
if (summary_info.title_valid)
if ((summary_info.title.length != 0) &&
(summary_info.title.ptr != (unsigned char *) NULL))
{
char
*label;
/*
Note image label.
*/
label=(char *) NULL;
if (~summary_info.title.length >= (MaxTextExtent-1))
label=(char *) AcquireQuantumMemory(summary_info.title.length+
MaxTextExtent,sizeof(*label));
if (label == (char *) NULL)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickString(label,(char *) summary_info.title.ptr,
summary_info.title.length+1);
(void) SetImageProperty(image,"label",label);
label=DestroyString(label);
}
if (summary_info.comments_valid)
if ((summary_info.comments.length != 0) &&
(summary_info.comments.ptr != (unsigned char *) NULL))
{
char
*comments;
/*
Note image comment.
*/
comments=(char *) NULL;
if (~summary_info.comments.length >= (MaxTextExtent-1))
comments=(char *) AcquireQuantumMemory(summary_info.comments.length+
MaxTextExtent,sizeof(*comments));
if (comments == (char *) NULL)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickString(comments,(char *) summary_info.comments.ptr,
summary_info.comments.length+1);
(void) SetImageProperty(image,"comment",comments);
comments=DestroyString(comments);
}
/*
Determine resolution by scene specification.
*/
for (i=1; ; i++)
if (((width >> i) < tile_width) || ((height >> i) < tile_height))
break;
scene=i;
if (image_info->number_scenes != 0)
while (scene > image_info->scene)
{
width>>=1;
height>>=1;
scene--;
}
if (image_info->size != (char *) NULL)
while ((width > image->columns) || (height > image->rows))
{
width>>=1;
height>>=1;
scene--;
}
image->depth=8;
image->columns=width;
image->rows=height;
if ((colorspace.numberOfComponents % 2) == 0)
image->matte=MagickTrue;
if (colorspace.numberOfComponents == 1)
{
/*
Create linear colormap.
*/
if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if (image_info->ping != MagickFalse)
{
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
return(GetFirstImageInList(image));
}
/*
Allocate memory for the image and pixel buffer.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,(tile_height+
1UL)*colorspace.numberOfComponents*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
{
FPX_ClearSystem();
(void) FPX_CloseImage(flashpix);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Initialize FlashPix image description.
*/
fpx_info.numberOfComponents=colorspace.numberOfComponents;
for (i=0; i < 4; i++)
{
fpx_info.components[i].myColorType.myDataType=DATA_TYPE_UNSIGNED_BYTE;
fpx_info.components[i].horzSubSampFactor=1;
fpx_info.components[i].vertSubSampFactor=1;
fpx_info.components[i].columnStride=fpx_info.numberOfComponents;
fpx_info.components[i].lineStride=image->columns*
fpx_info.components[i].columnStride;
fpx_info.components[i].theData=pixels+i;
}
fpx_info.components[0].myColorType.myColor=fpx_info.numberOfComponents > 2 ?
NIFRGB_R : MONOCHROME;
red_component=(&fpx_info.components[0]);
fpx_info.components[1].myColorType.myColor=fpx_info.numberOfComponents > 2 ?
NIFRGB_G : ALPHA;
green_component=(&fpx_info.components[1]);
fpx_info.components[2].myColorType.myColor=NIFRGB_B;
blue_component=(&fpx_info.components[2]);
fpx_info.components[3].myColorType.myColor=ALPHA;
alpha_component=(&fpx_info.components[fpx_info.numberOfComponents-1]);
FPX_SetResampleMethod(FPX_LINEAR_INTERPOLATION);
/*
Initialize image pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
if ((y % tile_height) == 0)
{
/*
Read FPX image tile (with or without viewing affine)..
*/
if (image_info->view != (char *) NULL)
fpx_status=FPX_ReadImageRectangle(flashpix,0,y,image->columns,y+
tile_height-1,scene,&fpx_info);
else
fpx_status=FPX_ReadImageTransformRectangle(flashpix,0.0F,
(float) y/image->rows,(float) image->columns/image->rows,
(float) (y+tile_height-1)/image->rows,(ssize_t) image->columns,
(ssize_t) tile_height,&fpx_info);
if (fpx_status == FPX_LOW_MEMORY_ERROR)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
/*
Transfer a FPX pixels.
*/
r=red_component->theData+(y % tile_height)*red_component->lineStride;
g=green_component->theData+(y % tile_height)*green_component->lineStride;
b=blue_component->theData+(y % tile_height)*blue_component->lineStride;
a=alpha_component->theData+(y % tile_height)*alpha_component->lineStride;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (fpx_info.numberOfComponents > 2)
{
SetPixelRed(q,ScaleCharToQuantum(*r));
SetPixelGreen(q,ScaleCharToQuantum(*g));
SetPixelBlue(q,ScaleCharToQuantum(*b));
}
else
{
index=ScaleCharToQuantum(*r);
SetPixelIndex(indexes+x,index);
SetPixelRed(q,index);
SetPixelGreen(q,index);
SetPixelBlue(q,index);
}
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*a));
q++;
r+=red_component->columnStride;
g+=green_component->columnStride;
b+=blue_component->columnStride;
a+=alpha_component->columnStride;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r F P X I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterFPXImage() adds attributes for the FPX 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 RegisterFPXImage method is:
%
% size_t RegisterFPXImage(void)
%
*/
ModuleExport size_t RegisterFPXImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("FPX");
#if defined(MAGICKCORE_FPX_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadFPXImage;
entry->encoder=(EncodeImageHandler *) WriteFPXImage;
#endif
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->blob_support=MagickFalse;
entry->description=ConstantString("FlashPix Format");
entry->module=ConstantString("FPX");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r F P X I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterFPXImage() removes format registrations made by the
% FPX module from the list of supported formats.
%
% The format of the UnregisterFPXImage method is:
%
% UnregisterFPXImage(void)
%
*/
ModuleExport void UnregisterFPXImage(void)
{
(void) UnregisterMagickInfo("FPX");
}
#if defined(MAGICKCORE_FPX_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e F P X I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteFPXImage() writes an image in the FlashPix image format. This
% method was contributed by BillR@corbis.com.
%
% The format of the WriteFPXImage method is:
%
% MagickBooleanType WriteFPXImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static void ColorTwistMultiply(FPXColorTwistMatrix first,
FPXColorTwistMatrix second,FPXColorTwistMatrix *color_twist)
{
/*
Matrix multiply.
*/
assert(color_twist != (FPXColorTwistMatrix *) NULL);
color_twist->byy=(first.byy*second.byy)+(first.byc1*second.bc1y)+
(first.byc2*second.bc2y)+(first.dummy1_zero*second.dummy4_zero);
color_twist->byc1=(first.byy*second.byc1)+(first.byc1*second.bc1c1)+
(first.byc2*second.bc2c1)+(first.dummy1_zero*second.dummy5_zero);
color_twist->byc2=(first.byy*second.byc2)+(first.byc1*second.bc1c2)+
(first.byc2*second.bc2c2)+(first.dummy1_zero*second.dummy6_zero);
color_twist->dummy1_zero=(first.byy*second.dummy1_zero)+
(first.byc1*second.dummy2_zero)+(first.byc2*second.dummy3_zero)+
(first.dummy1_zero*second.dummy7_one);
color_twist->bc1y=(first.bc1y*second.byy)+(first.bc1c1*second.bc1y)+
(first.bc1c2*second.bc2y)+(first.dummy2_zero*second.dummy4_zero);
color_twist->bc1c1=(first.bc1y*second.byc1)+(first.bc1c1*second.bc1c1)+
(first.bc1c2*second.bc2c1)+(first.dummy2_zero*second.dummy5_zero);
color_twist->bc1c2=(first.bc1y*second.byc2)+(first.bc1c1*second.bc1c2)+
(first.bc1c2*second.bc2c2)+(first.dummy2_zero*second.dummy6_zero);
color_twist->dummy2_zero=(first.bc1y*second.dummy1_zero)+
(first.bc1c1*second.dummy2_zero)+(first.bc1c2*second.dummy3_zero)+
(first.dummy2_zero*second.dummy7_one);
color_twist->bc2y=(first.bc2y*second.byy)+(first.bc2c1*second.bc1y)+
(first.bc2c2*second.bc2y)+(first.dummy3_zero*second.dummy4_zero);
color_twist->bc2c1=(first.bc2y*second.byc1)+(first.bc2c1*second.bc1c1)+
(first.bc2c2*second.bc2c1)+(first.dummy3_zero*second.dummy5_zero);
color_twist->bc2c2=(first.bc2y*second.byc2)+(first.bc2c1*second.bc1c2)+
(first.bc2c2*second.bc2c2)+(first.dummy3_zero*second.dummy6_zero);
color_twist->dummy3_zero=(first.bc2y*second.dummy1_zero)+
(first.bc2c1*second.dummy2_zero)+(first.bc2c2*second.dummy3_zero)+
(first.dummy3_zero*second.dummy7_one);
color_twist->dummy4_zero=(first.dummy4_zero*second.byy)+
(first.dummy5_zero*second.bc1y)+(first.dummy6_zero*second.bc2y)+
(first.dummy7_one*second.dummy4_zero);
color_twist->dummy5_zero=(first.dummy4_zero*second.byc1)+
(first.dummy5_zero*second.bc1c1)+(first.dummy6_zero*second.bc2c1)+
(first.dummy7_one*second.dummy5_zero);
color_twist->dummy6_zero=(first.dummy4_zero*second.byc2)+
(first.dummy5_zero*second.bc1c2)+(first.dummy6_zero*second.bc2c2)+
(first.dummy7_one*second.dummy6_zero);
color_twist->dummy7_one=(first.dummy4_zero*second.dummy1_zero)+
(first.dummy5_zero*second.dummy2_zero)+
(first.dummy6_zero*second.dummy3_zero)+(first.dummy7_one*second.dummy7_one);
}
static void SetBrightness(double brightness,FPXColorTwistMatrix *color_twist)
{
FPXColorTwistMatrix
effect,
result;
/*
Set image brightness in color twist matrix.
*/
assert(color_twist != (FPXColorTwistMatrix *) NULL);
brightness=sqrt((double) brightness);
effect.byy=brightness;
effect.byc1=0.0;
effect.byc2=0.0;
effect.dummy1_zero=0.0;
effect.bc1y=0.0;
effect.bc1c1=brightness;
effect.bc1c2=0.0;
effect.dummy2_zero=0.0;
effect.bc2y=0.0;
effect.bc2c1=0.0;
effect.bc2c2=brightness;
effect.dummy3_zero=0.0;
effect.dummy4_zero=0.0;
effect.dummy5_zero=0.0;
effect.dummy6_zero=0.0;
effect.dummy7_one=1.0;
ColorTwistMultiply(*color_twist,effect,&result);
*color_twist=result;
}
static void SetColorBalance(double red,double green,double blue,
FPXColorTwistMatrix *color_twist)
{
FPXColorTwistMatrix
blue_effect,
green_effect,
result,
rgb_effect,
rg_effect,
red_effect;
/*
Set image color balance in color twist matrix.
*/
assert(color_twist != (FPXColorTwistMatrix *) NULL);
red=sqrt((double) red)-1.0;
green=sqrt((double) green)-1.0;
blue=sqrt((double) blue)-1.0;
red_effect.byy=1.0;
red_effect.byc1=0.0;
red_effect.byc2=0.299*red;
red_effect.dummy1_zero=0.0;
red_effect.bc1y=(-0.299)*red;
red_effect.bc1c1=1.0-0.299*red;
red_effect.bc1c2=(-0.299)*red;
red_effect.dummy2_zero=0.0;
red_effect.bc2y=0.701*red;
red_effect.bc2c1=0.0;
red_effect.bc2c2=1.0+0.402*red;
red_effect.dummy3_zero=0.0;
red_effect.dummy4_zero=0.0;
red_effect.dummy5_zero=0.0;
red_effect.dummy6_zero=0.0;
red_effect.dummy7_one=1.0;
green_effect.byy=1.0;
green_effect.byc1=(-0.114)*green;
green_effect.byc2=(-0.299)*green;
green_effect.dummy1_zero=0.0;
green_effect.bc1y=(-0.587)*green;
green_effect.bc1c1=1.0-0.473*green;
green_effect.bc1c2=0.299*green;
green_effect.dummy2_zero=0.0;
green_effect.bc2y=(-0.587)*green;
green_effect.bc2c1=0.114*green;
green_effect.bc2c2=1.0-0.288*green;
green_effect.dummy3_zero=0.0;
green_effect.dummy4_zero=0.0;
green_effect.dummy5_zero=0.0;
green_effect.dummy6_zero=0.0;
green_effect.dummy7_one=1.0;
blue_effect.byy=1.0;
blue_effect.byc1=0.114*blue;
blue_effect.byc2=0.0;
blue_effect.dummy1_zero=0.0;
blue_effect.bc1y=0.886*blue;
blue_effect.bc1c1=1.0+0.772*blue;
blue_effect.bc1c2=0.0;
blue_effect.dummy2_zero=0.0;
blue_effect.bc2y=(-0.114)*blue;
blue_effect.bc2c1=(-0.114)*blue;
blue_effect.bc2c2=1.0-0.114*blue;
blue_effect.dummy3_zero=0.0;
blue_effect.dummy4_zero=0.0;
blue_effect.dummy5_zero=0.0;
blue_effect.dummy6_zero=0.0;
blue_effect.dummy7_one=1.0;
ColorTwistMultiply(red_effect,green_effect,&rg_effect);
ColorTwistMultiply(rg_effect,blue_effect,&rgb_effect);
ColorTwistMultiply(*color_twist,rgb_effect,&result);
*color_twist=result;
}
static void SetSaturation(double saturation,FPXColorTwistMatrix *color_twist)
{
FPXColorTwistMatrix
effect,
result;
/*
Set image saturation in color twist matrix.
*/
assert(color_twist != (FPXColorTwistMatrix *) NULL);
effect.byy=1.0;
effect.byc1=0.0;
effect.byc2=0.0;
effect.dummy1_zero=0.0;
effect.bc1y=0.0;
effect.bc1c1=saturation;
effect.bc1c2=0.0;
effect.dummy2_zero=0.0;
effect.bc2y=0.0;
effect.bc2c1=0.0;
effect.bc2c2=saturation;
effect.dummy3_zero=0.0;
effect.dummy4_zero=0.0;
effect.dummy5_zero=0.0;
effect.dummy6_zero=0.0;
effect.dummy7_one=1.0;
ColorTwistMultiply(*color_twist,effect,&result);
*color_twist=result;
}
static MagickBooleanType WriteFPXImage(const ImageInfo *image_info,Image *image)
{
FPXBackground
background_color;
FPXColorspace
colorspace =
{
TRUE, 4,
{
{ NIFRGB_R, DATA_TYPE_UNSIGNED_BYTE },
{ NIFRGB_G, DATA_TYPE_UNSIGNED_BYTE },
{ NIFRGB_B, DATA_TYPE_UNSIGNED_BYTE },
{ ALPHA, DATA_TYPE_UNSIGNED_BYTE }
}
};
const char
*comment,
*label;
FPXCompressionOption
compression;
FPXImageDesc
fpx_info;
FPXImageHandle
*flashpix;
FPXStatus
fpx_status;
FPXSummaryInformation
summary_info;
MagickBooleanType
status;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register const PixelPacket
*p;
register ssize_t
i;
size_t
memory_limit;
ssize_t
y;
unsigned char
*pixels;
unsigned int
tile_height,
tile_width;
/*
Open input file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
(void) CloseBlob(image);
/*
Initialize FPX toolkit.
*/
image->depth=8;
memory_limit=20000000;
fpx_status=FPX_SetToolkitMemoryLimit(&memory_limit);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToInitializeFPXLibrary");
tile_width=64;
tile_height=64;
colorspace.numberOfComponents=3;
if (image->matte != MagickFalse)
colorspace.numberOfComponents=4;
if ((image_info->type != TrueColorType) &&
IsGrayImage(image,&image->exception))
{
colorspace.numberOfComponents=1;
colorspace.theComponents[0].myColor=MONOCHROME;
}
background_color.color1_value=0;
background_color.color2_value=0;
background_color.color3_value=0;
background_color.color4_value=0;
compression=NONE;
if (image->compression == JPEGCompression)
compression=JPEG_UNSPECIFIED;
if (image_info->compression == JPEGCompression)
compression=JPEG_UNSPECIFIED;
{
#if defined(macintosh)
FSSpec
fsspec;
FilenameToFSSpec(filename,&fsspec);
fpx_status=FPX_CreateImageByFilename((const FSSpec &) fsspec,image->columns,
#else
fpx_status=FPX_CreateImageByFilename(image->filename,image->columns,
#endif
image->rows,tile_width,tile_height,colorspace,background_color,
compression,&flashpix);
}
if (fpx_status != FPX_OK)
return(status);
if (compression == JPEG_UNSPECIFIED)
{
/*
Initialize the compression by quality for the entire image.
*/
fpx_status=FPX_SetJPEGCompression(flashpix,(unsigned short)
image->quality == UndefinedCompressionQuality ? 75 : image->quality);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetJPEGLevel");
}
/*
Set image summary info.
*/
summary_info.title_valid=MagickFalse;
summary_info.subject_valid=MagickFalse;
summary_info.author_valid=MagickFalse;
summary_info.comments_valid=MagickFalse;
summary_info.keywords_valid=MagickFalse;
summary_info.OLEtemplate_valid=MagickFalse;
summary_info.last_author_valid=MagickFalse;
summary_info.rev_number_valid=MagickFalse;
summary_info.edit_time_valid=MagickFalse;
summary_info.last_printed_valid=MagickFalse;
summary_info.create_dtm_valid=MagickFalse;
summary_info.last_save_dtm_valid=MagickFalse;
summary_info.page_count_valid=MagickFalse;
summary_info.word_count_valid=MagickFalse;
summary_info.char_count_valid=MagickFalse;
summary_info.thumbnail_valid=MagickFalse;
summary_info.appname_valid=MagickFalse;
summary_info.security_valid=MagickFalse;
summary_info.title.ptr=(unsigned char *) NULL;
label=GetImageProperty(image,"label");
if (label != (const char *) NULL)
{
size_t
length;
/*
Note image label.
*/
summary_info.title_valid=MagickTrue;
length=strlen(label);
summary_info.title.length=length;
if (~length >= (MaxTextExtent-1))
summary_info.title.ptr=(unsigned char *) AcquireQuantumMemory(
length+MaxTextExtent,sizeof(*summary_info.title.ptr));
if (summary_info.title.ptr == (unsigned char *) NULL)
ThrowWriterException(DelegateError,"UnableToSetImageTitle");
(void) CopyMagickString((char *) summary_info.title.ptr,label,
MaxTextExtent);
}
comment=GetImageProperty(image,"comment");
if (comment != (const char *) NULL)
{
/*
Note image comment.
*/
summary_info.comments_valid=MagickTrue;
summary_info.comments.ptr=(unsigned char *) AcquireString(comment);
summary_info.comments.length=strlen(comment);
}
fpx_status=FPX_SetSummaryInformation(flashpix,&summary_info);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetSummaryInfo");
/*
Initialize FlashPix image description.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
fpx_info.numberOfComponents=colorspace.numberOfComponents;
for (i=0; i < (ssize_t) fpx_info.numberOfComponents; i++)
{
fpx_info.components[i].myColorType.myDataType=DATA_TYPE_UNSIGNED_BYTE;
fpx_info.components[i].horzSubSampFactor=1;
fpx_info.components[i].vertSubSampFactor=1;
fpx_info.components[i].columnStride=fpx_info.numberOfComponents;
fpx_info.components[i].lineStride=
image->columns*fpx_info.components[i].columnStride;
fpx_info.components[i].theData=pixels+i;
}
fpx_info.components[0].myColorType.myColor=fpx_info.numberOfComponents != 1
? NIFRGB_R : MONOCHROME;
fpx_info.components[1].myColorType.myColor=NIFRGB_G;
fpx_info.components[2].myColorType.myColor=NIFRGB_B;
fpx_info.components[3].myColorType.myColor=ALPHA;
/*
Write image pixelss.
*/
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
if (fpx_info.numberOfComponents == 1)
quantum_type=GrayQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
size_t
length;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
quantum_type,pixels,&image->exception);
(void) length;
fpx_status=FPX_WriteImageLine(flashpix,&fpx_info);
if (fpx_status != FPX_OK)
break;
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (image_info->view != (char *) NULL)
{
FPXAffineMatrix
affine;
FPXColorTwistMatrix
color_twist;
FPXContrastAdjustment
contrast;
FPXFilteringValue
sharpen;
FPXResultAspectRatio
aspect_ratio;
FPXROI
view_rect;
MagickBooleanType
affine_valid,
aspect_ratio_valid,
color_twist_valid,
contrast_valid,
sharpen_valid,
view_rect_valid;
/*
Initialize default viewing parameters.
*/
contrast=1.0;
contrast_valid=MagickTrue;
color_twist.byy=1.0;
color_twist.byc1=0.0;
color_twist.byc2=0.0;
color_twist.dummy1_zero=0.0;
color_twist.bc1y=0.0;
color_twist.bc1c1=1.0;
color_twist.bc1c2=0.0;
color_twist.dummy2_zero=0.0;
color_twist.bc2y=0.0;
color_twist.bc2c1=0.0;
color_twist.bc2c2=1.0;
color_twist.dummy3_zero=0.0;
color_twist.dummy4_zero=0.0;
color_twist.dummy5_zero=0.0;
color_twist.dummy6_zero=0.0;
color_twist.dummy7_one=1.0;
color_twist_valid=MagickTrue;
sharpen=0.0;
sharpen_valid=MagickTrue;
aspect_ratio=(double) image->columns/image->rows;
aspect_ratio_valid=MagickTrue;
view_rect.left=(float) 0.1;
view_rect.width=aspect_ratio-0.2;
view_rect.top=(float) 0.1;
view_rect.height=(float) 0.8; /* 1.0-0.2 */
view_rect_valid=MagickTrue;
affine.a11=1.0;
affine.a12=0.0;
affine.a13=0.0;
affine.a14=0.0;
affine.a21=0.0;
affine.a22=1.0;
affine.a23=0.0;
affine.a24=0.0;
affine.a31=0.0;
affine.a32=0.0;
affine.a33=1.0;
affine.a34=0.0;
affine.a41=0.0;
affine.a42=0.0;
affine.a43=0.0;
affine.a44=1.0;
affine_valid=MagickTrue;
if (0)
{
/*
Color color twist.
*/
SetBrightness(0.5,&color_twist);
SetSaturation(0.5,&color_twist);
SetColorBalance(0.5,1.0,1.0,&color_twist);
color_twist_valid=MagickTrue;
}
if (affine_valid != MagickFalse)
{
fpx_status=FPX_SetImageAffineMatrix(flashpix,&affine);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetAffineMatrix");
}
if (aspect_ratio_valid != MagickFalse)
{
fpx_status=FPX_SetImageResultAspectRatio(flashpix,&aspect_ratio);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetAspectRatio");
}
if (color_twist_valid != MagickFalse)
{
fpx_status=FPX_SetImageColorTwistMatrix(flashpix,&color_twist);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetColorTwist");
}
if (contrast_valid != MagickFalse)
{
fpx_status=FPX_SetImageContrastAdjustment(flashpix,&contrast);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetContrast");
}
if (sharpen_valid != MagickFalse)
{
fpx_status=FPX_SetImageFilteringValue(flashpix,&sharpen);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetFilteringValue");
}
if (view_rect_valid != MagickFalse)
{
fpx_status=FPX_SetImageROI(flashpix,&view_rect);
if (fpx_status != FPX_OK)
ThrowWriterException(DelegateError,"UnableToSetRegionOfInterest");
}
}
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
return(MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4787_20 |
crossvul-cpp_data_good_2521_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.127 2015/11/18 12:29:29 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 *, int, off_t, int, off_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_vaddr (size_t)((clazz == ELFCLASS32 \
? (off_t) (ph32.p_vaddr ? \
elf_getu32(swap, ph32.p_vaddr) : 4) \
: (off_t) (ph64.p_vaddr ? \
elf_getu64(swap, ph64.p_vaddr) : 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))
#define xauxv_addr (clazz == ELFCLASS32 \
? (void *)&auxv32 \
: (void *)&auxv64)
#define xauxv_sizeof (clazz == ELFCLASS32 \
? sizeof(auxv32) \
: sizeof(auxv64))
#define xauxv_type (clazz == ELFCLASS32 \
? elf_getu32(swap, auxv32.a_type) \
: elf_getu64(swap, auxv64.a_type))
#define xauxv_val (clazz == ELFCLASS32 \
? elf_getu32(swap, auxv32.a_v) \
: elf_getu64(swap, auxv64.a_v))
#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
#define FLAGS_DID_AUXV 0x200
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;
off_t ph_off = off;
int ph_num = num;
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, fd, ph_off,
ph_num, fsize);
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
/*ARGSUSED*/
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 >= 4 || descsz <= 20)) {
uint8_t desc[20];
const char *btype;
uint32_t i;
*flags |= FLAGS_DID_BUILD_ID;
switch (descsz) {
case 8:
btype = "xxHash";
break;
case 16:
btype = "md5/uuid";
break;
case 20:
btype = "sha1";
break;
default:
btype = "unknown";
break;
}
if (file_printf(ms, ", BuildID[%s]=", btype) == -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 << (int)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 off_t
get_offset_from_virtaddr(struct magic_set *ms, int swap, int clazz, int fd,
off_t off, int num, off_t fsize, uint64_t virtaddr)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
/*
* Loop through all the program headers and find the header with
* virtual address in which the "virtaddr" belongs to.
*/
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) {
file_badread(ms);
return -1;
}
off += xph_sizeof;
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Perhaps warn here */
continue;
}
if (virtaddr >= xph_vaddr && virtaddr < xph_vaddr + xph_filesz)
return xph_offset + (virtaddr - xph_vaddr);
}
return 0;
}
private size_t
get_string_on_virtaddr(struct magic_set *ms,
int swap, int clazz, int fd, off_t ph_off, int ph_num,
off_t fsize, uint64_t virtaddr, char *buf, ssize_t buflen)
{
char *bptr;
off_t offset;
if (buflen == 0)
return 0;
offset = get_offset_from_virtaddr(ms, swap, clazz, fd, ph_off, ph_num,
fsize, virtaddr);
if ((buflen = pread(fd, buf, buflen, offset)) <= 0) {
file_badread(ms);
return 0;
}
buf[buflen - 1] = '\0';
/* We expect only printable characters, so return if buffer contains
* non-printable character before the '\0' or just '\0'. */
for (bptr = buf; *bptr && isprint((unsigned char)*bptr); bptr++)
continue;
if (*bptr != '\0')
return 0;
return bptr - buf;
}
private int
do_auxv_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap, uint32_t namesz __attribute__((__unused__)),
uint32_t descsz __attribute__((__unused__)),
size_t noff __attribute__((__unused__)), size_t doff,
int *flags, size_t size __attribute__((__unused__)), int clazz,
int fd, off_t ph_off, int ph_num, off_t fsize)
{
#ifdef ELFCORE
Aux32Info auxv32;
Aux64Info auxv64;
size_t elsize = xauxv_sizeof;
const char *tag;
int is_string;
size_t nval;
if (type != NT_AUXV || (*flags & FLAGS_IS_CORE) == 0)
return 0;
*flags |= FLAGS_DID_AUXV;
nval = 0;
for (size_t off = 0; off + elsize <= descsz; off += elsize) {
(void)memcpy(xauxv_addr, &nbuf[doff + off], xauxv_sizeof);
/* Limit processing to 50 vector entries to prevent DoS */
if (nval++ >= 50) {
file_error(ms, 0, "Too many ELF Auxv elements");
return 1;
}
switch(xauxv_type) {
case AT_LINUX_EXECFN:
is_string = 1;
tag = "execfn";
break;
case AT_LINUX_PLATFORM:
is_string = 1;
tag = "platform";
break;
case AT_LINUX_UID:
is_string = 0;
tag = "real uid";
break;
case AT_LINUX_GID:
is_string = 0;
tag = "real gid";
break;
case AT_LINUX_EUID:
is_string = 0;
tag = "effective uid";
break;
case AT_LINUX_EGID:
is_string = 0;
tag = "effective gid";
break;
default:
is_string = 0;
tag = NULL;
break;
}
if (tag == NULL)
continue;
if (is_string) {
char buf[256];
ssize_t buflen;
buflen = get_string_on_virtaddr(ms, swap, clazz, fd,
ph_off, ph_num, fsize, xauxv_val, buf, sizeof(buf));
if (buflen == 0)
continue;
if (file_printf(ms, ", %s: '%s'", tag, buf) == -1)
return 0;
} else {
if (file_printf(ms, ", %s: %d", tag, (int) xauxv_val)
== -1)
return 0;
}
}
return 1;
#else
return 0;
#endif
}
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,
int fd, off_t ph_off, int ph_num, off_t fsize)
{
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 offset;
}
if ((*flags & FLAGS_DID_BUILD_ID) == 0) {
if (do_bid_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return offset;
}
if ((*flags & FLAGS_DID_NETBSD_PAX) == 0) {
if (do_pax_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return offset;
}
if ((*flags & FLAGS_DID_CORE) == 0) {
if (do_core_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags, size, clazz))
return offset;
}
if ((*flags & FLAGS_DID_AUXV) == 0) {
if (do_auxv_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags, size, clazz,
fd, ph_off, ph_num, fsize))
return offset;
}
if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) {
if (descsz > 100)
descsz = 100;
switch (xnh_type) {
case NT_NETBSD_VERSION:
return offset;
case NT_NETBSD_MARCH:
if (*flags & FLAGS_DID_NETBSD_MARCH)
return offset;
*flags |= FLAGS_DID_NETBSD_MARCH;
if (file_printf(ms, ", compiled for: %.*s",
(int)descsz, (const char *)&nbuf[doff]) == -1)
return offset;
break;
case NT_NETBSD_CMODEL:
if (*flags & FLAGS_DID_NETBSD_CMODEL)
return offset;
*flags |= FLAGS_DID_NETBSD_CMODEL;
if (file_printf(ms, ", compiler model: %.*s",
(int)descsz, (const char *)&nbuf[doff]) == -1)
return offset;
break;
default:
if (*flags & FLAGS_DID_NETBSD_UNKNOWN)
return offset;
*flags |= FLAGS_DID_NETBSD_UNKNOWN;
if (file_printf(ms, ", note=%u", xnh_type) == -1)
return offset;
break;
}
return offset;
}
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, CAST(off_t, (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 ((uintmax_t)(xsh_size + xsh_offset) >
(uintmax_t)fsize) {
if (file_printf(ms,
", note offset/size 0x%" INTMAX_T_FORMAT
"x+0x%" INTMAX_T_FORMAT "x exceeds"
" file size 0x%" INTMAX_T_FORMAT "x",
(uintmax_t)xsh_offset, (uintmax_t)xsh_size,
(uintmax_t)fsize) == -1)
return -1;
return 0;
}
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,
fd, 0, 0, 0);
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, fd, 0, 0, 0);
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|MAGIC_EXTENSION))
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-119/c/good_2521_0 |
crossvul-cpp_data_good_3011_0 | /*
* f2fs extent cache support
*
* Copyright (c) 2015 Motorola Mobility
* Copyright (c) 2015 Samsung Electronics
* Authors: Jaegeuk Kim <jaegeuk@kernel.org>
* Chao Yu <chao2.yu@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/fs.h>
#include <linux/f2fs_fs.h>
#include "f2fs.h"
#include "node.h"
#include <trace/events/f2fs.h>
static struct rb_entry *__lookup_rb_tree_fast(struct rb_entry *cached_re,
unsigned int ofs)
{
if (cached_re) {
if (cached_re->ofs <= ofs &&
cached_re->ofs + cached_re->len > ofs) {
return cached_re;
}
}
return NULL;
}
static struct rb_entry *__lookup_rb_tree_slow(struct rb_root *root,
unsigned int ofs)
{
struct rb_node *node = root->rb_node;
struct rb_entry *re;
while (node) {
re = rb_entry(node, struct rb_entry, rb_node);
if (ofs < re->ofs)
node = node->rb_left;
else if (ofs >= re->ofs + re->len)
node = node->rb_right;
else
return re;
}
return NULL;
}
struct rb_entry *__lookup_rb_tree(struct rb_root *root,
struct rb_entry *cached_re, unsigned int ofs)
{
struct rb_entry *re;
re = __lookup_rb_tree_fast(cached_re, ofs);
if (!re)
return __lookup_rb_tree_slow(root, ofs);
return re;
}
struct rb_node **__lookup_rb_tree_for_insert(struct f2fs_sb_info *sbi,
struct rb_root *root, struct rb_node **parent,
unsigned int ofs)
{
struct rb_node **p = &root->rb_node;
struct rb_entry *re;
while (*p) {
*parent = *p;
re = rb_entry(*parent, struct rb_entry, rb_node);
if (ofs < re->ofs)
p = &(*p)->rb_left;
else if (ofs >= re->ofs + re->len)
p = &(*p)->rb_right;
else
f2fs_bug_on(sbi, 1);
}
return p;
}
/*
* lookup rb entry in position of @ofs in rb-tree,
* if hit, return the entry, otherwise, return NULL
* @prev_ex: extent before ofs
* @next_ex: extent after ofs
* @insert_p: insert point for new extent at ofs
* in order to simpfy the insertion after.
* tree must stay unchanged between lookup and insertion.
*/
struct rb_entry *__lookup_rb_tree_ret(struct rb_root *root,
struct rb_entry *cached_re,
unsigned int ofs,
struct rb_entry **prev_entry,
struct rb_entry **next_entry,
struct rb_node ***insert_p,
struct rb_node **insert_parent,
bool force)
{
struct rb_node **pnode = &root->rb_node;
struct rb_node *parent = NULL, *tmp_node;
struct rb_entry *re = cached_re;
*insert_p = NULL;
*insert_parent = NULL;
*prev_entry = NULL;
*next_entry = NULL;
if (RB_EMPTY_ROOT(root))
return NULL;
if (re) {
if (re->ofs <= ofs && re->ofs + re->len > ofs)
goto lookup_neighbors;
}
while (*pnode) {
parent = *pnode;
re = rb_entry(*pnode, struct rb_entry, rb_node);
if (ofs < re->ofs)
pnode = &(*pnode)->rb_left;
else if (ofs >= re->ofs + re->len)
pnode = &(*pnode)->rb_right;
else
goto lookup_neighbors;
}
*insert_p = pnode;
*insert_parent = parent;
re = rb_entry(parent, struct rb_entry, rb_node);
tmp_node = parent;
if (parent && ofs > re->ofs)
tmp_node = rb_next(parent);
*next_entry = rb_entry_safe(tmp_node, struct rb_entry, rb_node);
tmp_node = parent;
if (parent && ofs < re->ofs)
tmp_node = rb_prev(parent);
*prev_entry = rb_entry_safe(tmp_node, struct rb_entry, rb_node);
return NULL;
lookup_neighbors:
if (ofs == re->ofs || force) {
/* lookup prev node for merging backward later */
tmp_node = rb_prev(&re->rb_node);
*prev_entry = rb_entry_safe(tmp_node, struct rb_entry, rb_node);
}
if (ofs == re->ofs + re->len - 1 || force) {
/* lookup next node for merging frontward later */
tmp_node = rb_next(&re->rb_node);
*next_entry = rb_entry_safe(tmp_node, struct rb_entry, rb_node);
}
return re;
}
bool __check_rb_tree_consistence(struct f2fs_sb_info *sbi,
struct rb_root *root)
{
#ifdef CONFIG_F2FS_CHECK_FS
struct rb_node *cur = rb_first(root), *next;
struct rb_entry *cur_re, *next_re;
if (!cur)
return true;
while (cur) {
next = rb_next(cur);
if (!next)
return true;
cur_re = rb_entry(cur, struct rb_entry, rb_node);
next_re = rb_entry(next, struct rb_entry, rb_node);
if (cur_re->ofs + cur_re->len > next_re->ofs) {
f2fs_msg(sbi->sb, KERN_INFO, "inconsistent rbtree, "
"cur(%u, %u) next(%u, %u)",
cur_re->ofs, cur_re->len,
next_re->ofs, next_re->len);
return false;
}
cur = next;
}
#endif
return true;
}
static struct kmem_cache *extent_tree_slab;
static struct kmem_cache *extent_node_slab;
static struct extent_node *__attach_extent_node(struct f2fs_sb_info *sbi,
struct extent_tree *et, struct extent_info *ei,
struct rb_node *parent, struct rb_node **p)
{
struct extent_node *en;
en = kmem_cache_alloc(extent_node_slab, GFP_ATOMIC);
if (!en)
return NULL;
en->ei = *ei;
INIT_LIST_HEAD(&en->list);
en->et = et;
rb_link_node(&en->rb_node, parent, p);
rb_insert_color(&en->rb_node, &et->root);
atomic_inc(&et->node_cnt);
atomic_inc(&sbi->total_ext_node);
return en;
}
static void __detach_extent_node(struct f2fs_sb_info *sbi,
struct extent_tree *et, struct extent_node *en)
{
rb_erase(&en->rb_node, &et->root);
atomic_dec(&et->node_cnt);
atomic_dec(&sbi->total_ext_node);
if (et->cached_en == en)
et->cached_en = NULL;
kmem_cache_free(extent_node_slab, en);
}
/*
* Flow to release an extent_node:
* 1. list_del_init
* 2. __detach_extent_node
* 3. kmem_cache_free.
*/
static void __release_extent_node(struct f2fs_sb_info *sbi,
struct extent_tree *et, struct extent_node *en)
{
spin_lock(&sbi->extent_lock);
f2fs_bug_on(sbi, list_empty(&en->list));
list_del_init(&en->list);
spin_unlock(&sbi->extent_lock);
__detach_extent_node(sbi, et, en);
}
static struct extent_tree *__grab_extent_tree(struct inode *inode)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et;
nid_t ino = inode->i_ino;
mutex_lock(&sbi->extent_tree_lock);
et = radix_tree_lookup(&sbi->extent_tree_root, ino);
if (!et) {
et = f2fs_kmem_cache_alloc(extent_tree_slab, GFP_NOFS);
f2fs_radix_tree_insert(&sbi->extent_tree_root, ino, et);
memset(et, 0, sizeof(struct extent_tree));
et->ino = ino;
et->root = RB_ROOT;
et->cached_en = NULL;
rwlock_init(&et->lock);
INIT_LIST_HEAD(&et->list);
atomic_set(&et->node_cnt, 0);
atomic_inc(&sbi->total_ext_tree);
} else {
atomic_dec(&sbi->total_zombie_tree);
list_del_init(&et->list);
}
mutex_unlock(&sbi->extent_tree_lock);
/* never died until evict_inode */
F2FS_I(inode)->extent_tree = et;
return et;
}
static struct extent_node *__init_extent_tree(struct f2fs_sb_info *sbi,
struct extent_tree *et, struct extent_info *ei)
{
struct rb_node **p = &et->root.rb_node;
struct extent_node *en;
en = __attach_extent_node(sbi, et, ei, NULL, p);
if (!en)
return NULL;
et->largest = en->ei;
et->cached_en = en;
return en;
}
static unsigned int __free_extent_tree(struct f2fs_sb_info *sbi,
struct extent_tree *et)
{
struct rb_node *node, *next;
struct extent_node *en;
unsigned int count = atomic_read(&et->node_cnt);
node = rb_first(&et->root);
while (node) {
next = rb_next(node);
en = rb_entry(node, struct extent_node, rb_node);
__release_extent_node(sbi, et, en);
node = next;
}
return count - atomic_read(&et->node_cnt);
}
static void __drop_largest_extent(struct inode *inode,
pgoff_t fofs, unsigned int len)
{
struct extent_info *largest = &F2FS_I(inode)->extent_tree->largest;
if (fofs < largest->fofs + largest->len && fofs + len > largest->fofs) {
largest->len = 0;
f2fs_mark_inode_dirty_sync(inode, true);
}
}
/* return true, if inode page is changed */
static bool __f2fs_init_extent_tree(struct inode *inode, struct f2fs_extent *i_ext)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et;
struct extent_node *en;
struct extent_info ei;
if (!f2fs_may_extent_tree(inode)) {
/* drop largest extent */
if (i_ext && i_ext->len) {
i_ext->len = 0;
return true;
}
return false;
}
et = __grab_extent_tree(inode);
if (!i_ext || !i_ext->len)
return false;
get_extent_info(&ei, i_ext);
write_lock(&et->lock);
if (atomic_read(&et->node_cnt))
goto out;
en = __init_extent_tree(sbi, et, &ei);
if (en) {
spin_lock(&sbi->extent_lock);
list_add_tail(&en->list, &sbi->extent_list);
spin_unlock(&sbi->extent_lock);
}
out:
write_unlock(&et->lock);
return false;
}
bool f2fs_init_extent_tree(struct inode *inode, struct f2fs_extent *i_ext)
{
bool ret = __f2fs_init_extent_tree(inode, i_ext);
if (!F2FS_I(inode)->extent_tree)
set_inode_flag(inode, FI_NO_EXTENT);
return ret;
}
static bool f2fs_lookup_extent_tree(struct inode *inode, pgoff_t pgofs,
struct extent_info *ei)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et = F2FS_I(inode)->extent_tree;
struct extent_node *en;
bool ret = false;
f2fs_bug_on(sbi, !et);
trace_f2fs_lookup_extent_tree_start(inode, pgofs);
read_lock(&et->lock);
if (et->largest.fofs <= pgofs &&
et->largest.fofs + et->largest.len > pgofs) {
*ei = et->largest;
ret = true;
stat_inc_largest_node_hit(sbi);
goto out;
}
en = (struct extent_node *)__lookup_rb_tree(&et->root,
(struct rb_entry *)et->cached_en, pgofs);
if (!en)
goto out;
if (en == et->cached_en)
stat_inc_cached_node_hit(sbi);
else
stat_inc_rbtree_node_hit(sbi);
*ei = en->ei;
spin_lock(&sbi->extent_lock);
if (!list_empty(&en->list)) {
list_move_tail(&en->list, &sbi->extent_list);
et->cached_en = en;
}
spin_unlock(&sbi->extent_lock);
ret = true;
out:
stat_inc_total_hit(sbi);
read_unlock(&et->lock);
trace_f2fs_lookup_extent_tree_end(inode, pgofs, ei);
return ret;
}
static struct extent_node *__try_merge_extent_node(struct inode *inode,
struct extent_tree *et, struct extent_info *ei,
struct extent_node *prev_ex,
struct extent_node *next_ex)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_node *en = NULL;
if (prev_ex && __is_back_mergeable(ei, &prev_ex->ei)) {
prev_ex->ei.len += ei->len;
ei = &prev_ex->ei;
en = prev_ex;
}
if (next_ex && __is_front_mergeable(ei, &next_ex->ei)) {
next_ex->ei.fofs = ei->fofs;
next_ex->ei.blk = ei->blk;
next_ex->ei.len += ei->len;
if (en)
__release_extent_node(sbi, et, prev_ex);
en = next_ex;
}
if (!en)
return NULL;
__try_update_largest_extent(inode, et, en);
spin_lock(&sbi->extent_lock);
if (!list_empty(&en->list)) {
list_move_tail(&en->list, &sbi->extent_list);
et->cached_en = en;
}
spin_unlock(&sbi->extent_lock);
return en;
}
static struct extent_node *__insert_extent_tree(struct inode *inode,
struct extent_tree *et, struct extent_info *ei,
struct rb_node **insert_p,
struct rb_node *insert_parent)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct rb_node **p = &et->root.rb_node;
struct rb_node *parent = NULL;
struct extent_node *en = NULL;
if (insert_p && insert_parent) {
parent = insert_parent;
p = insert_p;
goto do_insert;
}
p = __lookup_rb_tree_for_insert(sbi, &et->root, &parent, ei->fofs);
do_insert:
en = __attach_extent_node(sbi, et, ei, parent, p);
if (!en)
return NULL;
__try_update_largest_extent(inode, et, en);
/* update in global extent list */
spin_lock(&sbi->extent_lock);
list_add_tail(&en->list, &sbi->extent_list);
et->cached_en = en;
spin_unlock(&sbi->extent_lock);
return en;
}
static void f2fs_update_extent_tree_range(struct inode *inode,
pgoff_t fofs, block_t blkaddr, unsigned int len)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et = F2FS_I(inode)->extent_tree;
struct extent_node *en = NULL, *en1 = NULL;
struct extent_node *prev_en = NULL, *next_en = NULL;
struct extent_info ei, dei, prev;
struct rb_node **insert_p = NULL, *insert_parent = NULL;
unsigned int end = fofs + len;
unsigned int pos = (unsigned int)fofs;
if (!et)
return;
trace_f2fs_update_extent_tree_range(inode, fofs, blkaddr, len);
write_lock(&et->lock);
if (is_inode_flag_set(inode, FI_NO_EXTENT)) {
write_unlock(&et->lock);
return;
}
prev = et->largest;
dei.len = 0;
/*
* drop largest extent before lookup, in case it's already
* been shrunk from extent tree
*/
__drop_largest_extent(inode, fofs, len);
/* 1. lookup first extent node in range [fofs, fofs + len - 1] */
en = (struct extent_node *)__lookup_rb_tree_ret(&et->root,
(struct rb_entry *)et->cached_en, fofs,
(struct rb_entry **)&prev_en,
(struct rb_entry **)&next_en,
&insert_p, &insert_parent, false);
if (!en)
en = next_en;
/* 2. invlidate all extent nodes in range [fofs, fofs + len - 1] */
while (en && en->ei.fofs < end) {
unsigned int org_end;
int parts = 0; /* # of parts current extent split into */
next_en = en1 = NULL;
dei = en->ei;
org_end = dei.fofs + dei.len;
f2fs_bug_on(sbi, pos >= org_end);
if (pos > dei.fofs && pos - dei.fofs >= F2FS_MIN_EXTENT_LEN) {
en->ei.len = pos - en->ei.fofs;
prev_en = en;
parts = 1;
}
if (end < org_end && org_end - end >= F2FS_MIN_EXTENT_LEN) {
if (parts) {
set_extent_info(&ei, end,
end - dei.fofs + dei.blk,
org_end - end);
en1 = __insert_extent_tree(inode, et, &ei,
NULL, NULL);
next_en = en1;
} else {
en->ei.fofs = end;
en->ei.blk += end - dei.fofs;
en->ei.len -= end - dei.fofs;
next_en = en;
}
parts++;
}
if (!next_en) {
struct rb_node *node = rb_next(&en->rb_node);
next_en = rb_entry_safe(node, struct extent_node,
rb_node);
}
if (parts)
__try_update_largest_extent(inode, et, en);
else
__release_extent_node(sbi, et, en);
/*
* if original extent is split into zero or two parts, extent
* tree has been altered by deletion or insertion, therefore
* invalidate pointers regard to tree.
*/
if (parts != 1) {
insert_p = NULL;
insert_parent = NULL;
}
en = next_en;
}
/* 3. update extent in extent cache */
if (blkaddr) {
set_extent_info(&ei, fofs, blkaddr, len);
if (!__try_merge_extent_node(inode, et, &ei, prev_en, next_en))
__insert_extent_tree(inode, et, &ei,
insert_p, insert_parent);
/* give up extent_cache, if split and small updates happen */
if (dei.len >= 1 &&
prev.len < F2FS_MIN_EXTENT_LEN &&
et->largest.len < F2FS_MIN_EXTENT_LEN) {
__drop_largest_extent(inode, 0, UINT_MAX);
set_inode_flag(inode, FI_NO_EXTENT);
}
}
if (is_inode_flag_set(inode, FI_NO_EXTENT))
__free_extent_tree(sbi, et);
write_unlock(&et->lock);
}
unsigned int f2fs_shrink_extent_tree(struct f2fs_sb_info *sbi, int nr_shrink)
{
struct extent_tree *et, *next;
struct extent_node *en;
unsigned int node_cnt = 0, tree_cnt = 0;
int remained;
if (!test_opt(sbi, EXTENT_CACHE))
return 0;
if (!atomic_read(&sbi->total_zombie_tree))
goto free_node;
if (!mutex_trylock(&sbi->extent_tree_lock))
goto out;
/* 1. remove unreferenced extent tree */
list_for_each_entry_safe(et, next, &sbi->zombie_list, list) {
if (atomic_read(&et->node_cnt)) {
write_lock(&et->lock);
node_cnt += __free_extent_tree(sbi, et);
write_unlock(&et->lock);
}
f2fs_bug_on(sbi, atomic_read(&et->node_cnt));
list_del_init(&et->list);
radix_tree_delete(&sbi->extent_tree_root, et->ino);
kmem_cache_free(extent_tree_slab, et);
atomic_dec(&sbi->total_ext_tree);
atomic_dec(&sbi->total_zombie_tree);
tree_cnt++;
if (node_cnt + tree_cnt >= nr_shrink)
goto unlock_out;
cond_resched();
}
mutex_unlock(&sbi->extent_tree_lock);
free_node:
/* 2. remove LRU extent entries */
if (!mutex_trylock(&sbi->extent_tree_lock))
goto out;
remained = nr_shrink - (node_cnt + tree_cnt);
spin_lock(&sbi->extent_lock);
for (; remained > 0; remained--) {
if (list_empty(&sbi->extent_list))
break;
en = list_first_entry(&sbi->extent_list,
struct extent_node, list);
et = en->et;
if (!write_trylock(&et->lock)) {
/* refresh this extent node's position in extent list */
list_move_tail(&en->list, &sbi->extent_list);
continue;
}
list_del_init(&en->list);
spin_unlock(&sbi->extent_lock);
__detach_extent_node(sbi, et, en);
write_unlock(&et->lock);
node_cnt++;
spin_lock(&sbi->extent_lock);
}
spin_unlock(&sbi->extent_lock);
unlock_out:
mutex_unlock(&sbi->extent_tree_lock);
out:
trace_f2fs_shrink_extent_tree(sbi, node_cnt, tree_cnt);
return node_cnt + tree_cnt;
}
unsigned int f2fs_destroy_extent_node(struct inode *inode)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et = F2FS_I(inode)->extent_tree;
unsigned int node_cnt = 0;
if (!et || !atomic_read(&et->node_cnt))
return 0;
write_lock(&et->lock);
node_cnt = __free_extent_tree(sbi, et);
write_unlock(&et->lock);
return node_cnt;
}
void f2fs_drop_extent_tree(struct inode *inode)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et = F2FS_I(inode)->extent_tree;
set_inode_flag(inode, FI_NO_EXTENT);
write_lock(&et->lock);
__free_extent_tree(sbi, et);
__drop_largest_extent(inode, 0, UINT_MAX);
write_unlock(&et->lock);
}
void f2fs_destroy_extent_tree(struct inode *inode)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et = F2FS_I(inode)->extent_tree;
unsigned int node_cnt = 0;
if (!et)
return;
if (inode->i_nlink && !is_bad_inode(inode) &&
atomic_read(&et->node_cnt)) {
mutex_lock(&sbi->extent_tree_lock);
list_add_tail(&et->list, &sbi->zombie_list);
atomic_inc(&sbi->total_zombie_tree);
mutex_unlock(&sbi->extent_tree_lock);
return;
}
/* free all extent info belong to this extent tree */
node_cnt = f2fs_destroy_extent_node(inode);
/* delete extent tree entry in radix tree */
mutex_lock(&sbi->extent_tree_lock);
f2fs_bug_on(sbi, atomic_read(&et->node_cnt));
radix_tree_delete(&sbi->extent_tree_root, inode->i_ino);
kmem_cache_free(extent_tree_slab, et);
atomic_dec(&sbi->total_ext_tree);
mutex_unlock(&sbi->extent_tree_lock);
F2FS_I(inode)->extent_tree = NULL;
trace_f2fs_destroy_extent_tree(inode, node_cnt);
}
bool f2fs_lookup_extent_cache(struct inode *inode, pgoff_t pgofs,
struct extent_info *ei)
{
if (!f2fs_may_extent_tree(inode))
return false;
return f2fs_lookup_extent_tree(inode, pgofs, ei);
}
void f2fs_update_extent_cache(struct dnode_of_data *dn)
{
pgoff_t fofs;
block_t blkaddr;
if (!f2fs_may_extent_tree(dn->inode))
return;
if (dn->data_blkaddr == NEW_ADDR)
blkaddr = NULL_ADDR;
else
blkaddr = dn->data_blkaddr;
fofs = start_bidx_of_node(ofs_of_node(dn->node_page), dn->inode) +
dn->ofs_in_node;
f2fs_update_extent_tree_range(dn->inode, fofs, blkaddr, 1);
}
void f2fs_update_extent_cache_range(struct dnode_of_data *dn,
pgoff_t fofs, block_t blkaddr, unsigned int len)
{
if (!f2fs_may_extent_tree(dn->inode))
return;
f2fs_update_extent_tree_range(dn->inode, fofs, blkaddr, len);
}
void init_extent_cache_info(struct f2fs_sb_info *sbi)
{
INIT_RADIX_TREE(&sbi->extent_tree_root, GFP_NOIO);
mutex_init(&sbi->extent_tree_lock);
INIT_LIST_HEAD(&sbi->extent_list);
spin_lock_init(&sbi->extent_lock);
atomic_set(&sbi->total_ext_tree, 0);
INIT_LIST_HEAD(&sbi->zombie_list);
atomic_set(&sbi->total_zombie_tree, 0);
atomic_set(&sbi->total_ext_node, 0);
}
int __init create_extent_cache(void)
{
extent_tree_slab = f2fs_kmem_cache_create("f2fs_extent_tree",
sizeof(struct extent_tree));
if (!extent_tree_slab)
return -ENOMEM;
extent_node_slab = f2fs_kmem_cache_create("f2fs_extent_node",
sizeof(struct extent_node));
if (!extent_node_slab) {
kmem_cache_destroy(extent_tree_slab);
return -ENOMEM;
}
return 0;
}
void destroy_extent_cache(void)
{
kmem_cache_destroy(extent_node_slab);
kmem_cache_destroy(extent_tree_slab);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3011_0 |
crossvul-cpp_data_bad_507_1 | /******************************************************************************
** Copyright (c) 2017-2018, Intel Corporation **
** All rights reserved. **
** **
** Redistribution and use in source and binary forms, with or without **
** modification, are permitted provided that the following conditions **
** are met: **
** 1. Redistributions of source code must retain the above copyright **
** notice, this list of conditions and the following disclaimer. **
** 2. Redistributions in binary form must reproduce the above copyright **
** notice, this list of conditions and the following disclaimer in the **
** documentation and/or other materials provided with the distribution. **
** 3. Neither the name of the copyright holder nor the names of its **
** contributors may be used to endorse or promote products derived **
** from this software without specific prior written permission. **
** **
** THIS SOFTWARE IS PROVIDED BY THE 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 **
** HOLDER 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. **
******************************************************************************/
/* Alexander Heinecke (Intel Corp.)
******************************************************************************/
#include "edge_proxy_common.h"
void edge_sparse_csr_reader_double( const char* i_csr_file_in,
unsigned int** o_row_idx,
unsigned int** o_column_idx,
double** o_values,
unsigned int* o_row_count,
unsigned int* o_column_count,
unsigned int* o_element_count ) {
FILE *l_csr_file_handle;
const unsigned int l_line_length = 512;
char l_line[512/*l_line_length*/+1];
unsigned int l_header_read = 0;
unsigned int* l_row_idx_id = NULL;
unsigned int l_i = 0;
l_csr_file_handle = fopen( i_csr_file_in, "r" );
if ( l_csr_file_handle == NULL ) {
fprintf( stderr, "cannot open CSR file!\n" );
return;
}
while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) {
if ( strlen(l_line) == l_line_length ) {
fprintf( stderr, "could not read file length!\n" );
return;
}
/* check if we are still reading comments header */
if ( l_line[0] == '%' ) {
continue;
} else {
/* if we are the first line after comment header, we allocate our data structures */
if ( l_header_read == 0 ) {
if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) {
/* allocate CSC datastructure matching mtx file */
*o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count));
*o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1));
*o_values = (double*) malloc(sizeof(double) * (*o_element_count));
l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count));
/* check if mallocs were successful */
if ( ( *o_row_idx == NULL ) ||
( *o_column_idx == NULL ) ||
( *o_values == NULL ) ||
( l_row_idx_id == NULL ) ) {
fprintf( stderr, "could not allocate sp data!\n" );
return;
}
/* set everything to zero for init */
memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1));
memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count));
memset(*o_values, 0, sizeof(double)*(*o_element_count));
memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count));
/* init column idx */
for ( l_i = 0; l_i < (*o_row_count + 1); l_i++)
(*o_row_idx)[l_i] = (*o_element_count);
/* init */
(*o_row_idx)[0] = 0;
l_i = 0;
l_header_read = 1;
} else {
fprintf( stderr, "could not csr description!\n" );
return;
}
/* now we read the actual content */
} else {
unsigned int l_row, l_column;
double l_value;
/* read a line of content */
if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) {
fprintf( stderr, "could not read element!\n" );
return;
}
/* adjust numbers to zero termination */
l_row--;
l_column--;
/* add these values to row and value structure */
(*o_column_idx)[l_i] = l_column;
(*o_values)[l_i] = l_value;
l_i++;
/* handle columns, set id to own for this column, yeah we need to handle empty columns */
l_row_idx_id[l_row] = 1;
(*o_row_idx)[l_row+1] = l_i;
}
}
}
/* close mtx file */
fclose( l_csr_file_handle );
/* check if we read a file which was consistent */
if ( l_i != (*o_element_count) ) {
fprintf( stderr, "we were not able to read all elements!\n" );
return;
}
/* let's handle empty rows */
for ( l_i = 0; l_i < (*o_row_count); l_i++) {
if ( l_row_idx_id[l_i] == 0 ) {
(*o_row_idx)[l_i+1] = (*o_row_idx)[l_i];
}
}
/* free helper data structure */
if ( l_row_idx_id != NULL ) {
free( l_row_idx_id );
}
}
void edge_sparse_csr_reader_float( const char* i_csr_file_in,
unsigned int** o_row_idx,
unsigned int** o_column_idx,
float** o_values,
unsigned int* o_row_count,
unsigned int* o_column_count,
unsigned int* o_element_count ) {
double* l_values;
unsigned int i;
/* read using double */
edge_sparse_csr_reader_double( i_csr_file_in, o_row_idx, o_column_idx, &l_values,
o_row_count, o_column_count, o_element_count );
/* converting double values into float */
*o_values = (float*) malloc((*o_element_count)*sizeof(float));
for ( i = 0; i < (*o_element_count); ++i ) {
(*o_values)[i] = (float)l_values[i];
}
free(l_values);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_507_1 |
crossvul-cpp_data_bad_3071_0 | /*
* Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Implementation of RFC 3779 section 2.2.
*/
#include <stdio.h>
#include <stdlib.h>
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/buffer.h>
#include <openssl/x509v3.h>
#include "internal/x509_int.h"
#include "ext_dat.h"
#ifndef OPENSSL_NO_RFC3779
/*
* OpenSSL ASN.1 template translation of RFC 3779 2.2.3.
*/
ASN1_SEQUENCE(IPAddressRange) = {
ASN1_SIMPLE(IPAddressRange, min, ASN1_BIT_STRING),
ASN1_SIMPLE(IPAddressRange, max, ASN1_BIT_STRING)
} ASN1_SEQUENCE_END(IPAddressRange)
ASN1_CHOICE(IPAddressOrRange) = {
ASN1_SIMPLE(IPAddressOrRange, u.addressPrefix, ASN1_BIT_STRING),
ASN1_SIMPLE(IPAddressOrRange, u.addressRange, IPAddressRange)
} ASN1_CHOICE_END(IPAddressOrRange)
ASN1_CHOICE(IPAddressChoice) = {
ASN1_SIMPLE(IPAddressChoice, u.inherit, ASN1_NULL),
ASN1_SEQUENCE_OF(IPAddressChoice, u.addressesOrRanges, IPAddressOrRange)
} ASN1_CHOICE_END(IPAddressChoice)
ASN1_SEQUENCE(IPAddressFamily) = {
ASN1_SIMPLE(IPAddressFamily, addressFamily, ASN1_OCTET_STRING),
ASN1_SIMPLE(IPAddressFamily, ipAddressChoice, IPAddressChoice)
} ASN1_SEQUENCE_END(IPAddressFamily)
ASN1_ITEM_TEMPLATE(IPAddrBlocks) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0,
IPAddrBlocks, IPAddressFamily)
static_ASN1_ITEM_TEMPLATE_END(IPAddrBlocks)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressRange)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressOrRange)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressChoice)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressFamily)
/*
* How much buffer space do we need for a raw address?
*/
#define ADDR_RAW_BUF_LEN 16
/*
* What's the address length associated with this AFI?
*/
static int length_from_afi(const unsigned afi)
{
switch (afi) {
case IANA_AFI_IPV4:
return 4;
case IANA_AFI_IPV6:
return 16;
default:
return 0;
}
}
/*
* Extract the AFI from an IPAddressFamily.
*/
unsigned int X509v3_addr_get_afi(const IPAddressFamily *f)
{
return ((f != NULL &&
f->addressFamily != NULL && f->addressFamily->data != NULL)
? ((f->addressFamily->data[0] << 8) | (f->addressFamily->data[1]))
: 0);
}
/*
* Expand the bitstring form of an address into a raw byte array.
* At the moment this is coded for simplicity, not speed.
*/
static int addr_expand(unsigned char *addr,
const ASN1_BIT_STRING *bs,
const int length, const unsigned char fill)
{
if (bs->length < 0 || bs->length > length)
return 0;
if (bs->length > 0) {
memcpy(addr, bs->data, bs->length);
if ((bs->flags & 7) != 0) {
unsigned char mask = 0xFF >> (8 - (bs->flags & 7));
if (fill == 0)
addr[bs->length - 1] &= ~mask;
else
addr[bs->length - 1] |= mask;
}
}
memset(addr + bs->length, fill, length - bs->length);
return 1;
}
/*
* Extract the prefix length from a bitstring.
*/
#define addr_prefixlen(bs) ((int) ((bs)->length * 8 - ((bs)->flags & 7)))
/*
* i2r handler for one address bitstring.
*/
static int i2r_address(BIO *out,
const unsigned afi,
const unsigned char fill, const ASN1_BIT_STRING *bs)
{
unsigned char addr[ADDR_RAW_BUF_LEN];
int i, n;
if (bs->length < 0)
return 0;
switch (afi) {
case IANA_AFI_IPV4:
if (!addr_expand(addr, bs, 4, fill))
return 0;
BIO_printf(out, "%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]);
break;
case IANA_AFI_IPV6:
if (!addr_expand(addr, bs, 16, fill))
return 0;
for (n = 16; n > 1 && addr[n - 1] == 0x00 && addr[n - 2] == 0x00;
n -= 2) ;
for (i = 0; i < n; i += 2)
BIO_printf(out, "%x%s", (addr[i] << 8) | addr[i + 1],
(i < 14 ? ":" : ""));
if (i < 16)
BIO_puts(out, ":");
if (i == 0)
BIO_puts(out, ":");
break;
default:
for (i = 0; i < bs->length; i++)
BIO_printf(out, "%s%02x", (i > 0 ? ":" : ""), bs->data[i]);
BIO_printf(out, "[%d]", (int)(bs->flags & 7));
break;
}
return 1;
}
/*
* i2r handler for a sequence of addresses and ranges.
*/
static int i2r_IPAddressOrRanges(BIO *out,
const int indent,
const IPAddressOrRanges *aors,
const unsigned afi)
{
int i;
for (i = 0; i < sk_IPAddressOrRange_num(aors); i++) {
const IPAddressOrRange *aor = sk_IPAddressOrRange_value(aors, i);
BIO_printf(out, "%*s", indent, "");
switch (aor->type) {
case IPAddressOrRange_addressPrefix:
if (!i2r_address(out, afi, 0x00, aor->u.addressPrefix))
return 0;
BIO_printf(out, "/%d\n", addr_prefixlen(aor->u.addressPrefix));
continue;
case IPAddressOrRange_addressRange:
if (!i2r_address(out, afi, 0x00, aor->u.addressRange->min))
return 0;
BIO_puts(out, "-");
if (!i2r_address(out, afi, 0xFF, aor->u.addressRange->max))
return 0;
BIO_puts(out, "\n");
continue;
}
}
return 1;
}
/*
* i2r handler for an IPAddrBlocks extension.
*/
static int i2r_IPAddrBlocks(const X509V3_EXT_METHOD *method,
void *ext, BIO *out, int indent)
{
const IPAddrBlocks *addr = ext;
int i;
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
const unsigned int afi = X509v3_addr_get_afi(f);
switch (afi) {
case IANA_AFI_IPV4:
BIO_printf(out, "%*sIPv4", indent, "");
break;
case IANA_AFI_IPV6:
BIO_printf(out, "%*sIPv6", indent, "");
break;
default:
BIO_printf(out, "%*sUnknown AFI %u", indent, "", afi);
break;
}
if (f->addressFamily->length > 2) {
switch (f->addressFamily->data[2]) {
case 1:
BIO_puts(out, " (Unicast)");
break;
case 2:
BIO_puts(out, " (Multicast)");
break;
case 3:
BIO_puts(out, " (Unicast/Multicast)");
break;
case 4:
BIO_puts(out, " (MPLS)");
break;
case 64:
BIO_puts(out, " (Tunnel)");
break;
case 65:
BIO_puts(out, " (VPLS)");
break;
case 66:
BIO_puts(out, " (BGP MDT)");
break;
case 128:
BIO_puts(out, " (MPLS-labeled VPN)");
break;
default:
BIO_printf(out, " (Unknown SAFI %u)",
(unsigned)f->addressFamily->data[2]);
break;
}
}
switch (f->ipAddressChoice->type) {
case IPAddressChoice_inherit:
BIO_puts(out, ": inherit\n");
break;
case IPAddressChoice_addressesOrRanges:
BIO_puts(out, ":\n");
if (!i2r_IPAddressOrRanges(out,
indent + 2,
f->ipAddressChoice->
u.addressesOrRanges, afi))
return 0;
break;
}
}
return 1;
}
/*
* Sort comparison function for a sequence of IPAddressOrRange
* elements.
*
* There's no sane answer we can give if addr_expand() fails, and an
* assertion failure on externally supplied data is seriously uncool,
* so we just arbitrarily declare that if given invalid inputs this
* function returns -1. If this messes up your preferred sort order
* for garbage input, tough noogies.
*/
static int IPAddressOrRange_cmp(const IPAddressOrRange *a,
const IPAddressOrRange *b, const int length)
{
unsigned char addr_a[ADDR_RAW_BUF_LEN], addr_b[ADDR_RAW_BUF_LEN];
int prefixlen_a = 0, prefixlen_b = 0;
int r;
switch (a->type) {
case IPAddressOrRange_addressPrefix:
if (!addr_expand(addr_a, a->u.addressPrefix, length, 0x00))
return -1;
prefixlen_a = addr_prefixlen(a->u.addressPrefix);
break;
case IPAddressOrRange_addressRange:
if (!addr_expand(addr_a, a->u.addressRange->min, length, 0x00))
return -1;
prefixlen_a = length * 8;
break;
}
switch (b->type) {
case IPAddressOrRange_addressPrefix:
if (!addr_expand(addr_b, b->u.addressPrefix, length, 0x00))
return -1;
prefixlen_b = addr_prefixlen(b->u.addressPrefix);
break;
case IPAddressOrRange_addressRange:
if (!addr_expand(addr_b, b->u.addressRange->min, length, 0x00))
return -1;
prefixlen_b = length * 8;
break;
}
if ((r = memcmp(addr_a, addr_b, length)) != 0)
return r;
else
return prefixlen_a - prefixlen_b;
}
/*
* IPv4-specific closure over IPAddressOrRange_cmp, since sk_sort()
* comparison routines are only allowed two arguments.
*/
static int v4IPAddressOrRange_cmp(const IPAddressOrRange *const *a,
const IPAddressOrRange *const *b)
{
return IPAddressOrRange_cmp(*a, *b, 4);
}
/*
* IPv6-specific closure over IPAddressOrRange_cmp, since sk_sort()
* comparison routines are only allowed two arguments.
*/
static int v6IPAddressOrRange_cmp(const IPAddressOrRange *const *a,
const IPAddressOrRange *const *b)
{
return IPAddressOrRange_cmp(*a, *b, 16);
}
/*
* Calculate whether a range collapses to a prefix.
* See last paragraph of RFC 3779 2.2.3.7.
*/
static int range_should_be_prefix(const unsigned char *min,
const unsigned char *max, const int length)
{
unsigned char mask;
int i, j;
OPENSSL_assert(memcmp(min, max, length) <= 0);
for (i = 0; i < length && min[i] == max[i]; i++) ;
for (j = length - 1; j >= 0 && min[j] == 0x00 && max[j] == 0xFF; j--) ;
if (i < j)
return -1;
if (i > j)
return i * 8;
mask = min[i] ^ max[i];
switch (mask) {
case 0x01:
j = 7;
break;
case 0x03:
j = 6;
break;
case 0x07:
j = 5;
break;
case 0x0F:
j = 4;
break;
case 0x1F:
j = 3;
break;
case 0x3F:
j = 2;
break;
case 0x7F:
j = 1;
break;
default:
return -1;
}
if ((min[i] & mask) != 0 || (max[i] & mask) != mask)
return -1;
else
return i * 8 + j;
}
/*
* Construct a prefix.
*/
static int make_addressPrefix(IPAddressOrRange **result,
unsigned char *addr, const int prefixlen)
{
int bytelen = (prefixlen + 7) / 8, bitlen = prefixlen % 8;
IPAddressOrRange *aor = IPAddressOrRange_new();
if (aor == NULL)
return 0;
aor->type = IPAddressOrRange_addressPrefix;
if (aor->u.addressPrefix == NULL &&
(aor->u.addressPrefix = ASN1_BIT_STRING_new()) == NULL)
goto err;
if (!ASN1_BIT_STRING_set(aor->u.addressPrefix, addr, bytelen))
goto err;
aor->u.addressPrefix->flags &= ~7;
aor->u.addressPrefix->flags |= ASN1_STRING_FLAG_BITS_LEFT;
if (bitlen > 0) {
aor->u.addressPrefix->data[bytelen - 1] &= ~(0xFF >> bitlen);
aor->u.addressPrefix->flags |= 8 - bitlen;
}
*result = aor;
return 1;
err:
IPAddressOrRange_free(aor);
return 0;
}
/*
* Construct a range. If it can be expressed as a prefix,
* return a prefix instead. Doing this here simplifies
* the rest of the code considerably.
*/
static int make_addressRange(IPAddressOrRange **result,
unsigned char *min,
unsigned char *max, const int length)
{
IPAddressOrRange *aor;
int i, prefixlen;
if ((prefixlen = range_should_be_prefix(min, max, length)) >= 0)
return make_addressPrefix(result, min, prefixlen);
if ((aor = IPAddressOrRange_new()) == NULL)
return 0;
aor->type = IPAddressOrRange_addressRange;
OPENSSL_assert(aor->u.addressRange == NULL);
if ((aor->u.addressRange = IPAddressRange_new()) == NULL)
goto err;
if (aor->u.addressRange->min == NULL &&
(aor->u.addressRange->min = ASN1_BIT_STRING_new()) == NULL)
goto err;
if (aor->u.addressRange->max == NULL &&
(aor->u.addressRange->max = ASN1_BIT_STRING_new()) == NULL)
goto err;
for (i = length; i > 0 && min[i - 1] == 0x00; --i) ;
if (!ASN1_BIT_STRING_set(aor->u.addressRange->min, min, i))
goto err;
aor->u.addressRange->min->flags &= ~7;
aor->u.addressRange->min->flags |= ASN1_STRING_FLAG_BITS_LEFT;
if (i > 0) {
unsigned char b = min[i - 1];
int j = 1;
while ((b & (0xFFU >> j)) != 0)
++j;
aor->u.addressRange->min->flags |= 8 - j;
}
for (i = length; i > 0 && max[i - 1] == 0xFF; --i) ;
if (!ASN1_BIT_STRING_set(aor->u.addressRange->max, max, i))
goto err;
aor->u.addressRange->max->flags &= ~7;
aor->u.addressRange->max->flags |= ASN1_STRING_FLAG_BITS_LEFT;
if (i > 0) {
unsigned char b = max[i - 1];
int j = 1;
while ((b & (0xFFU >> j)) != (0xFFU >> j))
++j;
aor->u.addressRange->max->flags |= 8 - j;
}
*result = aor;
return 1;
err:
IPAddressOrRange_free(aor);
return 0;
}
/*
* Construct a new address family or find an existing one.
*/
static IPAddressFamily *make_IPAddressFamily(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi)
{
IPAddressFamily *f;
unsigned char key[3];
int keylen;
int i;
key[0] = (afi >> 8) & 0xFF;
key[1] = afi & 0xFF;
if (safi != NULL) {
key[2] = *safi & 0xFF;
keylen = 3;
} else {
keylen = 2;
}
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
f = sk_IPAddressFamily_value(addr, i);
OPENSSL_assert(f->addressFamily->data != NULL);
if (f->addressFamily->length == keylen &&
!memcmp(f->addressFamily->data, key, keylen))
return f;
}
if ((f = IPAddressFamily_new()) == NULL)
goto err;
if (f->ipAddressChoice == NULL &&
(f->ipAddressChoice = IPAddressChoice_new()) == NULL)
goto err;
if (f->addressFamily == NULL &&
(f->addressFamily = ASN1_OCTET_STRING_new()) == NULL)
goto err;
if (!ASN1_OCTET_STRING_set(f->addressFamily, key, keylen))
goto err;
if (!sk_IPAddressFamily_push(addr, f))
goto err;
return f;
err:
IPAddressFamily_free(f);
return NULL;
}
/*
* Add an inheritance element.
*/
int X509v3_addr_add_inherit(IPAddrBlocks *addr,
const unsigned afi, const unsigned *safi)
{
IPAddressFamily *f = make_IPAddressFamily(addr, afi, safi);
if (f == NULL ||
f->ipAddressChoice == NULL ||
(f->ipAddressChoice->type == IPAddressChoice_addressesOrRanges &&
f->ipAddressChoice->u.addressesOrRanges != NULL))
return 0;
if (f->ipAddressChoice->type == IPAddressChoice_inherit &&
f->ipAddressChoice->u.inherit != NULL)
return 1;
if (f->ipAddressChoice->u.inherit == NULL &&
(f->ipAddressChoice->u.inherit = ASN1_NULL_new()) == NULL)
return 0;
f->ipAddressChoice->type = IPAddressChoice_inherit;
return 1;
}
/*
* Construct an IPAddressOrRange sequence, or return an existing one.
*/
static IPAddressOrRanges *make_prefix_or_range(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi)
{
IPAddressFamily *f = make_IPAddressFamily(addr, afi, safi);
IPAddressOrRanges *aors = NULL;
if (f == NULL ||
f->ipAddressChoice == NULL ||
(f->ipAddressChoice->type == IPAddressChoice_inherit &&
f->ipAddressChoice->u.inherit != NULL))
return NULL;
if (f->ipAddressChoice->type == IPAddressChoice_addressesOrRanges)
aors = f->ipAddressChoice->u.addressesOrRanges;
if (aors != NULL)
return aors;
if ((aors = sk_IPAddressOrRange_new_null()) == NULL)
return NULL;
switch (afi) {
case IANA_AFI_IPV4:
(void)sk_IPAddressOrRange_set_cmp_func(aors, v4IPAddressOrRange_cmp);
break;
case IANA_AFI_IPV6:
(void)sk_IPAddressOrRange_set_cmp_func(aors, v6IPAddressOrRange_cmp);
break;
}
f->ipAddressChoice->type = IPAddressChoice_addressesOrRanges;
f->ipAddressChoice->u.addressesOrRanges = aors;
return aors;
}
/*
* Add a prefix.
*/
int X509v3_addr_add_prefix(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi,
unsigned char *a, const int prefixlen)
{
IPAddressOrRanges *aors = make_prefix_or_range(addr, afi, safi);
IPAddressOrRange *aor;
if (aors == NULL || !make_addressPrefix(&aor, a, prefixlen))
return 0;
if (sk_IPAddressOrRange_push(aors, aor))
return 1;
IPAddressOrRange_free(aor);
return 0;
}
/*
* Add a range.
*/
int X509v3_addr_add_range(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi,
unsigned char *min, unsigned char *max)
{
IPAddressOrRanges *aors = make_prefix_or_range(addr, afi, safi);
IPAddressOrRange *aor;
int length = length_from_afi(afi);
if (aors == NULL)
return 0;
if (!make_addressRange(&aor, min, max, length))
return 0;
if (sk_IPAddressOrRange_push(aors, aor))
return 1;
IPAddressOrRange_free(aor);
return 0;
}
/*
* Extract min and max values from an IPAddressOrRange.
*/
static int extract_min_max(IPAddressOrRange *aor,
unsigned char *min, unsigned char *max, int length)
{
if (aor == NULL || min == NULL || max == NULL)
return 0;
switch (aor->type) {
case IPAddressOrRange_addressPrefix:
return (addr_expand(min, aor->u.addressPrefix, length, 0x00) &&
addr_expand(max, aor->u.addressPrefix, length, 0xFF));
case IPAddressOrRange_addressRange:
return (addr_expand(min, aor->u.addressRange->min, length, 0x00) &&
addr_expand(max, aor->u.addressRange->max, length, 0xFF));
}
return 0;
}
/*
* Public wrapper for extract_min_max().
*/
int X509v3_addr_get_range(IPAddressOrRange *aor,
const unsigned afi,
unsigned char *min,
unsigned char *max, const int length)
{
int afi_length = length_from_afi(afi);
if (aor == NULL || min == NULL || max == NULL ||
afi_length == 0 || length < afi_length ||
(aor->type != IPAddressOrRange_addressPrefix &&
aor->type != IPAddressOrRange_addressRange) ||
!extract_min_max(aor, min, max, afi_length))
return 0;
return afi_length;
}
/*
* Sort comparison function for a sequence of IPAddressFamily.
*
* The last paragraph of RFC 3779 2.2.3.3 is slightly ambiguous about
* the ordering: I can read it as meaning that IPv6 without a SAFI
* comes before IPv4 with a SAFI, which seems pretty weird. The
* examples in appendix B suggest that the author intended the
* null-SAFI rule to apply only within a single AFI, which is what I
* would have expected and is what the following code implements.
*/
static int IPAddressFamily_cmp(const IPAddressFamily *const *a_,
const IPAddressFamily *const *b_)
{
const ASN1_OCTET_STRING *a = (*a_)->addressFamily;
const ASN1_OCTET_STRING *b = (*b_)->addressFamily;
int len = ((a->length <= b->length) ? a->length : b->length);
int cmp = memcmp(a->data, b->data, len);
return cmp ? cmp : a->length - b->length;
}
/*
* Check whether an IPAddrBLocks is in canonical form.
*/
int X509v3_addr_is_canonical(IPAddrBlocks *addr)
{
unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN];
unsigned char b_min[ADDR_RAW_BUF_LEN], b_max[ADDR_RAW_BUF_LEN];
IPAddressOrRanges *aors;
int i, j, k;
/*
* Empty extension is canonical.
*/
if (addr == NULL)
return 1;
/*
* Check whether the top-level list is in order.
*/
for (i = 0; i < sk_IPAddressFamily_num(addr) - 1; i++) {
const IPAddressFamily *a = sk_IPAddressFamily_value(addr, i);
const IPAddressFamily *b = sk_IPAddressFamily_value(addr, i + 1);
if (IPAddressFamily_cmp(&a, &b) >= 0)
return 0;
}
/*
* Top level's ok, now check each address family.
*/
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
int length = length_from_afi(X509v3_addr_get_afi(f));
/*
* Inheritance is canonical. Anything other than inheritance or
* a SEQUENCE OF IPAddressOrRange is an ASN.1 error or something.
*/
if (f == NULL || f->ipAddressChoice == NULL)
return 0;
switch (f->ipAddressChoice->type) {
case IPAddressChoice_inherit:
continue;
case IPAddressChoice_addressesOrRanges:
break;
default:
return 0;
}
/*
* It's an IPAddressOrRanges sequence, check it.
*/
aors = f->ipAddressChoice->u.addressesOrRanges;
if (sk_IPAddressOrRange_num(aors) == 0)
return 0;
for (j = 0; j < sk_IPAddressOrRange_num(aors) - 1; j++) {
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, j);
IPAddressOrRange *b = sk_IPAddressOrRange_value(aors, j + 1);
if (!extract_min_max(a, a_min, a_max, length) ||
!extract_min_max(b, b_min, b_max, length))
return 0;
/*
* Punt misordered list, overlapping start, or inverted range.
*/
if (memcmp(a_min, b_min, length) >= 0 ||
memcmp(a_min, a_max, length) > 0 ||
memcmp(b_min, b_max, length) > 0)
return 0;
/*
* Punt if adjacent or overlapping. Check for adjacency by
* subtracting one from b_min first.
*/
for (k = length - 1; k >= 0 && b_min[k]-- == 0x00; k--) ;
if (memcmp(a_max, b_min, length) >= 0)
return 0;
/*
* Check for range that should be expressed as a prefix.
*/
if (a->type == IPAddressOrRange_addressRange &&
range_should_be_prefix(a_min, a_max, length) >= 0)
return 0;
}
/*
* Check range to see if it's inverted or should be a
* prefix.
*/
j = sk_IPAddressOrRange_num(aors) - 1;
{
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, j);
if (a != NULL && a->type == IPAddressOrRange_addressRange) {
if (!extract_min_max(a, a_min, a_max, length))
return 0;
if (memcmp(a_min, a_max, length) > 0 ||
range_should_be_prefix(a_min, a_max, length) >= 0)
return 0;
}
}
}
/*
* If we made it through all that, we're happy.
*/
return 1;
}
/*
* Whack an IPAddressOrRanges into canonical form.
*/
static int IPAddressOrRanges_canonize(IPAddressOrRanges *aors,
const unsigned afi)
{
int i, j, length = length_from_afi(afi);
/*
* Sort the IPAddressOrRanges sequence.
*/
sk_IPAddressOrRange_sort(aors);
/*
* Clean up representation issues, punt on duplicates or overlaps.
*/
for (i = 0; i < sk_IPAddressOrRange_num(aors) - 1; i++) {
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, i);
IPAddressOrRange *b = sk_IPAddressOrRange_value(aors, i + 1);
unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN];
unsigned char b_min[ADDR_RAW_BUF_LEN], b_max[ADDR_RAW_BUF_LEN];
if (!extract_min_max(a, a_min, a_max, length) ||
!extract_min_max(b, b_min, b_max, length))
return 0;
/*
* Punt inverted ranges.
*/
if (memcmp(a_min, a_max, length) > 0 ||
memcmp(b_min, b_max, length) > 0)
return 0;
/*
* Punt overlaps.
*/
if (memcmp(a_max, b_min, length) >= 0)
return 0;
/*
* Merge if a and b are adjacent. We check for
* adjacency by subtracting one from b_min first.
*/
for (j = length - 1; j >= 0 && b_min[j]-- == 0x00; j--) ;
if (memcmp(a_max, b_min, length) == 0) {
IPAddressOrRange *merged;
if (!make_addressRange(&merged, a_min, b_max, length))
return 0;
(void)sk_IPAddressOrRange_set(aors, i, merged);
(void)sk_IPAddressOrRange_delete(aors, i + 1);
IPAddressOrRange_free(a);
IPAddressOrRange_free(b);
--i;
continue;
}
}
/*
* Check for inverted final range.
*/
j = sk_IPAddressOrRange_num(aors) - 1;
{
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, j);
if (a != NULL && a->type == IPAddressOrRange_addressRange) {
unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN];
if (!extract_min_max(a, a_min, a_max, length))
return 0;
if (memcmp(a_min, a_max, length) > 0)
return 0;
}
}
return 1;
}
/*
* Whack an IPAddrBlocks extension into canonical form.
*/
int X509v3_addr_canonize(IPAddrBlocks *addr)
{
int i;
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
if (f->ipAddressChoice->type == IPAddressChoice_addressesOrRanges &&
!IPAddressOrRanges_canonize(f->ipAddressChoice->
u.addressesOrRanges,
X509v3_addr_get_afi(f)))
return 0;
}
(void)sk_IPAddressFamily_set_cmp_func(addr, IPAddressFamily_cmp);
sk_IPAddressFamily_sort(addr);
OPENSSL_assert(X509v3_addr_is_canonical(addr));
return 1;
}
/*
* v2i handler for the IPAddrBlocks extension.
*/
static void *v2i_IPAddrBlocks(const struct v3_ext_method *method,
struct v3_ext_ctx *ctx,
STACK_OF(CONF_VALUE) *values)
{
static const char v4addr_chars[] = "0123456789.";
static const char v6addr_chars[] = "0123456789.:abcdefABCDEF";
IPAddrBlocks *addr = NULL;
char *s = NULL, *t;
int i;
if ((addr = sk_IPAddressFamily_new(IPAddressFamily_cmp)) == NULL) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS, ERR_R_MALLOC_FAILURE);
return NULL;
}
for (i = 0; i < sk_CONF_VALUE_num(values); i++) {
CONF_VALUE *val = sk_CONF_VALUE_value(values, i);
unsigned char min[ADDR_RAW_BUF_LEN], max[ADDR_RAW_BUF_LEN];
unsigned afi, *safi = NULL, safi_;
const char *addr_chars = NULL;
int prefixlen, i1, i2, delim, length;
if (!name_cmp(val->name, "IPv4")) {
afi = IANA_AFI_IPV4;
} else if (!name_cmp(val->name, "IPv6")) {
afi = IANA_AFI_IPV6;
} else if (!name_cmp(val->name, "IPv4-SAFI")) {
afi = IANA_AFI_IPV4;
safi = &safi_;
} else if (!name_cmp(val->name, "IPv6-SAFI")) {
afi = IANA_AFI_IPV6;
safi = &safi_;
} else {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS,
X509V3_R_EXTENSION_NAME_ERROR);
X509V3_conf_err(val);
goto err;
}
switch (afi) {
case IANA_AFI_IPV4:
addr_chars = v4addr_chars;
break;
case IANA_AFI_IPV6:
addr_chars = v6addr_chars;
break;
}
length = length_from_afi(afi);
/*
* Handle SAFI, if any, and OPENSSL_strdup() so we can null-terminate
* the other input values.
*/
if (safi != NULL) {
*safi = strtoul(val->value, &t, 0);
t += strspn(t, " \t");
if (*safi > 0xFF || *t++ != ':') {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS, X509V3_R_INVALID_SAFI);
X509V3_conf_err(val);
goto err;
}
t += strspn(t, " \t");
s = OPENSSL_strdup(t);
} else {
s = OPENSSL_strdup(val->value);
}
if (s == NULL) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS, ERR_R_MALLOC_FAILURE);
goto err;
}
/*
* Check for inheritance. Not worth additional complexity to
* optimize this (seldom-used) case.
*/
if (strcmp(s, "inherit") == 0) {
if (!X509v3_addr_add_inherit(addr, afi, safi)) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS,
X509V3_R_INVALID_INHERITANCE);
X509V3_conf_err(val);
goto err;
}
OPENSSL_free(s);
s = NULL;
continue;
}
i1 = strspn(s, addr_chars);
i2 = i1 + strspn(s + i1, " \t");
delim = s[i2++];
s[i1] = '\0';
if (a2i_ipadd(min, s) != length) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS, X509V3_R_INVALID_IPADDRESS);
X509V3_conf_err(val);
goto err;
}
switch (delim) {
case '/':
prefixlen = (int)strtoul(s + i2, &t, 10);
if (t == s + i2 || *t != '\0') {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS,
X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_err(val);
goto err;
}
if (!X509v3_addr_add_prefix(addr, afi, safi, min, prefixlen)) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS, ERR_R_MALLOC_FAILURE);
goto err;
}
break;
case '-':
i1 = i2 + strspn(s + i2, " \t");
i2 = i1 + strspn(s + i1, addr_chars);
if (i1 == i2 || s[i2] != '\0') {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS,
X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_err(val);
goto err;
}
if (a2i_ipadd(max, s + i1) != length) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS,
X509V3_R_INVALID_IPADDRESS);
X509V3_conf_err(val);
goto err;
}
if (memcmp(min, max, length_from_afi(afi)) > 0) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS,
X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_err(val);
goto err;
}
if (!X509v3_addr_add_range(addr, afi, safi, min, max)) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS, ERR_R_MALLOC_FAILURE);
goto err;
}
break;
case '\0':
if (!X509v3_addr_add_prefix(addr, afi, safi, min, length * 8)) {
X509V3err(X509V3_F_V2I_IPADDRBLOCKS, ERR_R_MALLOC_FAILURE);
goto err;
}
break;
default:
X509V3err(X509V3_F_V2I_IPADDRBLOCKS,
X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_err(val);
goto err;
}
OPENSSL_free(s);
s = NULL;
}
/*
* Canonize the result, then we're done.
*/
if (!X509v3_addr_canonize(addr))
goto err;
return addr;
err:
OPENSSL_free(s);
sk_IPAddressFamily_pop_free(addr, IPAddressFamily_free);
return NULL;
}
/*
* OpenSSL dispatch
*/
const X509V3_EXT_METHOD v3_addr = {
NID_sbgp_ipAddrBlock, /* nid */
0, /* flags */
ASN1_ITEM_ref(IPAddrBlocks), /* template */
0, 0, 0, 0, /* old functions, ignored */
0, /* i2s */
0, /* s2i */
0, /* i2v */
v2i_IPAddrBlocks, /* v2i */
i2r_IPAddrBlocks, /* i2r */
0, /* r2i */
NULL /* extension-specific data */
};
/*
* Figure out whether extension sues inheritance.
*/
int X509v3_addr_inherits(IPAddrBlocks *addr)
{
int i;
if (addr == NULL)
return 0;
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
if (f->ipAddressChoice->type == IPAddressChoice_inherit)
return 1;
}
return 0;
}
/*
* Figure out whether parent contains child.
*/
static int addr_contains(IPAddressOrRanges *parent,
IPAddressOrRanges *child, int length)
{
unsigned char p_min[ADDR_RAW_BUF_LEN], p_max[ADDR_RAW_BUF_LEN];
unsigned char c_min[ADDR_RAW_BUF_LEN], c_max[ADDR_RAW_BUF_LEN];
int p, c;
if (child == NULL || parent == child)
return 1;
if (parent == NULL)
return 0;
p = 0;
for (c = 0; c < sk_IPAddressOrRange_num(child); c++) {
if (!extract_min_max(sk_IPAddressOrRange_value(child, c),
c_min, c_max, length))
return -1;
for (;; p++) {
if (p >= sk_IPAddressOrRange_num(parent))
return 0;
if (!extract_min_max(sk_IPAddressOrRange_value(parent, p),
p_min, p_max, length))
return 0;
if (memcmp(p_max, c_max, length) < 0)
continue;
if (memcmp(p_min, c_min, length) > 0)
return 0;
break;
}
}
return 1;
}
/*
* Test whether a is a subset of b.
*/
int X509v3_addr_subset(IPAddrBlocks *a, IPAddrBlocks *b)
{
int i;
if (a == NULL || a == b)
return 1;
if (b == NULL || X509v3_addr_inherits(a) || X509v3_addr_inherits(b))
return 0;
(void)sk_IPAddressFamily_set_cmp_func(b, IPAddressFamily_cmp);
for (i = 0; i < sk_IPAddressFamily_num(a); i++) {
IPAddressFamily *fa = sk_IPAddressFamily_value(a, i);
int j = sk_IPAddressFamily_find(b, fa);
IPAddressFamily *fb;
fb = sk_IPAddressFamily_value(b, j);
if (fb == NULL)
return 0;
if (!addr_contains(fb->ipAddressChoice->u.addressesOrRanges,
fa->ipAddressChoice->u.addressesOrRanges,
length_from_afi(X509v3_addr_get_afi(fb))))
return 0;
}
return 1;
}
/*
* Validation error handling via callback.
*/
#define validation_err(_err_) \
do { \
if (ctx != NULL) { \
ctx->error = _err_; \
ctx->error_depth = i; \
ctx->current_cert = x; \
ret = ctx->verify_cb(0, ctx); \
} else { \
ret = 0; \
} \
if (!ret) \
goto done; \
} while (0)
/*
* Core code for RFC 3779 2.3 path validation.
*
* Returns 1 for success, 0 on error.
*
* When returning 0, ctx->error MUST be set to an appropriate value other than
* X509_V_OK.
*/
static int addr_validate_path_internal(X509_STORE_CTX *ctx,
STACK_OF(X509) *chain,
IPAddrBlocks *ext)
{
IPAddrBlocks *child = NULL;
int i, j, ret = 1;
X509 *x;
OPENSSL_assert(chain != NULL && sk_X509_num(chain) > 0);
OPENSSL_assert(ctx != NULL || ext != NULL);
OPENSSL_assert(ctx == NULL || ctx->verify_cb != NULL);
/*
* Figure out where to start. If we don't have an extension to
* check, we're done. Otherwise, check canonical form and
* set up for walking up the chain.
*/
if (ext != NULL) {
i = -1;
x = NULL;
} else {
i = 0;
x = sk_X509_value(chain, i);
OPENSSL_assert(x != NULL);
if ((ext = x->rfc3779_addr) == NULL)
goto done;
}
if (!X509v3_addr_is_canonical(ext))
validation_err(X509_V_ERR_INVALID_EXTENSION);
(void)sk_IPAddressFamily_set_cmp_func(ext, IPAddressFamily_cmp);
if ((child = sk_IPAddressFamily_dup(ext)) == NULL) {
X509V3err(X509V3_F_ADDR_VALIDATE_PATH_INTERNAL,
ERR_R_MALLOC_FAILURE);
ctx->error = X509_V_ERR_OUT_OF_MEM;
ret = 0;
goto done;
}
/*
* Now walk up the chain. No cert may list resources that its
* parent doesn't list.
*/
for (i++; i < sk_X509_num(chain); i++) {
x = sk_X509_value(chain, i);
OPENSSL_assert(x != NULL);
if (!X509v3_addr_is_canonical(x->rfc3779_addr))
validation_err(X509_V_ERR_INVALID_EXTENSION);
if (x->rfc3779_addr == NULL) {
for (j = 0; j < sk_IPAddressFamily_num(child); j++) {
IPAddressFamily *fc = sk_IPAddressFamily_value(child, j);
if (fc->ipAddressChoice->type != IPAddressChoice_inherit) {
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
break;
}
}
continue;
}
(void)sk_IPAddressFamily_set_cmp_func(x->rfc3779_addr,
IPAddressFamily_cmp);
for (j = 0; j < sk_IPAddressFamily_num(child); j++) {
IPAddressFamily *fc = sk_IPAddressFamily_value(child, j);
int k = sk_IPAddressFamily_find(x->rfc3779_addr, fc);
IPAddressFamily *fp =
sk_IPAddressFamily_value(x->rfc3779_addr, k);
if (fp == NULL) {
if (fc->ipAddressChoice->type ==
IPAddressChoice_addressesOrRanges) {
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
break;
}
continue;
}
if (fp->ipAddressChoice->type ==
IPAddressChoice_addressesOrRanges) {
if (fc->ipAddressChoice->type == IPAddressChoice_inherit
|| addr_contains(fp->ipAddressChoice->u.addressesOrRanges,
fc->ipAddressChoice->u.addressesOrRanges,
length_from_afi(X509v3_addr_get_afi(fc))))
sk_IPAddressFamily_set(child, j, fp);
else
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
}
}
}
/*
* Trust anchor can't inherit.
*/
OPENSSL_assert(x != NULL);
if (x->rfc3779_addr != NULL) {
for (j = 0; j < sk_IPAddressFamily_num(x->rfc3779_addr); j++) {
IPAddressFamily *fp =
sk_IPAddressFamily_value(x->rfc3779_addr, j);
if (fp->ipAddressChoice->type == IPAddressChoice_inherit
&& sk_IPAddressFamily_find(child, fp) >= 0)
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
}
}
done:
sk_IPAddressFamily_free(child);
return ret;
}
#undef validation_err
/*
* RFC 3779 2.3 path validation -- called from X509_verify_cert().
*/
int X509v3_addr_validate_path(X509_STORE_CTX *ctx)
{
return addr_validate_path_internal(ctx, ctx->chain, NULL);
}
/*
* RFC 3779 2.3 path validation of an extension.
* Test whether chain covers extension.
*/
int X509v3_addr_validate_resource_set(STACK_OF(X509) *chain,
IPAddrBlocks *ext, int allow_inheritance)
{
if (ext == NULL)
return 1;
if (chain == NULL || sk_X509_num(chain) == 0)
return 0;
if (!allow_inheritance && X509v3_addr_inherits(ext))
return 0;
return addr_validate_path_internal(NULL, chain, ext);
}
#endif /* OPENSSL_NO_RFC3779 */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3071_0 |
crossvul-cpp_data_bad_342_7 | /*
* sc.c: General functions
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#ifdef ENABLE_OPENSSL
#include <openssl/crypto.h> /* for OPENSSL_cleanse */
#endif
#include "internal.h"
#ifdef PACKAGE_VERSION
static const char *sc_version = PACKAGE_VERSION;
#else
static const char *sc_version = "(undef)";
#endif
const char *sc_get_version(void)
{
return sc_version;
}
int sc_hex_to_bin(const char *in, u8 *out, size_t *outlen)
{
int err = SC_SUCCESS;
size_t left, count = 0, in_len;
if (in == NULL || out == NULL || outlen == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
left = *outlen;
in_len = strlen(in);
while (*in != '\0') {
int byte = 0, nybbles = 2;
while (nybbles-- && *in && *in != ':' && *in != ' ') {
char c;
byte <<= 4;
c = *in++;
if ('0' <= c && c <= '9')
c -= '0';
else
if ('a' <= c && c <= 'f')
c = c - 'a' + 10;
else
if ('A' <= c && c <= 'F')
c = c - 'A' + 10;
else {
err = SC_ERROR_INVALID_ARGUMENTS;
goto out;
}
byte |= c;
}
/* Detect premature end of string before byte is complete */
if (in_len > 1 && *in == '\0' && nybbles >= 0) {
err = SC_ERROR_INVALID_ARGUMENTS;
break;
}
if (*in == ':' || *in == ' ')
in++;
if (left <= 0) {
err = SC_ERROR_BUFFER_TOO_SMALL;
break;
}
out[count++] = (u8) byte;
left--;
}
out:
*outlen = count;
return err;
}
int sc_bin_to_hex(const u8 *in, size_t in_len, char *out, size_t out_len,
int in_sep)
{
unsigned int n, sep_len;
char *pos, *end, sep;
sep = (char)in_sep;
sep_len = sep > 0 ? 1 : 0;
pos = out;
end = out + out_len;
for (n = 0; n < in_len; n++) {
if (pos + 3 + sep_len >= end)
return SC_ERROR_BUFFER_TOO_SMALL;
if (n && sep_len)
*pos++ = sep;
sprintf(pos, "%02x", in[n]);
pos += 2;
}
*pos = '\0';
return SC_SUCCESS;
}
/*
* Right trim all non-printable characters
*/
size_t sc_right_trim(u8 *buf, size_t len) {
size_t i;
if (!buf)
return 0;
if (len > 0) {
for(i = len-1; i > 0; i--) {
if(!isprint(buf[i])) {
buf[i] = '\0';
len--;
continue;
}
break;
}
}
return len;
}
u8 *ulong2bebytes(u8 *buf, unsigned long x)
{
if (buf != NULL) {
buf[3] = (u8) (x & 0xff);
buf[2] = (u8) ((x >> 8) & 0xff);
buf[1] = (u8) ((x >> 16) & 0xff);
buf[0] = (u8) ((x >> 24) & 0xff);
}
return buf;
}
u8 *ushort2bebytes(u8 *buf, unsigned short x)
{
if (buf != NULL) {
buf[1] = (u8) (x & 0xff);
buf[0] = (u8) ((x >> 8) & 0xff);
}
return buf;
}
unsigned long bebytes2ulong(const u8 *buf)
{
if (buf == NULL)
return 0UL;
return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]);
}
unsigned short bebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short) (buf[0] << 8 | buf[1]);
}
unsigned short lebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short)buf[1] << 8 | (unsigned short)buf[0];
}
void sc_init_oid(struct sc_object_id *oid)
{
int ii;
if (!oid)
return;
for (ii=0; ii<SC_MAX_OBJECT_ID_OCTETS; ii++)
oid->value[ii] = -1;
}
int sc_format_oid(struct sc_object_id *oid, const char *in)
{
int ii, ret = SC_ERROR_INVALID_ARGUMENTS;
const char *p;
char *q;
if (oid == NULL || in == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
sc_init_oid(oid);
p = in;
for (ii=0; ii < SC_MAX_OBJECT_ID_OCTETS; ii++) {
oid->value[ii] = strtol(p, &q, 10);
if (!*q)
break;
if (!(q[0] == '.' && isdigit(q[1])))
goto out;
p = q + 1;
}
if (!sc_valid_oid(oid))
goto out;
ret = SC_SUCCESS;
out:
if (ret)
sc_init_oid(oid);
return ret;
}
int sc_compare_oid(const struct sc_object_id *oid1, const struct sc_object_id *oid2)
{
int i;
if (oid1 == NULL || oid2 == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) {
if (oid1->value[i] != oid2->value[i])
return 0;
if (oid1->value[i] == -1)
break;
}
return 1;
}
int sc_valid_oid(const struct sc_object_id *oid)
{
int ii;
if (!oid)
return 0;
if (oid->value[0] == -1 || oid->value[1] == -1)
return 0;
if (oid->value[0] > 2 || oid->value[1] > 39)
return 0;
for (ii=0;ii<SC_MAX_OBJECT_ID_OCTETS;ii++)
if (oid->value[ii])
break;
if (ii==SC_MAX_OBJECT_ID_OCTETS)
return 0;
return 1;
}
int sc_detect_card_presence(sc_reader_t *reader)
{
int r;
LOG_FUNC_CALLED(reader->ctx);
if (reader->ops->detect_card_presence == NULL)
LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED);
r = reader->ops->detect_card_presence(reader);
LOG_FUNC_RETURN(reader->ctx, r);
}
int sc_path_set(sc_path_t *path, int type, const u8 *id, size_t id_len,
int idx, int count)
{
if (path == NULL || id == NULL || id_len == 0 || id_len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(path, 0, sizeof(*path));
memcpy(path->value, id, id_len);
path->len = id_len;
path->type = type;
path->index = idx;
path->count = count;
return SC_SUCCESS;
}
void sc_format_path(const char *str, sc_path_t *path)
{
int type = SC_PATH_TYPE_PATH;
if (path) {
memset(path, 0, sizeof(*path));
if (*str == 'i' || *str == 'I') {
type = SC_PATH_TYPE_FILE_ID;
str++;
}
path->len = sizeof(path->value);
if (sc_hex_to_bin(str, path->value, &path->len) >= 0) {
path->type = type;
}
path->count = -1;
}
}
int sc_append_path(sc_path_t *dest, const sc_path_t *src)
{
return sc_concatenate_path(dest, dest, src);
}
int sc_append_path_id(sc_path_t *dest, const u8 *id, size_t idlen)
{
if (dest->len + idlen > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memcpy(dest->value + dest->len, id, idlen);
dest->len += idlen;
return SC_SUCCESS;
}
int sc_append_file_id(sc_path_t *dest, unsigned int fid)
{
u8 id[2] = { fid >> 8, fid & 0xff };
return sc_append_path_id(dest, id, 2);
}
int sc_concatenate_path(sc_path_t *d, const sc_path_t *p1, const sc_path_t *p2)
{
sc_path_t tpath;
if (d == NULL || p1 == NULL || p2 == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (p1->type == SC_PATH_TYPE_DF_NAME || p2->type == SC_PATH_TYPE_DF_NAME)
/* we do not support concatenation of AIDs at the moment */
return SC_ERROR_NOT_SUPPORTED;
if (p1->len + p2->len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(&tpath, 0, sizeof(sc_path_t));
memcpy(tpath.value, p1->value, p1->len);
memcpy(tpath.value + p1->len, p2->value, p2->len);
tpath.len = p1->len + p2->len;
tpath.type = SC_PATH_TYPE_PATH;
/* use 'index' and 'count' entry of the second path object */
tpath.index = p2->index;
tpath.count = p2->count;
/* the result is currently always as path */
tpath.type = SC_PATH_TYPE_PATH;
*d = tpath;
return SC_SUCCESS;
}
const char *sc_print_path(const sc_path_t *path)
{
static char buffer[SC_MAX_PATH_STRING_SIZE + SC_MAX_AID_STRING_SIZE];
if (sc_path_print(buffer, sizeof(buffer), path) != SC_SUCCESS)
buffer[0] = '\0';
return buffer;
}
int sc_path_print(char *buf, size_t buflen, const sc_path_t *path)
{
size_t i;
if (buf == NULL || path == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (buflen < path->len * 2 + path->aid.len * 2 + 1)
return SC_ERROR_BUFFER_TOO_SMALL;
buf[0] = '\0';
if (path->aid.len) {
for (i = 0; i < path->aid.len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->aid.value[i]);
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
}
for (i = 0; i < path->len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->value[i]);
if (!path->aid.len && path->type == SC_PATH_TYPE_DF_NAME)
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
return SC_SUCCESS;
}
int sc_compare_path(const sc_path_t *path1, const sc_path_t *path2)
{
return path1->len == path2->len
&& !memcmp(path1->value, path2->value, path1->len);
}
int sc_compare_path_prefix(const sc_path_t *prefix, const sc_path_t *path)
{
sc_path_t tpath;
if (prefix->len > path->len)
return 0;
tpath = *path;
tpath.len = prefix->len;
return sc_compare_path(&tpath, prefix);
}
const sc_path_t *sc_get_mf_path(void)
{
static const sc_path_t mf_path = {
{0x3f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2,
0,
0,
SC_PATH_TYPE_PATH,
{{0},0}
};
return &mf_path;
}
int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation,
unsigned int method, unsigned long key_ref)
{
sc_acl_entry_t *p, *_new;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return SC_ERROR_INVALID_ARGUMENTS;
}
switch (method) {
case SC_AC_NEVER:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 1;
return SC_SUCCESS;
case SC_AC_NONE:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 2;
return SC_SUCCESS;
case SC_AC_UNKNOWN:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 3;
return SC_SUCCESS;
default:
/* NONE and UNKNOWN get zapped when a new AC is added.
* If the ACL is NEVER, additional entries will be
* dropped silently. */
if (file->acl[operation] == (sc_acl_entry_t *) 1)
return SC_SUCCESS;
if (file->acl[operation] == (sc_acl_entry_t *) 2
|| file->acl[operation] == (sc_acl_entry_t *) 3)
file->acl[operation] = NULL;
}
/* If the entry is already present (e.g. due to the mapping)
* of the card's AC with OpenSC's), don't add it again. */
for (p = file->acl[operation]; p != NULL; p = p->next) {
if ((p->method == method) && (p->key_ref == key_ref))
return SC_SUCCESS;
}
_new = malloc(sizeof(sc_acl_entry_t));
if (_new == NULL)
return SC_ERROR_OUT_OF_MEMORY;
_new->method = method;
_new->key_ref = key_ref;
_new->next = NULL;
p = file->acl[operation];
if (p == NULL) {
file->acl[operation] = _new;
return SC_SUCCESS;
}
while (p->next != NULL)
p = p->next;
p->next = _new;
return SC_SUCCESS;
}
const sc_acl_entry_t * sc_file_get_acl_entry(const sc_file_t *file,
unsigned int operation)
{
sc_acl_entry_t *p;
static const sc_acl_entry_t e_never = {
SC_AC_NEVER, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_none = {
SC_AC_NONE, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_unknown = {
SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return NULL;
}
p = file->acl[operation];
if (p == (sc_acl_entry_t *) 1)
return &e_never;
if (p == (sc_acl_entry_t *) 2)
return &e_none;
if (p == (sc_acl_entry_t *) 3)
return &e_unknown;
return file->acl[operation];
}
void sc_file_clear_acl_entries(sc_file_t *file, unsigned int operation)
{
sc_acl_entry_t *e;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return;
}
e = file->acl[operation];
if (e == (sc_acl_entry_t *) 1 ||
e == (sc_acl_entry_t *) 2 ||
e == (sc_acl_entry_t *) 3) {
file->acl[operation] = NULL;
return;
}
while (e != NULL) {
sc_acl_entry_t *tmp = e->next;
free(e);
e = tmp;
}
file->acl[operation] = NULL;
}
sc_file_t * sc_file_new(void)
{
sc_file_t *file = (sc_file_t *)calloc(1, sizeof(sc_file_t));
if (file == NULL)
return NULL;
file->magic = SC_FILE_MAGIC;
return file;
}
void sc_file_free(sc_file_t *file)
{
unsigned int i;
if (file == NULL || !sc_file_valid(file))
return;
file->magic = 0;
for (i = 0; i < SC_MAX_AC_OPS; i++)
sc_file_clear_acl_entries(file, i);
if (file->sec_attr)
free(file->sec_attr);
if (file->prop_attr)
free(file->prop_attr);
if (file->type_attr)
free(file->type_attr);
if (file->encoded_content)
free(file->encoded_content);
free(file);
}
void sc_file_dup(sc_file_t **dest, const sc_file_t *src)
{
sc_file_t *newf;
const sc_acl_entry_t *e;
unsigned int op;
*dest = NULL;
if (!sc_file_valid(src))
return;
newf = sc_file_new();
if (newf == NULL)
return;
*dest = newf;
memcpy(&newf->path, &src->path, sizeof(struct sc_path));
memcpy(&newf->name, &src->name, sizeof(src->name));
newf->namelen = src->namelen;
newf->type = src->type;
newf->shareable = src->shareable;
newf->ef_structure = src->ef_structure;
newf->size = src->size;
newf->id = src->id;
newf->status = src->status;
for (op = 0; op < SC_MAX_AC_OPS; op++) {
newf->acl[op] = NULL;
e = sc_file_get_acl_entry(src, op);
if (e != NULL) {
if (sc_file_add_acl_entry(newf, op, e->method, e->key_ref) < 0)
goto err;
}
}
newf->record_length = src->record_length;
newf->record_count = src->record_count;
if (sc_file_set_sec_attr(newf, src->sec_attr, src->sec_attr_len) < 0)
goto err;
if (sc_file_set_prop_attr(newf, src->prop_attr, src->prop_attr_len) < 0)
goto err;
if (sc_file_set_type_attr(newf, src->type_attr, src->type_attr_len) < 0)
goto err;
if (sc_file_set_content(newf, src->encoded_content, src->encoded_content_len) < 0)
goto err;
return;
err:
sc_file_free(newf);
*dest = NULL;
}
int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
int sc_file_set_prop_attr(sc_file_t *file, const u8 *prop_attr,
size_t prop_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (prop_attr == NULL) {
if (file->prop_attr != NULL)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->prop_attr, prop_attr_len);
if (!tmp) {
if (file->prop_attr)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->prop_attr = tmp;
memcpy(file->prop_attr, prop_attr, prop_attr_len);
file->prop_attr_len = prop_attr_len;
return SC_SUCCESS;
}
int sc_file_set_type_attr(sc_file_t *file, const u8 *type_attr,
size_t type_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (type_attr == NULL) {
if (file->type_attr != NULL)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->type_attr, type_attr_len);
if (!tmp) {
if (file->type_attr)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->type_attr = tmp;
memcpy(file->type_attr, type_attr, type_attr_len);
file->type_attr_len = type_attr_len;
return SC_SUCCESS;
}
int sc_file_set_content(sc_file_t *file, const u8 *content,
size_t content_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (content == NULL) {
if (file->encoded_content != NULL)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->encoded_content, content_len);
if (!tmp) {
if (file->encoded_content)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->encoded_content = tmp;
memcpy(file->encoded_content, content, content_len);
file->encoded_content_len = content_len;
return SC_SUCCESS;
}
int sc_file_valid(const sc_file_t *file) {
if (file == NULL)
return 0;
return file->magic == SC_FILE_MAGIC;
}
int _sc_parse_atr(sc_reader_t *reader)
{
u8 *p = reader->atr.value;
int atr_len = (int) reader->atr.len;
int n_hist, x;
int tx[4] = {-1, -1, -1, -1};
int i, FI, DI;
const int Fi_table[] = {
372, 372, 558, 744, 1116, 1488, 1860, -1,
-1, 512, 768, 1024, 1536, 2048, -1, -1 };
const int f_table[] = {
40, 50, 60, 80, 120, 160, 200, -1,
-1, 50, 75, 100, 150, 200, -1, -1 };
const int Di_table[] = {
-1, 1, 2, 4, 8, 16, 32, -1,
12, 20, -1, -1, -1, -1, -1, -1 };
reader->atr_info.hist_bytes_len = 0;
reader->atr_info.hist_bytes = NULL;
if (atr_len == 0) {
sc_log(reader->ctx, "empty ATR - card not present?\n");
return SC_ERROR_INTERNAL;
}
if (p[0] != 0x3B && p[0] != 0x3F) {
sc_log(reader->ctx, "invalid sync byte in ATR: 0x%02X\n", p[0]);
return SC_ERROR_INTERNAL;
}
n_hist = p[1] & 0x0F;
x = p[1] >> 4;
p += 2;
atr_len -= 2;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
if (tx[0] >= 0) {
reader->atr_info.FI = FI = tx[0] >> 4;
reader->atr_info.DI = DI = tx[0] & 0x0F;
reader->atr_info.Fi = Fi_table[FI];
reader->atr_info.f = f_table[FI];
reader->atr_info.Di = Di_table[DI];
} else {
reader->atr_info.Fi = -1;
reader->atr_info.f = -1;
reader->atr_info.Di = -1;
}
if (tx[2] >= 0)
reader->atr_info.N = tx[3];
else
reader->atr_info.N = -1;
while (tx[3] > 0 && tx[3] & 0xF0 && atr_len > 0) {
x = tx[3] >> 4;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
}
if (atr_len <= 0)
return SC_SUCCESS;
if (n_hist > atr_len)
n_hist = atr_len;
reader->atr_info.hist_bytes_len = n_hist;
reader->atr_info.hist_bytes = p;
return SC_SUCCESS;
}
void sc_mem_clear(void *ptr, size_t len)
{
if (len > 0) {
#ifdef ENABLE_OPENSSL
OPENSSL_cleanse(ptr, len);
#else
memset(ptr, 0, len);
#endif
}
}
int sc_mem_reverse(unsigned char *buf, size_t len)
{
unsigned char ch;
size_t ii;
if (!buf || !len)
return SC_ERROR_INVALID_ARGUMENTS;
for (ii = 0; ii < len / 2; ii++) {
ch = *(buf + ii);
*(buf + ii) = *(buf + len - 1 - ii);
*(buf + len - 1 - ii) = ch;
}
return SC_SUCCESS;
}
static int
sc_remote_apdu_allocate(struct sc_remote_data *rdata,
struct sc_remote_apdu **new_rapdu)
{
struct sc_remote_apdu *rapdu = NULL, *rr;
if (!rdata)
return SC_ERROR_INVALID_ARGUMENTS;
rapdu = calloc(1, sizeof(struct sc_remote_apdu));
if (rapdu == NULL)
return SC_ERROR_OUT_OF_MEMORY;
rapdu->apdu.data = &rapdu->sbuf[0];
rapdu->apdu.resp = &rapdu->rbuf[0];
rapdu->apdu.resplen = sizeof(rapdu->rbuf);
if (new_rapdu)
*new_rapdu = rapdu;
if (rdata->data == NULL) {
rdata->data = rapdu;
rdata->length = 1;
return SC_SUCCESS;
}
for (rr = rdata->data; rr->next; rr = rr->next)
;
rr->next = rapdu;
rdata->length++;
return SC_SUCCESS;
}
static void
sc_remote_apdu_free (struct sc_remote_data *rdata)
{
struct sc_remote_apdu *rapdu = NULL;
if (!rdata)
return;
rapdu = rdata->data;
while(rapdu) {
struct sc_remote_apdu *rr = rapdu->next;
free(rapdu);
rapdu = rr;
}
}
void sc_remote_data_init(struct sc_remote_data *rdata)
{
if (!rdata)
return;
memset(rdata, 0, sizeof(struct sc_remote_data));
rdata->alloc = sc_remote_apdu_allocate;
rdata->free = sc_remote_apdu_free;
}
static unsigned long sc_CRC_tab32[256];
static int sc_CRC_tab32_initialized = 0;
unsigned sc_crc32(const unsigned char *value, size_t len)
{
size_t ii, jj;
unsigned long crc;
unsigned long index, long_c;
if (!sc_CRC_tab32_initialized) {
for (ii=0; ii<256; ii++) {
crc = (unsigned long) ii;
for (jj=0; jj<8; jj++) {
if ( crc & 0x00000001L )
crc = ( crc >> 1 ) ^ 0xEDB88320l;
else
crc = crc >> 1;
}
sc_CRC_tab32[ii] = crc;
}
sc_CRC_tab32_initialized = 1;
}
crc = 0xffffffffL;
for (ii=0; ii<len; ii++) {
long_c = 0x000000ffL & (unsigned long) (*(value + ii));
index = crc ^ long_c;
crc = (crc >> 8) ^ sc_CRC_tab32[ index & 0xff ];
}
crc ^= 0xffffffff;
return crc%0xffff;
}
const u8 *sc_compacttlv_find_tag(const u8 *buf, size_t len, u8 tag, size_t *outlen)
{
if (buf != NULL) {
size_t idx;
u8 plain_tag = tag & 0xF0;
size_t expected_len = tag & 0x0F;
for (idx = 0; idx < len; idx++) {
if ((buf[idx] & 0xF0) == plain_tag && idx + expected_len < len &&
(expected_len == 0 || expected_len == (buf[idx] & 0x0F))) {
if (outlen != NULL)
*outlen = buf[idx] & 0x0F;
return buf + (idx + 1);
}
idx += (buf[idx] & 0x0F);
}
}
return NULL;
}
/**************************** mutex functions ************************/
int sc_mutex_create(const sc_context_t *ctx, void **mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->create_mutex != NULL)
return ctx->thread_ctx->create_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_lock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->lock_mutex != NULL)
return ctx->thread_ctx->lock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_unlock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->unlock_mutex != NULL)
return ctx->thread_ctx->unlock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_destroy(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->destroy_mutex != NULL)
return ctx->thread_ctx->destroy_mutex(mutex);
else
return SC_SUCCESS;
}
unsigned long sc_thread_id(const sc_context_t *ctx)
{
if (ctx == NULL || ctx->thread_ctx == NULL ||
ctx->thread_ctx->thread_id == NULL)
return 0UL;
else
return ctx->thread_ctx->thread_id();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_342_7 |
crossvul-cpp_data_bad_1050_2 | /* -*- coding: utf-8 -*- */
/* Copyright (C) 2000-2012 by George Williams */
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <fontforge-config.h>
#include "autotrace.h"
#include "charset.h"
#include "encoding.h"
#include "ffglib.h"
#include "fontforgeui.h"
#include "gfile.h"
#include "gkeysym.h"
#include "gresedit.h"
#include "gresource.h"
#include "groups.h"
#include "macenc.h"
#include "namelist.h"
#include "othersubrs.h"
#include "prefs.h"
#include "sfd.h"
#include "splineutil.h"
#include "ttf.h"
#include "ustring.h"
#include <dirent.h>
#include <locale.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#if HAVE_LANGINFO_H
# include <langinfo.h>
#endif
#define RAD2DEG (180/3.1415926535897932)
static void change_res_filename(const char *newname);
extern int splash;
extern int adjustwidth;
extern int adjustlbearing;
extern Encoding *default_encoding;
extern int autohint_before_generate;
extern int use_freetype_to_rasterize_fv;
extern int use_freetype_with_aa_fill_cv;
extern int OpenCharsInNewWindow;
extern int ItalicConstrained;
extern int accent_offset;
extern int GraveAcuteCenterBottom;
extern int PreferSpacingAccents;
extern int CharCenterHighest;
extern int ask_user_for_resolution;
#ifndef _NO_LIBPNG
extern int WritePNGInSFD;
#endif
extern int stop_at_join;
extern int recognizePUA;
extern float arrowAmount;
extern float arrowAccelFactor;
extern float snapdistance;
extern float snapdistancemeasuretool;
extern int measuretoolshowhorizontolvertical;
extern int snaptoint;
extern float joinsnap;
extern char *BDFFoundry;
extern char *TTFFoundry;
extern char *xuid;
extern char *SaveTablesPref;
/*struct cvshows CVShows = { 1, 1, 1, 1, 1, 0, 1 };*/ /* in charview */
/* int default_fv_font_size = 24; */ /* in fontview */
/* int default_fv_antialias = false */ /* in fontview */
/* int default_fv_bbsized = false */ /* in fontview */
extern int default_fv_row_count; /* in fontview */
extern int default_fv_col_count; /* in fontview */
extern int default_fv_showhmetrics; /* in fontview */
extern int default_fv_showvmetrics; /* in fontview */
extern int default_fv_glyphlabel; /* in fontview */
extern int save_to_dir; /* in fontview, use sfdir rather than sfd */
extern int palettes_docked; /* in cvpalettes */
extern int cvvisible[2], bvvisible[3]; /* in cvpalettes.c */
extern int maxundoes; /* in cvundoes */
extern int pref_mv_shift_and_arrow_skip; /* in metricsview.c */
extern int pref_mv_control_shift_and_arrow_skip; /* in metricsview.c */
extern int mv_type; /* in metricsview.c */
extern int prefer_cjk_encodings; /* in parsettf */
extern int onlycopydisplayed, copymetadata, copyttfinstr;
extern struct cvshows CVShows;
extern int infowindowdistance; /* in cvruler.c */
extern int oldformatstate; /* in savefontdlg.c */
extern int oldbitmapstate; /* in savefontdlg.c */
static int old_ttf_flags=0, old_otf_flags=0;
extern int old_sfnt_flags; /* in savefont.c */
extern int old_ps_flags; /* in savefont.c */
extern int old_validate; /* in savefontdlg.c */
extern int old_fontlog; /* in savefontdlg.c */
extern int oldsystem; /* in bitmapdlg.c */
extern int preferpotrace; /* in autotrace.c */
extern int autotrace_ask; /* in autotrace.c */
extern int mf_ask; /* in autotrace.c */
extern int mf_clearbackgrounds; /* in autotrace.c */
extern int mf_showerrors; /* in autotrace.c */
extern char *mf_args; /* in autotrace.c */
static int glyph_2_name_map=0; /* was in tottf.c, now a flag in savefont options dlg */
extern int coverageformatsallowed; /* in tottfgpos.c */
extern int debug_wins; /* in cvdebug.c */
extern int gridfit_dpi, gridfit_depth; /* in cvgridfit.c */
extern float gridfit_pointsizey; /* in cvgridfit.c */
extern float gridfit_pointsizex; /* in cvgridfit.c */
extern int gridfit_x_sameas_y; /* in cvgridfit.c */
extern int hint_diagonal_ends; /* in stemdb.c */
extern int hint_diagonal_intersections; /* in stemdb.c */
extern int hint_bounding_boxes; /* in stemdb.c */
extern int detect_diagonal_stems; /* in stemdb.c */
extern float stem_slope_error; /* in stemdb.c */
extern float stub_slope_error; /* in stemdb.c */
extern int instruct_diagonal_stems; /* in nowakowskittfinstr.c */
extern int instruct_serif_stems; /* in nowakowskittfinstr.c */
extern int instruct_ball_terminals; /* in nowakowskittfinstr.c */
extern int interpolate_strong; /* in nowakowskittfinstr.c */
extern int control_counters; /* in nowakowskittfinstr.c */
extern unichar_t *script_menu_names[SCRIPT_MENU_MAX];
extern char *script_filenames[SCRIPT_MENU_MAX];
static char *xdefs_filename;
extern int new_em_size; /* in splineutil2.c */
extern int new_fonts_are_order2; /* in splineutil2.c */
extern int loaded_fonts_same_as_new; /* in splineutil2.c */
extern int use_second_indic_scripts; /* in tottfgpos.c */
static char *othersubrsfile = NULL;
extern MacFeat *default_mac_feature_map, /* from macenc.c */
*user_mac_feature_map;
extern int updateflex; /* in charview.c */
extern int default_autokern_dlg; /* in lookupui.c */
extern int allow_utf8_glyphnames; /* in lookupui.c */
extern int add_char_to_name_list; /* in charinfo.c */
extern int clear_tt_instructions_when_needed; /* in cvundoes.c */
extern int export_clipboard; /* in cvundoes.c */
extern int cv_width; /* in charview.c */
extern int cv_height; /* in charview.c */
extern int cv_show_fill_with_space; /* in charview.c */
extern int interpCPsOnMotion; /* in charview.c */
extern int DrawOpenPathsWithHighlight; /* in charview.c */
extern float prefs_cvEditHandleSize; /* in charview.c */
extern int prefs_cvInactiveHandleAlpha; /* in charview.c */
extern int mv_width; /* in metricsview.c */
extern int mv_height; /* in metricsview.c */
extern int bv_width; /* in bitmapview.c */
extern int bv_height; /* in bitmapview.c */
extern int ask_user_for_cmap; /* in parsettf.c */
extern int mvshowgrid; /* in metricsview.c */
extern int rectelipse, polystar, regular_star; /* from cvpalettes.c */
extern int center_out[2]; /* from cvpalettes.c */
extern float rr_radius; /* from cvpalettes.c */
extern int ps_pointcnt; /* from cvpalettes.c */
extern float star_percent; /* from cvpalettes.c */
extern int home_char; /* from fontview.c */
extern int compact_font_on_open; /* from fontview.c */
extern int aa_pixelsize; /* from anchorsaway.c */
extern enum cvtools cv_b1_tool, cv_cb1_tool, cv_b2_tool, cv_cb2_tool; /* cvpalettes.c */
extern int show_kerning_pane_in_class; /* kernclass.c */
extern int AutoSaveFrequency; /* autosave.c */
extern int UndoRedoLimitToSave; /* sfd.c */
extern int UndoRedoLimitToLoad; /* sfd.c */
extern int prefRevisionsToRetain; /* sfd.c */
extern int prefs_cv_show_control_points_always_initially; /* from charview.c */
extern int prefs_create_dragging_comparison_outline; /* from charview.c */
extern int prefs_cv_outline_thickness; /* from charview.c */
extern float OpenTypeLoadHintEqualityTolerance; /* autohint.c */
extern float GenerateHintWidthEqualityTolerance; /* splinesave.c */
extern NameList *force_names_when_opening;
extern NameList *force_names_when_saving;
extern NameList *namelist_for_new_fonts;
extern int default_font_filter_index;
extern struct openfilefilters *user_font_filters;
static int alwaysgenapple=false, alwaysgenopentype=false;
static int gfc_showhidden, gfc_dirplace;
static char *gfc_bookmarks=NULL;
static int prefs_usecairo = true;
static int pointless;
/* These first three must match the values in macenc.c */
#define CID_Features 101
#define CID_FeatureDel 103
#define CID_FeatureEdit 105
#define CID_Mapping 102
#define CID_MappingDel 104
#define CID_MappingEdit 106
#define CID_ScriptMNameBase 200
#define CID_ScriptMFileBase (200+SCRIPT_MENU_MAX)
#define CID_ScriptMBrowseBase (200+2*SCRIPT_MENU_MAX)
#define CID_PrefsBase 1000
#define CID_PrefsOffset 100
#define CID_PrefsBrowseOffset (CID_PrefsOffset/2)
//////////////////////////////////
// The _oldval_ are used to cache the setting when the prefs window
// is created so that a redraw can be performed only when the
// value has changed.
float prefs_oldval_cvEditHandleSize = 0;
int prefs_oldval_cvInactiveHandleAlpha = 0;
/* ************************************************************************** */
/* ***************************** mac data ***************************** */
/* ************************************************************************** */
extern struct macsettingname macfeat_otftag[], *user_macfeat_otftag;
static void UserSettingsFree(void) {
free( user_macfeat_otftag );
user_macfeat_otftag = NULL;
}
static int UserSettingsDiffer(void) {
int i,j;
if ( user_macfeat_otftag==NULL )
return( false );
for ( i=0; user_macfeat_otftag[i].otf_tag!=0; ++i );
for ( j=0; macfeat_otftag[j].otf_tag!=0; ++j );
if ( i!=j )
return( true );
for ( i=0; user_macfeat_otftag[i].otf_tag!=0; ++i ) {
for ( j=0; macfeat_otftag[j].otf_tag!=0; ++j ) {
if ( macfeat_otftag[j].mac_feature_type ==
user_macfeat_otftag[i].mac_feature_type &&
macfeat_otftag[j].mac_feature_setting ==
user_macfeat_otftag[i].mac_feature_setting &&
macfeat_otftag[j].otf_tag ==
user_macfeat_otftag[i].otf_tag )
break;
}
if ( macfeat_otftag[j].otf_tag==0 )
return( true );
}
return( false );
}
/**************************************************************************** */
/* don't use mnemonics 'C' or 'O' (Cancel & OK) */
enum pref_types { pr_int, pr_real, pr_bool, pr_enum, pr_encoding, pr_string,
pr_file, pr_namelist, pr_unicode, pr_angle };
struct enums { char *name; int value; };
struct enums fvsize_enums[] = { {NULL, 0} };
#define PREFS_LIST_EMPTY { NULL, 0, NULL, NULL, NULL, '\0', NULL, 0, NULL }
static struct prefs_list {
char *name;
/* In the prefs file the untranslated name will always be used, but */
/* in the UI that name may be translated. */
enum pref_types type;
void *val;
void *(*get)(void);
void (*set)(void *);
char mn;
struct enums *enums;
unsigned int dontdisplay: 1;
char *popup;
} general_list[] = {
/* GT: The following strings have no spaces and an odd capitalization */
/* GT: this is because these strings are used in two different ways, one */
/* GT: translated (which the user sees, and should probably have added spaces,*/
/* GT: and one untranslated which needs the current odd format */
{ N_("ResourceFile"), pr_file, &xdefs_filename, NULL, NULL, 'R', NULL, 0, N_("When FontForge starts up, it loads the user interface theme from\nthis file. Any changes will only take effect the next time you start FontForge.") },
{ N_("OtherSubrsFile"), pr_file, &othersubrsfile, NULL, NULL, 'O', NULL, 0, N_("If you wish to replace Adobe's OtherSubrs array (for Type1 fonts)\nwith an array of your own, set this to point to a file containing\na list of up to 14 PostScript subroutines. Each subroutine must\nbe preceded by a line starting with '%%%%' (any text before the\nfirst '%%%%' line will be treated as an initial copyright notice).\nThe first three subroutines are for flex hints, the next for hint\nsubstitution (this MUST be present), the 14th (or 13 as the\nnumbering actually starts with 0) is for counter hints.\nThe subroutines should not be enclosed in a [ ] pair.") },
{ N_("FreeTypeInFontView"), pr_bool, &use_freetype_to_rasterize_fv, NULL, NULL, 'O', NULL, 0, N_("Use the FreeType rasterizer (when available)\nto rasterize glyphs in the font view.\nThis generally results in better quality.") },
{ N_("FreeTypeAAFillInOutlineView"), pr_bool, &use_freetype_with_aa_fill_cv, NULL, NULL, 'O', NULL, 0, N_("When filling using freetype in the outline view,\nhave freetype render the glyph antialiased.") },
{ N_("SplashScreen"), pr_bool, &splash, NULL, NULL, 'S', NULL, 0, N_("Show splash screen on start-up") },
#ifndef _NO_LIBCAIRO
{ N_("UseCairoDrawing"), pr_bool, &prefs_usecairo, NULL, NULL, '\0', NULL, 0, N_("Use the cairo library for drawing (if available)\nThis makes for prettier (anti-aliased) but slower drawing\nThis applies to any windows created AFTER this is set.\nAlready existing windows will continue as they are.") },
#endif
{ N_("ExportClipboard"), pr_bool, &export_clipboard, NULL, NULL, '\0', NULL, 0, N_( "If you are running an X11 clipboard manager you might want\nto turn this off. FF can put things into its internal clipboard\nwhich it cannot export to X11 (things like copying more than\none glyph in the fontview). If you have a clipboard manager\nrunning it will force these to be exported with consequent\nloss of data.") },
{ N_("AutoSaveFrequency"), pr_int, &AutoSaveFrequency, NULL, NULL, '\0', NULL, 0, N_( "The number of seconds between autosaves. If you set this to 0 there will be no autosaves.") },
{ N_("RevisionsToRetain"), pr_int, &prefRevisionsToRetain, NULL, NULL, '\0', NULL, 0, N_( "When Saving, keep this number of previous versions of the file. file.sfd-01 will be the last saved file, file.sfd-02 will be the file saved before that, and so on. If you set this to 0 then no revisions will be retained.") },
{ N_("UndoRedoLimitToSave"), pr_int, &UndoRedoLimitToSave, NULL, NULL, '\0', NULL, 0, N_( "The number of undo and redo operations which will be saved in sfd files.\nIf you set this to 0 undo/redo information is not saved to sfd files.\nIf set to -1 then all available undo/redo information is saved without limit.") },
PREFS_LIST_EMPTY
},
new_list[] = {
{ N_("NewCharset"), pr_encoding, &default_encoding, NULL, NULL, 'N', NULL, 0, N_("Default encoding for\nnew fonts") },
{ N_("NewEmSize"), pr_int, &new_em_size, NULL, NULL, 'S', NULL, 0, N_("The default size of the Em-Square in a newly created font.") },
{ N_("NewFontsQuadratic"), pr_bool, &new_fonts_are_order2, NULL, NULL, 'Q', NULL, 0, N_("Whether new fonts should contain splines of quadratic (truetype)\nor cubic (postscript & opentype).") },
{ N_("LoadedFontsAsNew"), pr_bool, &loaded_fonts_same_as_new, NULL, NULL, 'L', NULL, 0, N_("Whether fonts loaded from the disk should retain their splines\nwith the original order (quadratic or cubic), or whether the\nsplines should be converted to the default order for new fonts\n(see NewFontsQuadratic).") },
PREFS_LIST_EMPTY
},
open_list[] = {
{ N_("PreferCJKEncodings"), pr_bool, &prefer_cjk_encodings, NULL, NULL, 'C', NULL, 0, N_("When loading a truetype or opentype font which has both a unicode\nand a CJK encoding table, use this flag to specify which\nshould be loaded for the font.") },
{ N_("AskUserForCMap"), pr_bool, &ask_user_for_cmap, NULL, NULL, 'O', NULL, 0, N_("When loading a font in sfnt format (TrueType, OpenType, etc.),\nask the user to specify which cmap to use initially.") },
{ N_("PreserveTables"), pr_string, &SaveTablesPref, NULL, NULL, 'P', NULL, 0, N_("Enter a list of 4 letter table tags, separated by commas.\nFontForge will make a binary copy of these tables when it\nloads a True/OpenType font, and will output them (unchanged)\nwhen it generates the font. Do not include table tags which\nFontForge thinks it understands.") },
{ N_("SeekCharacter"), pr_unicode, &home_char, NULL, NULL, '\0', NULL, 0, N_("When fontforge opens a (non-sfd) font it will try to display this unicode character in the fontview.")},
{ N_("CompactOnOpen"), pr_bool, &compact_font_on_open, NULL, NULL, 'O', NULL, 0, N_("When a font is opened, should it be made compact?")},
{ N_("UndoRedoLimitToLoad"), pr_int, &UndoRedoLimitToLoad, NULL, NULL, '\0', NULL, 0, N_( "The number of undo and redo operations to load from sfd files.\nWith this option you can disregard undo information while loading SFD files.\nIf set to 0 then no undo/redo information is loaded.\nIf set to -1 then all available undo/redo information is loaded without limit.") },
{ N_("OpenTypeLoadHintEqualityTolerance"), pr_real, &OpenTypeLoadHintEqualityTolerance, NULL, NULL, '\0', NULL, 0, N_( "When importing an OpenType font, for the purposes of hinting spline points might not exactly match boundaries. For example, a point might be -0.0002 instead of exactly 0\nThis setting gives the user some control over this allowing a small tolerance value to be fed into the OpenType loading code.\nComparisons are then not performed for raw equality but for equality within tolerance (e.g., values within the range -0.0002 to 0.0002 will be considered equal to 0 when figuring out hints).") },
PREFS_LIST_EMPTY
},
navigation_list[] = {
{ N_("GlyphAutoGoto"), pr_bool, &cv_auto_goto, NULL, NULL, '\0', NULL, 0, N_("Typing a normal character in the glyph view window changes the window to look at that character.\nEnabling GlyphAutoGoto will disable the shortcut where holding just the ` key will enable Preview mode as long as the key is held.") },
{ N_("OpenCharsInNewWindow"), pr_bool, &OpenCharsInNewWindow, NULL, NULL, '\0', NULL, 0, N_("When double clicking on a character in the font view\nopen that character in a new window, otherwise\nreuse an existing one.") },
PREFS_LIST_EMPTY
},
editing_list[] = {
{ N_("ItalicConstrained"), pr_bool, &ItalicConstrained, NULL, NULL, '\0', NULL, 0, N_("In the Outline View, the Shift key constrains motion to be parallel to the ItalicAngle rather than constraining it to be vertical.") },
{ N_("InterpolateCPsOnMotion"), pr_bool, &interpCPsOnMotion, NULL, NULL, '\0', NULL, 0, N_("When moving one end point of a spline but not the other\ninterpolate the control points between the two.") },
{ N_("SnapDistance"), pr_real, &snapdistance, NULL, NULL, '\0', NULL, 0, N_("When the mouse pointer is within this many pixels\nof one of the various interesting features (baseline,\nwidth, grid splines, etc.) the pointer will snap\nto that feature.") },
{ N_("SnapDistanceMeasureTool"), pr_real, &snapdistancemeasuretool, NULL, NULL, '\0', NULL, 0, N_("When the measure tool is active and when the mouse pointer is within this many pixels\nof one of the various interesting features (baseline,\nwidth, grid splines, etc.) the pointer will snap\nto that feature.") },
{ N_("SnapToInt"), pr_bool, &snaptoint, NULL, NULL, '\0', NULL, 0, N_("When the user clicks in the editing window, round the location to the nearest integers.") },
{ N_("StopAtJoin"), pr_bool, &stop_at_join, NULL, NULL, '\0', NULL, 0, N_("When dragging points in the outline view a join may occur\n(two open contours may connect at their endpoints). When\nthis is On a join will cause FontForge to stop moving the\nselection (as if the user had released the mouse button).\nThis is handy if your fingers are inclined to wiggle a bit.") },
{ N_("JoinSnap"), pr_real, &joinsnap, NULL, NULL, '\0', NULL, 0, N_("The Edit->Join command will join points which are this close together\nA value of 0 means they must be coincident") },
{ N_("CopyMetaData"), pr_bool, ©metadata, NULL, NULL, '\0', NULL, 0, N_("When copying glyphs from the font view, also copy the\nglyphs' metadata (name, encoding, comment, etc).") },
{ N_("UndoDepth"), pr_int, &maxundoes, NULL, NULL, '\0', NULL, 0, N_("The maximum number of Undoes/Redoes stored in a glyph. Use -1 for infinite Undoes\n(but watch RAM consumption and use the Edit menu's Remove Undoes as needed)") },
{ N_("UpdateFlex"), pr_bool, &updateflex, NULL, NULL, '\0', NULL, 0, N_("Figure out flex hints after every change") },
{ N_("AutoKernDialog"), pr_bool, &default_autokern_dlg, NULL, NULL, '\0', NULL, 0, N_("Open AutoKern dialog for new kerning subtables") },
{ N_("MetricsShiftSkip"), pr_int, &pref_mv_shift_and_arrow_skip, NULL, NULL, '\0', NULL, 0, N_("Number of units to increment/decrement a table value by in the metrics window when shift is held") },
{ N_("MetricsControlShiftSkip"), pr_int, &pref_mv_control_shift_and_arrow_skip, NULL, NULL, '\0', NULL, 0, N_("Number of units to increment/decrement a table value by in the metrics window when both control and shift is held") },
PREFS_LIST_EMPTY
},
editing_interface_list[] = {
{ N_("ArrowMoveSize"), pr_real, &arrowAmount, NULL, NULL, '\0', NULL, 0, N_("The number of em-units by which an arrow key will move a selected point") },
{ N_("ArrowAccelFactor"), pr_real, &arrowAccelFactor, NULL, NULL, '\0', NULL, 0, N_("Holding down the Shift key will speed up arrow key motion by this factor") },
{ N_("DrawOpenPathsWithHighlight"), pr_bool, &DrawOpenPathsWithHighlight, NULL, NULL, '\0', NULL, 0, N_("Open paths should be drawn in a special highlight color to make them more apparent.") },
{ N_("MeasureToolShowHorizontalVertical"), pr_bool, &measuretoolshowhorizontolvertical, NULL, NULL, '\0', NULL, 0, N_("Have the measure tool show horizontal and vertical distances on the canvas.") },
{ N_("EditHandleSize"), pr_real, &prefs_cvEditHandleSize, NULL, NULL, '\0', NULL, 0, N_("The size of the handles showing control points and other interesting points in the glyph editor (default is 5).") },
{ N_("InactiveHandleAlpha"), pr_int, &prefs_cvInactiveHandleAlpha, NULL, NULL, '\0', NULL, 0, N_("Inactive handles in the glyph editor will be drawn with this alpha value (range: 0-255 default is 255).") },
{ N_("ShowControlPointsAlways"), pr_bool, &prefs_cv_show_control_points_always_initially, NULL, NULL, '\0', NULL, 0, N_("Always show the control points when editing a glyph.\nThis can be turned off in the menu View/Show, this setting will effect if control points are shown initially.\nChange requires a restart of fontforge.") },
{ N_("ShowFillWithSpace"), pr_bool, &cv_show_fill_with_space, NULL, NULL, '\0', NULL, 0, N_("Also enable preview mode when the space bar is pressed.") },
{ N_("OutlineThickness"), pr_int, &prefs_cv_outline_thickness, NULL, NULL, '\0', NULL, 0, N_("Setting above 1 will cause a thick outline to be drawn for glyph paths\n which is only extended inwards from the edge of the glyph.\n See also the ForegroundThickOutlineColor Resource for the color of this outline.") },
PREFS_LIST_EMPTY
},
sync_list[] = {
{ N_("AutoWidthSync"), pr_bool, &adjustwidth, NULL, NULL, '\0', NULL, 0, N_("Changing the width of a glyph\nchanges the widths of all accented\nglyphs based on it.") },
{ N_("AutoLBearingSync"), pr_bool, &adjustlbearing, NULL, NULL, '\0', NULL, 0, N_("Changing the left side bearing\nof a glyph adjusts the lbearing\nof other references in all accented\nglyphs based on it.") },
PREFS_LIST_EMPTY
},
tt_list[] = {
{ N_("ClearInstrsBigChanges"), pr_bool, &clear_tt_instructions_when_needed, NULL, NULL, 'C', NULL, 0, N_("Instructions in a TrueType font refer to\npoints by number, so if you edit a glyph\nin such a way that some points have different\nnumbers (add points, remove them, etc.) then\nthe instructions will be applied to the wrong\npoints with disasterous results.\n Normally FontForge will remove the instructions\nif it detects that the points have been renumbered\nin order to avoid the above problem. You may turn\nthis behavior off -- but be careful!") },
{ N_("CopyTTFInstrs"), pr_bool, ©ttfinstr, NULL, NULL, '\0', NULL, 0, N_("When copying glyphs from the font view, also copy the\nglyphs' truetype instructions.") },
PREFS_LIST_EMPTY
},
accent_list[] = {
{ N_("AccentOffsetPercent"), pr_int, &accent_offset, NULL, NULL, '\0', NULL, 0, N_("The percentage of an em by which an accent is offset from its base glyph in Build Accent") },
{ N_("AccentCenterLowest"), pr_bool, &GraveAcuteCenterBottom, NULL, NULL, '\0', NULL, 0, N_("When placing grave and acute accents above letters, should\nFontForge center them based on their full width, or\nshould it just center based on the lowest point\nof the accent.") },
{ N_("CharCenterHighest"), pr_bool, &CharCenterHighest, NULL, NULL, '\0', NULL, 0, N_("When centering an accent over a glyph, should the accent\nbe centered on the highest point(s) of the glyph,\nor the middle of the glyph?") },
{ N_("PreferSpacingAccents"), pr_bool, &PreferSpacingAccents, NULL, NULL, '\0', NULL, 0, N_("Use spacing accents (Unicode: 02C0-02FF) rather than\ncombining accents (Unicode: 0300-036F) when\nbuilding accented glyphs.") },
PREFS_LIST_EMPTY
},
args_list[] = {
{ N_("PreferPotrace"), pr_bool, &preferpotrace, NULL, NULL, '\0', NULL, 0, N_("FontForge supports two different helper applications to do autotracing\n autotrace and potrace\nIf your system only has one it will use that one, if you have both\nuse this option to tell FontForge which to pick.") },
{ N_("AutotraceArgs"), pr_string, NULL, GetAutoTraceArgs, SetAutoTraceArgs, '\0', NULL, 0, N_("Extra arguments for configuring the autotrace program\n(either autotrace or potrace)") },
{ N_("AutotraceAsk"), pr_bool, &autotrace_ask, NULL, NULL, '\0', NULL, 0, N_("Ask the user for autotrace arguments each time autotrace is invoked") },
{ N_("MfArgs"), pr_string, &mf_args, NULL, NULL, '\0', NULL, 0, N_("Commands to pass to mf (metafont) program, the filename will follow these") },
{ N_("MfAsk"), pr_bool, &mf_ask, NULL, NULL, '\0', NULL, 0, N_("Ask the user for mf commands each time mf is invoked") },
{ N_("MfClearBg"), pr_bool, &mf_clearbackgrounds, NULL, NULL, '\0', NULL, 0, N_("FontForge loads large images into the background of each glyph\nprior to autotracing them. You may retain those\nimages to look at after mf processing is complete, or\nremove them to save space") },
{ N_("MfShowErr"), pr_bool, &mf_showerrors, NULL, NULL, '\0', NULL, 0, N_("MetaFont (mf) generates lots of verbiage to stdout.\nMost of the time I find it an annoyance but it is\nimportant to see if something goes wrong.") },
PREFS_LIST_EMPTY
},
fontinfo_list[] = {
{ N_("FoundryName"), pr_string, &BDFFoundry, NULL, NULL, 'F', NULL, 0, N_("Name used for foundry field in bdf\nfont generation") },
{ N_("TTFFoundry"), pr_string, &TTFFoundry, NULL, NULL, 'T', NULL, 0, N_("Name used for Vendor ID field in\nttf (OS/2 table) font generation.\nMust be no more than 4 characters") },
{ N_("NewFontNameList"), pr_namelist, &namelist_for_new_fonts, NULL, NULL, '\0', NULL, 0, N_("FontForge will use this namelist when assigning\nglyph names to code points in a new font.") },
{ N_("RecognizePUANames"), pr_bool, &recognizePUA, NULL, NULL, 'U', NULL, 0, N_("Once upon a time, Adobe assigned PUA (public use area) encodings\nfor many stylistic variants of characters (small caps, old style\nnumerals, etc.). Adobe no longer believes this to be a good idea,\nand recommends that these encodings be ignored.\n\n The assignments were originally made because most applications\ncould not handle OpenType features for accessing variants. Adobe\nnow believes that all apps that matter can now do so. Applications\nlike Word and OpenOffice still can't handle these features, so\n fontforge's default behavior is to ignore Adobe's current\nrecommendations.\n\nNote: This does not affect figuring out unicode from the font's encoding,\nit just controls determining unicode from a name.") },
{ N_("UnicodeGlyphNames"), pr_bool, &allow_utf8_glyphnames, NULL, NULL, 'O', NULL, 0, N_("Allow the full unicode character set in glyph names.\nThis does not conform to adobe's glyph name standard.\nSuch names should be for internal use only and\nshould NOT end up in production fonts." ) },
{ N_("AddCharToNameList"), pr_bool, &add_char_to_name_list, NULL, NULL, 'O', NULL, 0, N_( "When displaying a list of glyph names\n(or sometimes just a single glyph name)\nFontForge will add the unicode character\nthe name refers to in parenthesis after\nthe name. It does this because some names\nare obscure.\nSome people would prefer not to see this,\nso this preference item lets you turn off\n this behavior" ) },
PREFS_LIST_EMPTY
},
generate_list[] = {
{ N_("AskBDFResolution"), pr_bool, &ask_user_for_resolution, NULL, NULL, 'B', NULL, 0, N_("When generating a set of BDF fonts ask the user\nto specify the screen resolution of the fonts\notherwise FontForge will guess depending on the pixel size.") },
{ N_("AutoHint"), pr_bool, &autohint_before_generate, NULL, NULL, 'H', NULL, 0, N_("AutoHint changed glyphs before generating a font") },
#ifndef _NO_LIBPNG
{ N_("WritePNGInSFD"), pr_bool, &WritePNGInSFD, NULL, NULL, 'B', NULL, 0, N_("If your SFD contains images, write them as PNG; this results in smaller SFDs; but was not supported in FontForge versions compiled before July 2019, so older FontForge versions cannot read them.") },
#endif
{ N_("GenerateHintWidthEqualityTolerance"), pr_real, &GenerateHintWidthEqualityTolerance, NULL, NULL, '\0', NULL, 0, N_( "When generating a font, ignore slight rounding errors for hints that should be at the top or bottom of the glyph. For example, you might like to set this to 0.02 so that 19.999 will be considered 20. But only for the hint width value.") },
PREFS_LIST_EMPTY
},
hints_list[] = {
{ N_("StandardSlopeError"), pr_angle, &stem_slope_error, NULL, NULL, '\0', NULL, 0, N_("The maximum slope difference which still allows to consider two points \"parallel\".\nEnlarge this to make the autohinter more tolerable to small deviations from straight lines when detecting stem edges.") },
{ N_("SerifSlopeError"), pr_angle, &stub_slope_error, NULL, NULL, '\0', NULL, 0, N_("Same as above, but for terminals of small features (e. g. serifs), which can deviate more significantly from the horizontal or vertical direction.") },
{ N_("HintBoundingBoxes"), pr_bool, &hint_bounding_boxes, NULL, NULL, '\0', NULL, 0, N_("FontForge will place vertical or horizontal hints to describe the bounding boxes of suitable glyphs.") },
{ N_("HintDiagonalEnds"), pr_bool, &hint_diagonal_ends, NULL, NULL, '\0', NULL, 0, N_("FontForge will place vertical or horizontal hints at the ends of diagonal stems.") },
{ N_("HintDiagonalInter"), pr_bool, &hint_diagonal_intersections, NULL, NULL, '\0', NULL, 0, N_("FontForge will place vertical or horizontal hints at the intersections of diagonal stems.") },
{ N_("DetectDiagonalStems"), pr_bool, &detect_diagonal_stems, NULL, NULL, '\0', NULL, 0, N_("FontForge will generate diagonal stem hints, which then can be used by the AutoInstr command.") },
PREFS_LIST_EMPTY
},
instrs_list[] = {
{ N_("InstructDiagonalStems"), pr_bool, &instruct_diagonal_stems, NULL, NULL, '\0', NULL, 0, N_("Generate instructions for diagonal stem hints.") },
{ N_("InstructSerifs"), pr_bool, &instruct_serif_stems, NULL, NULL, '\0', NULL, 0, N_("Try to detect serifs and other elements protruding from base stems and generate instructions for them.") },
{ N_("InstructBallTerminals"), pr_bool, &instruct_ball_terminals, NULL, NULL, '\0', NULL, 0, N_("Generate instructions for ball terminals.") },
{ N_("InterpolateStrongPoints"), pr_bool, &interpolate_strong, NULL, NULL, '\0', NULL, 0, N_("Interpolate between stem edges some important points, not affected by other instructions.") },
{ N_("CounterControl"), pr_bool, &control_counters, NULL, NULL, '\0', NULL, 0, N_("Make sure similar or equal counters remain the same in gridfitted outlines.\nEnabling this option may result in glyph advance widths being\ninconsistently scaled at some PPEMs.") },
PREFS_LIST_EMPTY
},
opentype_list[] = {
{ N_("UseNewIndicScripts"), pr_bool, &use_second_indic_scripts, NULL, NULL, 'C', NULL, 0, N_("MS has changed (in August 2006) the inner workings of their Indic shaping\nengine, and to disambiguate this change has created a parallel set of script\ntags (generally ending in '2') for Indic writing systems. If you are working\nwith the new system set this flag, if you are working with the old unset it.\n(if you aren't doing Indic work, this flag is irrelevant).") },
PREFS_LIST_EMPTY
},
/* These are hidden, so will never appear in preference ui, hence, no "N_(" */
/* They are controled elsewhere AntiAlias is a menu item in the font window's View menu */
/* etc. */
hidden_list[] = {
{ "AntiAlias", pr_bool, &default_fv_antialias, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultFVShowHmetrics", pr_int, &default_fv_showhmetrics, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultFVShowVmetrics", pr_int, &default_fv_showvmetrics, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultFVSize", pr_int, &default_fv_font_size, NULL, NULL, 'S', NULL, 1, NULL },
{ "DefaultFVRowCount", pr_int, &default_fv_row_count, NULL, NULL, 'S', NULL, 1, NULL },
{ "DefaultFVColCount", pr_int, &default_fv_col_count, NULL, NULL, 'S', NULL, 1, NULL },
{ "DefaultFVGlyphLabel", pr_int, &default_fv_glyphlabel, NULL, NULL, 'S', NULL, 1, NULL },
{ "SaveToDir", pr_int, &save_to_dir, NULL, NULL, 'S', NULL, 1, NULL },
{ "OnlyCopyDisplayed", pr_bool, &onlycopydisplayed, NULL, NULL, '\0', NULL, 1, NULL },
{ "PalettesDocked", pr_bool, &palettes_docked, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultCVWidth", pr_int, &cv_width, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultCVHeight", pr_int, &cv_height, NULL, NULL, '\0', NULL, 1, NULL },
{ "CVVisible0", pr_bool, &cvvisible[0], NULL, NULL, '\0', NULL, 1, NULL },
{ "CVVisible1", pr_bool, &cvvisible[1], NULL, NULL, '\0', NULL, 1, NULL },
{ "BVVisible0", pr_bool, &bvvisible[0], NULL, NULL, '\0', NULL, 1, NULL },
{ "BVVisible1", pr_bool, &bvvisible[1], NULL, NULL, '\0', NULL, 1, NULL },
{ "BVVisible2", pr_bool, &bvvisible[2], NULL, NULL, '\0', NULL, 1, NULL },
{ "MarkExtrema", pr_int, &CVShows.markextrema, NULL, NULL, '\0', NULL, 1, NULL },
{ "MarkPointsOfInflect", pr_int, &CVShows.markpoi, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowRulers", pr_bool, &CVShows.showrulers, NULL, NULL, '\0', NULL, 1, N_("Display rulers in the Outline Glyph View") },
{ "ShowCPInfo", pr_int, &CVShows.showcpinfo, NULL, NULL, '\0', NULL, 1, NULL },
{ "CreateDraggingComparisonOutline", pr_int, &prefs_create_dragging_comparison_outline, NULL, NULL, '\0', NULL, 1, NULL },
{ "InfoWindowDistance", pr_int, &infowindowdistance, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowSideBearings", pr_int, &CVShows.showsidebearings, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowRefNames", pr_int, &CVShows.showrefnames, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowPoints", pr_bool, &CVShows.showpoints, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowFilled", pr_int, &CVShows.showfilled, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowTabs", pr_int, &CVShows.showtabs, NULL, NULL, '\0', NULL, 1, NULL },
{ "SnapOutlines", pr_int, &CVShows.snapoutlines, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowAlmostHVLines", pr_bool, &CVShows.showalmosthvlines, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowAlmostHVCurves", pr_bool, &CVShows.showalmosthvcurves, NULL, NULL, '\0', NULL, 1, NULL },
{ "AlmostHVBound", pr_int, &CVShows.hvoffset, NULL, NULL, '\0', NULL, 1, NULL },
{ "CheckSelfIntersects", pr_bool, &CVShows.checkselfintersects, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowDebugChanges", pr_bool, &CVShows.showdebugchanges, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultScreenDpiSystem", pr_int, &oldsystem, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultOutputFormat", pr_int, &oldformatstate, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultBitmapFormat", pr_int, &oldbitmapstate, NULL, NULL, '\0', NULL, 1, NULL },
{ "SaveValidate", pr_int, &old_validate, NULL, NULL, '\0', NULL, 1, NULL },
{ "SaveFontLogAsk", pr_int, &old_fontlog, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultSFNTflags", pr_int, &old_sfnt_flags, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultPSflags", pr_int, &old_ps_flags, NULL, NULL, '\0', NULL, 1, NULL },
{ "PageWidth", pr_int, &pagewidth, NULL, NULL, '\0', NULL, 1, NULL },
{ "PageHeight", pr_int, &pageheight, NULL, NULL, '\0', NULL, 1, NULL },
{ "PrintType", pr_int, &printtype, NULL, NULL, '\0', NULL, 1, NULL },
{ "PrintCommand", pr_string, &printcommand, NULL, NULL, '\0', NULL, 1, NULL },
{ "PageLazyPrinter", pr_string, &printlazyprinter, NULL, NULL, '\0', NULL, 1, NULL },
{ "RegularStar", pr_bool, ®ular_star, NULL, NULL, '\0', NULL, 1, NULL },
{ "PolyStar", pr_bool, &polystar, NULL, NULL, '\0', NULL, 1, NULL },
{ "RectEllipse", pr_bool, &rectelipse, NULL, NULL, '\0', NULL, 1, NULL },
{ "RectCenterOut", pr_bool, ¢er_out[0], NULL, NULL, '\0', NULL, 1, NULL },
{ "EllipseCenterOut", pr_bool, ¢er_out[1], NULL, NULL, '\0', NULL, 1, NULL },
{ "PolyStartPointCnt", pr_int, &ps_pointcnt, NULL, NULL, '\0', NULL, 1, NULL },
{ "RoundRectRadius", pr_real, &rr_radius, NULL, NULL, '\0', NULL, 1, NULL },
{ "StarPercent", pr_real, &star_percent, NULL, NULL, '\0', NULL, 1, NULL },
{ "CoverageFormatsAllowed", pr_int, &coverageformatsallowed, NULL, NULL, '\0', NULL, 1, NULL },
{ "DebugWins", pr_int, &debug_wins, NULL, NULL, '\0', NULL, 1, NULL },
{ "GridFitDpi", pr_int, &gridfit_dpi, NULL, NULL, '\0', NULL, 1, NULL },
{ "GridFitDepth", pr_int, &gridfit_depth, NULL, NULL, '\0', NULL, 1, NULL },
{ "GridFitPointSize", pr_real, &gridfit_pointsizey, NULL, NULL, '\0', NULL, 1, NULL },
{ "GridFitPointSizeX", pr_real, &gridfit_pointsizex, NULL, NULL, '\0', NULL, 1, NULL },
{ "GridFitSameAs", pr_int, &gridfit_x_sameas_y, NULL, NULL, '\0', NULL, 1, NULL },
{ "MVShowGrid", pr_int, &mvshowgrid, NULL, NULL, '\0', NULL, 1, NULL },
{ "ForceNamesWhenOpening", pr_namelist, &force_names_when_opening, NULL, NULL, '\0', NULL, 1, NULL },
{ "ForceNamesWhenSaving", pr_namelist, &force_names_when_saving, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultFontFilterIndex", pr_int, &default_font_filter_index, NULL, NULL, '\0', NULL, 1, NULL },
{ "FCShowHidden", pr_bool, &gfc_showhidden, NULL, NULL, '\0', NULL, 1, NULL },
{ "FCDirPlacement", pr_int, &gfc_dirplace, NULL, NULL, '\0', NULL, 1, NULL },
{ "FCBookmarks", pr_string, &gfc_bookmarks, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultMVType", pr_int, &mv_type, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultMVWidth", pr_int, &mv_width, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultMVHeight", pr_int, &mv_height, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultBVWidth", pr_int, &bv_width, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultBVHeight", pr_int, &bv_height, NULL, NULL, '\0', NULL, 1, NULL },
{ "AnchorControlPixelSize", pr_int, &aa_pixelsize, NULL, NULL, '\0', NULL, 1, NULL },
#ifdef _NO_LIBCAIRO
{ "UseCairoDrawing", pr_bool, &prefs_usecairo, NULL, NULL, '\0', NULL, 0, N_("Use the cairo library for drawing (if available)\nThis makes for prettier (anti-aliased) but slower drawing\nThis applies to any windows created AFTER this is set.\nAlready existing windows will continue as they are.") },
#endif
{ "CV_B1Tool", pr_int, (int *) &cv_b1_tool, NULL, NULL, '\0', NULL, 1, NULL },
{ "CV_CB1Tool", pr_int, (int *) &cv_cb1_tool, NULL, NULL, '\0', NULL, 1, NULL },
{ "CV_B2Tool", pr_int, (int *) &cv_b2_tool, NULL, NULL, '\0', NULL, 1, NULL },
{ "CV_CB2Tool", pr_int, (int *) &cv_cb2_tool, NULL, NULL, '\0', NULL, 1, NULL },
{ "XUID-Base", pr_string, &xuid, NULL, NULL, 'X', NULL, 0, N_("If specified this should be a space separated list of integers each\nless than 16777216 which uniquely identify your organization\nFontForge will generate a random number for the final component.") }, /* Obsolete */
{ "ShowKerningPane", pr_int, (int *) &show_kerning_pane_in_class, NULL, NULL, '\0', NULL, 1, NULL },
PREFS_LIST_EMPTY
},
oldnames[] = {
{ "DumpGlyphMap", pr_bool, &glyph_2_name_map, NULL, NULL, '\0', NULL, 0, N_("When generating a truetype or opentype font it is occasionally\nuseful to know the mapping between truetype glyph ids and\nglyph names. Setting this option will cause FontForge to\nproduce a file (with extension .g2n) containing those data.") },
{ "DefaultTTFApple", pr_int, &pointless, NULL, NULL, '\0', NULL, 1, NULL },
{ "AcuteCenterBottom", pr_bool, &GraveAcuteCenterBottom, NULL, NULL, '\0', NULL, 1, N_("When placing grave and acute accents above letters, should\nFontForge center them based on their full width, or\nshould it just center based on the lowest point\nof the accent.") },
{ "AlwaysGenApple", pr_bool, &alwaysgenapple, NULL, NULL, 'A', NULL, 0, N_("Apple and MS/Adobe differ about the format of truetype and opentype files.\nThis controls the default setting of the Apple checkbox in the\nFile->Generate Font dialog.\nThe main differences are:\n Bitmap data are stored in different tables\n Scaled composite glyphs are treated differently\n Use of GSUB rather than morx(t)/feat\n Use of GPOS rather than kern/opbd\n Use of GDEF rather than lcar/prop\nIf both this and OpenType are set, both formats are generated") },
{ "AlwaysGenOpenType", pr_bool, &alwaysgenopentype, NULL, NULL, 'O', NULL, 0, N_("Apple and MS/Adobe differ about the format of truetype and opentype files.\nThis controls the default setting of the OpenType checkbox in the\nFile->Generate Font dialog.\nThe main differences are:\n Bitmap data are stored in different tables\n Scaled composite glyphs are treated differently\n Use of GSUB rather than morx(t)/feat\n Use of GPOS rather than kern/opbd\n Use of GDEF rather than lcar/prop\nIf both this and Apple are set, both formats are generated") },
{ "DefaultTTFflags", pr_int, &old_ttf_flags, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultOTFflags", pr_int, &old_otf_flags, NULL, NULL, '\0', NULL, 1, NULL },
PREFS_LIST_EMPTY
},
*prefs_list[] = { general_list, new_list, open_list, navigation_list, sync_list, editing_list, editing_interface_list, accent_list, args_list, fontinfo_list, generate_list, tt_list, opentype_list, hints_list, instrs_list,
hidden_list, NULL },
*load_prefs_list[] = { general_list, new_list, open_list, navigation_list, sync_list, editing_list, editing_interface_list, accent_list, args_list, fontinfo_list, generate_list, tt_list, opentype_list, hints_list, instrs_list,
hidden_list, oldnames, NULL };
struct visible_prefs_list { char *tab_name; int nest; struct prefs_list *pl; } visible_prefs_list[] = {
{ N_("Generic"), 0, general_list},
{ N_("New Font"), 0, new_list},
{ N_("Open Font"), 0, open_list},
{ N_("Navigation"), 0, navigation_list},
{ N_("Editing"), 0, editing_list},
{ N_("Interface"), 1, editing_interface_list},
{ N_("Synchronize"), 1, sync_list},
{ N_("TT"), 1, tt_list},
{ N_("Accents"), 1, accent_list},
{ N_("Apps"), 1, args_list},
{ N_("Font Info"), 0, fontinfo_list},
{ N_("Generate"), 0, generate_list},
{ N_("PS Hints"), 1, hints_list},
{ N_("TT Instrs"), 1, instrs_list},
{ N_("OpenType"), 1, opentype_list},
{ NULL, 0, NULL }
};
static void FileChooserPrefsChanged(void *pointless) {
SavePrefs(true);
}
static void ProcessFileChooserPrefs(void) {
unichar_t **b;
int i;
GFileChooserSetShowHidden(gfc_showhidden);
GFileChooserSetDirectoryPlacement(gfc_dirplace);
if ( gfc_bookmarks==NULL ) {
b = malloc(8*sizeof(unichar_t *));
i = 0;
#ifdef __Mac
b[i++] = uc_copy("~/Library/Fonts/");
#endif
b[i++] = uc_copy("~/fonts");
#ifdef __Mac
b[i++] = uc_copy("/Library/Fonts/");
b[i++] = uc_copy("/System/Library/Fonts/");
#endif
#if __CygWin
b[i++] = uc_copy("/cygdrive/c/Windows/Fonts/");
#endif
b[i++] = uc_copy("/usr/X11R6/lib/X11/fonts/");
b[i++] = NULL;
GFileChooserSetBookmarks(b);
} else {
char *pt, *start;
start = gfc_bookmarks;
for ( i=0; ; ++i ) {
pt = strchr(start,';');
if ( pt==NULL )
break;
start = pt+1;
}
start = gfc_bookmarks;
b = malloc((i+2)*sizeof(unichar_t *));
for ( i=0; ; ++i ) {
pt = strchr(start,';');
if ( pt!=NULL )
*pt = '\0';
b[i] = utf82u_copy(start);
if ( pt==NULL )
break;
*pt = ';';
start = pt+1;
}
b[i+1] = NULL;
GFileChooserSetBookmarks(b);
}
GFileChooserSetPrefsChangedCallback(NULL,FileChooserPrefsChanged);
}
static void GetFileChooserPrefs(void) {
unichar_t **foo;
gfc_showhidden = GFileChooserGetShowHidden();
gfc_dirplace = GFileChooserGetDirectoryPlacement();
foo = GFileChooserGetBookmarks();
free(gfc_bookmarks);
if ( foo==NULL || foo[0]==NULL )
gfc_bookmarks = NULL;
else {
int i,len=0;
for ( i=0; foo[i]!=NULL; ++i )
len += 4*u_strlen(foo[i])+1;
gfc_bookmarks = malloc(len+10);
len = 0;
for ( i=0; foo[i]!=NULL; ++i ) {
u2utf8_strcpy(gfc_bookmarks+len,foo[i]);
len += strlen(gfc_bookmarks+len);
gfc_bookmarks[len++] = ';';
}
if ( len>0 )
gfc_bookmarks[len-1] = '\0';
else {
free(gfc_bookmarks);
gfc_bookmarks = NULL;
}
}
}
#define TOPICS (sizeof(visible_prefs_list)/sizeof(visible_prefs_list[0])-1)
static int PrefsUI_GetPrefs(char *name,Val *val) {
int i,j;
/* Support for obsolete preferences */
alwaysgenapple=(old_sfnt_flags&ttf_flag_applemode)?1:0;
alwaysgenopentype=(old_sfnt_flags&ttf_flag_otmode)?1:0;
for ( i=0; prefs_list[i]!=NULL; ++i ) for ( j=0; prefs_list[i][j].name!=NULL; ++j ) {
if ( strcmp(prefs_list[i][j].name,name)==0 ) {
struct prefs_list *pf = &prefs_list[i][j];
if ( pf->type == pr_bool || pf->type == pr_int || pf->type == pr_unicode ) {
val->type = v_int;
val->u.ival = *((int *) (pf->val));
} else if ( pf->type == pr_string || pf->type == pr_file ) {
val->type = v_str;
char *tmpstr = pf->val ? *((char **) (pf->val)) : (char *) (pf->get)();
val->u.sval = copy( tmpstr ? tmpstr : "" );
if( ! pf->val )
free( tmpstr );
} else if ( pf->type == pr_encoding ) {
val->type = v_str;
if ( *((NameList **) (pf->val))==NULL )
val->u.sval = copy( "NULL" );
else
val->u.sval = copy( (*((Encoding **) (pf->val)))->enc_name );
} else if ( pf->type == pr_namelist ) {
val->type = v_str;
val->u.sval = copy( (*((NameList **) (pf->val)))->title );
} else if ( pf->type == pr_real || pf->type == pr_angle ) {
val->type = v_real;
val->u.fval = *((float *) (pf->val));
if ( pf->type == pr_angle )
val->u.fval *= RAD2DEG;
} else
return( false );
return( true );
}
}
return( false );
}
static void CheckObsoletePrefs(void) {
if ( alwaysgenapple==false ) {
old_sfnt_flags &= ~ttf_flag_applemode;
} else if ( alwaysgenapple==true ) {
old_sfnt_flags |= ttf_flag_applemode;
}
if ( alwaysgenopentype==false ) {
old_sfnt_flags &= ~ttf_flag_otmode;
} else if ( alwaysgenopentype==true ) {
old_sfnt_flags |= ttf_flag_otmode;
}
if ( old_ttf_flags!=0 )
old_sfnt_flags = old_ttf_flags | old_otf_flags;
}
static int PrefsUI_SetPrefs(char *name,Val *val1, Val *val2) {
int i,j;
/* Support for obsolete preferences */
alwaysgenapple=-1; alwaysgenopentype=-1;
for ( i=0; prefs_list[i]!=NULL; ++i ) for ( j=0; prefs_list[i][j].name!=NULL; ++j ) {
if ( strcmp(prefs_list[i][j].name,name)==0 ) {
struct prefs_list *pf = &prefs_list[i][j];
if ( pf->type == pr_bool || pf->type == pr_int || pf->type == pr_unicode ) {
if ( (val1->type!=v_int && val1->type!=v_unicode) || val2!=NULL )
return( -1 );
*((int *) (pf->val)) = val1->u.ival;
} else if ( pf->type == pr_real || pf->type == pr_angle ) {
if ( val1->type==v_real && val2==NULL )
*((float *) (pf->val)) = val1->u.fval;
else if ( val1->type!=v_int || (val2!=NULL && val2->type!=v_int ))
return( -1 );
else
*((float *) (pf->val)) = (val2==NULL ? val1->u.ival : val1->u.ival / (double) val2->u.ival);
if ( pf->type == pr_angle )
*((float *) (pf->val)) /= RAD2DEG;
} else if ( pf->type == pr_string || pf->type == pr_file ) {
if ( val1->type!=v_str || val2!=NULL )
return( -1 );
if ( pf->set ) {
pf->set( val1->u.sval );
} else {
free( *((char **) (pf->val)));
*((char **) (pf->val)) = copy( val1->u.sval );
}
} else if ( pf->type == pr_encoding ) {
if ( val2!=NULL )
return( -1 );
else if ( val1->type==v_str && pf->val == &default_encoding) {
Encoding *enc = FindOrMakeEncoding(val1->u.sval);
if ( enc==NULL )
return( -1 );
*((Encoding **) (pf->val)) = enc;
} else
return( -1 );
} else if ( pf->type == pr_namelist ) {
if ( val2!=NULL )
return( -1 );
else if ( val1->type==v_str ) {
NameList *nl = NameListByName(val1->u.sval);
if ( strcmp(val1->u.sval,"NULL")==0 && pf->val != &namelist_for_new_fonts )
nl = NULL;
else if ( nl==NULL )
return( -1 );
*((NameList **) (pf->val)) = nl;
} else
return( -1 );
} else
return( false );
CheckObsoletePrefs();
SavePrefs(true);
return( true );
}
}
return( false );
}
static char *getPfaEditPrefs(void) {
static char *prefs=NULL;
char buffer[1025];
char *ffdir;
if ( prefs!=NULL )
return prefs;
ffdir = getFontForgeUserDir(Config);
if ( ffdir==NULL )
return NULL;
sprintf(buffer,"%s/prefs", ffdir);
free(ffdir);
prefs = copy(buffer);
return prefs;
}
static char *PrefsUI_getFontForgeShareDir(void) {
return getShareDir();
}
static int encmatch(const char *enc,int subok) {
static struct { char *name; int enc; } encs[] = {
{ "US-ASCII", e_usascii },
{ "ASCII", e_usascii },
{ "ISO646-NO", e_iso646_no },
{ "ISO646-SE", e_iso646_se },
{ "LATIN10", e_iso8859_16 },
{ "LATIN1", e_iso8859_1 },
{ "ISO-8859-1", e_iso8859_1 },
{ "ISO-8859-2", e_iso8859_2 },
{ "ISO-8859-3", e_iso8859_3 },
{ "ISO-8859-4", e_iso8859_4 },
{ "ISO-8859-5", e_iso8859_4 },
{ "ISO-8859-6", e_iso8859_4 },
{ "ISO-8859-7", e_iso8859_4 },
{ "ISO-8859-8", e_iso8859_4 },
{ "ISO-8859-9", e_iso8859_4 },
{ "ISO-8859-10", e_iso8859_10 },
{ "ISO-8859-11", e_iso8859_11 },
{ "ISO-8859-13", e_iso8859_13 },
{ "ISO-8859-14", e_iso8859_14 },
{ "ISO-8859-15", e_iso8859_15 },
{ "ISO-8859-16", e_iso8859_16 },
{ "ISO_8859-1", e_iso8859_1 },
{ "ISO_8859-2", e_iso8859_2 },
{ "ISO_8859-3", e_iso8859_3 },
{ "ISO_8859-4", e_iso8859_4 },
{ "ISO_8859-5", e_iso8859_4 },
{ "ISO_8859-6", e_iso8859_4 },
{ "ISO_8859-7", e_iso8859_4 },
{ "ISO_8859-8", e_iso8859_4 },
{ "ISO_8859-9", e_iso8859_4 },
{ "ISO_8859-10", e_iso8859_10 },
{ "ISO_8859-11", e_iso8859_11 },
{ "ISO_8859-13", e_iso8859_13 },
{ "ISO_8859-14", e_iso8859_14 },
{ "ISO_8859-15", e_iso8859_15 },
{ "ISO_8859-16", e_iso8859_16 },
{ "ISO8859-1", e_iso8859_1 },
{ "ISO8859-2", e_iso8859_2 },
{ "ISO8859-3", e_iso8859_3 },
{ "ISO8859-4", e_iso8859_4 },
{ "ISO8859-5", e_iso8859_4 },
{ "ISO8859-6", e_iso8859_4 },
{ "ISO8859-7", e_iso8859_4 },
{ "ISO8859-8", e_iso8859_4 },
{ "ISO8859-9", e_iso8859_4 },
{ "ISO8859-10", e_iso8859_10 },
{ "ISO8859-11", e_iso8859_11 },
{ "ISO8859-13", e_iso8859_13 },
{ "ISO8859-14", e_iso8859_14 },
{ "ISO8859-15", e_iso8859_15 },
{ "ISO8859-16", e_iso8859_16 },
{ "ISO88591", e_iso8859_1 },
{ "ISO88592", e_iso8859_2 },
{ "ISO88593", e_iso8859_3 },
{ "ISO88594", e_iso8859_4 },
{ "ISO88595", e_iso8859_4 },
{ "ISO88596", e_iso8859_4 },
{ "ISO88597", e_iso8859_4 },
{ "ISO88598", e_iso8859_4 },
{ "ISO88599", e_iso8859_4 },
{ "ISO885910", e_iso8859_10 },
{ "ISO885911", e_iso8859_11 },
{ "ISO885913", e_iso8859_13 },
{ "ISO885914", e_iso8859_14 },
{ "ISO885915", e_iso8859_15 },
{ "ISO885916", e_iso8859_16 },
{ "8859_1", e_iso8859_1 },
{ "8859_2", e_iso8859_2 },
{ "8859_3", e_iso8859_3 },
{ "8859_4", e_iso8859_4 },
{ "8859_5", e_iso8859_4 },
{ "8859_6", e_iso8859_4 },
{ "8859_7", e_iso8859_4 },
{ "8859_8", e_iso8859_4 },
{ "8859_9", e_iso8859_4 },
{ "8859_10", e_iso8859_10 },
{ "8859_11", e_iso8859_11 },
{ "8859_13", e_iso8859_13 },
{ "8859_14", e_iso8859_14 },
{ "8859_15", e_iso8859_15 },
{ "8859_16", e_iso8859_16 },
{ "KOI8-R", e_koi8_r },
{ "KOI8R", e_koi8_r },
{ "WINDOWS-1252", e_win },
{ "CP1252", e_win },
{ "Big5", e_big5 },
{ "Big-5", e_big5 },
{ "BigFive", e_big5 },
{ "Big-Five", e_big5 },
{ "Big5HKSCS", e_big5hkscs },
{ "Big5-HKSCS", e_big5hkscs },
{ "UTF-8", e_utf8 },
{ "ISO-10646/UTF-8", e_utf8 },
{ "ISO_10646/UTF-8", e_utf8 },
{ "UCS2", e_unicode },
{ "UCS-2", e_unicode },
{ "UCS-2-INTERNAL", e_unicode },
{ "ISO-10646", e_unicode },
{ "ISO_10646", e_unicode },
/* { "eucJP", e_euc }, */
/* { "EUC-JP", e_euc }, */
/* { "ujis", ??? }, */
/* { "EUC-KR", e_euckorean }, */
{ NULL, 0 }
};
int i;
char buffer[80];
#if HAVE_ICONV_H
static char *last_complaint;
iconv_t test;
free(iconv_local_encoding_name);
iconv_local_encoding_name= NULL;
#endif
if ( strchr(enc,'@')!=NULL && strlen(enc)<sizeof(buffer)-1 ) {
strcpy(buffer,enc);
*strchr(buffer,'@') = '\0';
enc = buffer;
}
for ( i=0; encs[i].name!=NULL; ++i )
if ( strmatch(enc,encs[i].name)==0 )
return( encs[i].enc );
if ( subok ) {
for ( i=0; encs[i].name!=NULL; ++i )
if ( strstrmatch(enc,encs[i].name)!=NULL )
return( encs[i].enc );
#if HAVE_ICONV_H
/* I only try to use iconv if the encoding doesn't match one I support*/
/* loading iconv unicode data takes a while */
test = iconv_open(enc,FindUnicharName());
if ( test==(iconv_t) (-1) || test==NULL ) {
if ( last_complaint==NULL || strcmp(last_complaint,enc)!=0 ) {
fprintf( stderr, "Neither FontForge nor iconv() supports your encoding (%s) we will pretend\n you asked for latin1 instead.\n", enc );
free( last_complaint );
last_complaint = copy(enc);
}
} else {
if ( last_complaint==NULL || strcmp(last_complaint,enc)!=0 ) {
fprintf( stderr, "FontForge does not support your encoding (%s), it will try to use iconv()\n or it will pretend the local encoding is latin1\n", enc );
free( last_complaint );
last_complaint = copy(enc);
}
iconv_local_encoding_name= copy(enc);
iconv_close(test);
}
#else
fprintf( stderr, "FontForge does not support your encoding (%s), it will pretend the local encoding is latin1\n", enc );
#endif
return( e_iso8859_1 );
}
return( e_unknown );
}
static int DefaultEncoding(void) {
const char *loc;
int enc;
#if HAVE_LANGINFO_H
loc = nl_langinfo(CODESET);
enc = encmatch(loc,false);
if ( enc!=e_unknown )
return( enc );
#endif
loc = getenv("LC_ALL");
if ( loc==NULL ) loc = getenv("LC_CTYPE");
/*if ( loc==NULL ) loc = getenv("LC_MESSAGES");*/
if ( loc==NULL ) loc = getenv("LANG");
if ( loc==NULL )
return( e_iso8859_1 );
enc = encmatch(loc,false);
if ( enc==e_unknown ) {
loc = strrchr(loc,'.');
if ( loc==NULL )
return( e_iso8859_1 );
enc = encmatch(loc+1,true);
}
if ( enc==e_unknown )
return( e_iso8859_1 );
return( enc );
}
static void DefaultXUID(void) {
/* Adobe has assigned PfaEdit a base XUID of 1021. Each new user is going */
/* to get a couple of random numbers appended to that, hoping that will */
/* make for a fairly safe system. */
/* FontForge will use the same scheme */
int r1, r2;
char buffer[50];
struct timeval tv;
gettimeofday(&tv,NULL);
srand(tv.tv_usec);
do {
r1 = rand()&0x3ff;
} while ( r1==0 ); /* I reserve "0" for me! */
gettimeofday(&tv,NULL);
g_random_set_seed(tv.tv_usec+1);
r2 = g_random_int();
sprintf( buffer, "1021 %d %d", r1, r2 );
if (xuid != NULL) free(xuid);
xuid = copy(buffer);
}
static void PrefsUI_SetDefaults(void) {
DefaultXUID();
local_encoding = DefaultEncoding();
}
static void ParseMacMapping(char *pt,struct macsettingname *ms) {
char *end;
ms->mac_feature_type = strtol(pt,&end,10);
if ( *end==',' ) ++end;
ms->mac_feature_setting = strtol(end,&end,10);
if ( *end==' ' ) ++end;
ms->otf_tag =
((end[0]&0xff)<<24) |
((end[1]&0xff)<<16) |
((end[2]&0xff)<<8) |
(end[3]&0xff);
}
static void ParseNewMacFeature(FILE *p,char *line) {
fseek(p,-(strlen(line)-strlen("MacFeat:")),SEEK_CUR);
line[strlen("MacFeat:")] ='\0';
default_mac_feature_map = SFDParseMacFeatures(p,line);
fseek(p,-strlen(line),SEEK_CUR);
if ( user_mac_feature_map!=NULL )
MacFeatListFree(user_mac_feature_map);
user_mac_feature_map = default_mac_feature_map;
}
static void PrefsUI_LoadPrefs_FromFile( char* filename )
{
FILE *p;
char line[1100];
int i, j, ri=0, mn=0, ms=0, fn=0, ff=0, filt_max=0;
int msp=0, msc=0;
char *pt;
struct prefs_list *pl;
if ( filename!=NULL && (p=fopen(filename,"r"))!=NULL ) {
while ( fgets(line,sizeof(line),p)!=NULL ) {
if ( *line=='#' )
continue;
pt = strchr(line,':');
if ( pt==NULL )
continue;
for ( j=0; load_prefs_list[j]!=NULL; ++j ) {
for ( i=0; load_prefs_list[j][i].name!=NULL; ++i )
if ( strncmp(line,load_prefs_list[j][i].name,pt-line)==0 )
break;
if ( load_prefs_list[j][i].name!=NULL )
break;
}
pl = NULL;
if ( load_prefs_list[j]!=NULL )
pl = &load_prefs_list[j][i];
for ( ++pt; *pt=='\t'; ++pt );
if ( line[strlen(line)-1]=='\n' )
line[strlen(line)-1] = '\0';
if ( line[strlen(line)-1]=='\r' )
line[strlen(line)-1] = '\0';
if ( pl==NULL ) {
if ( strncmp(line,"Recent:",strlen("Recent:"))==0 && ri<RECENT_MAX )
RecentFiles[ri++] = copy(pt);
else if ( strncmp(line,"MenuScript:",strlen("MenuScript:"))==0 && ms<SCRIPT_MENU_MAX )
script_filenames[ms++] = copy(pt);
else if ( strncmp(line,"MenuName:",strlen("MenuName:"))==0 && mn<SCRIPT_MENU_MAX )
script_menu_names[mn++] = utf82u_copy(pt);
else if ( strncmp(line,"FontFilterName:",strlen("FontFilterName:"))==0 ) {
if ( fn>=filt_max )
user_font_filters = realloc(user_font_filters,((filt_max+=10)+1)*sizeof( struct openfilefilters));
user_font_filters[fn].filter = NULL;
user_font_filters[fn++].name = copy(pt);
user_font_filters[fn].name = NULL;
} else if ( strncmp(line,"FontFilter:",strlen("FontFilter:"))==0 ) {
if ( ff<filt_max )
user_font_filters[ff++].filter = copy(pt);
} else if ( strncmp(line,"MacMapCnt:",strlen("MacSetCnt:"))==0 ) {
sscanf( pt, "%d", &msc );
msp = 0;
user_macfeat_otftag = calloc(msc+1,sizeof(struct macsettingname));
} else if ( strncmp(line,"MacMapping:",strlen("MacMapping:"))==0 && msp<msc ) {
ParseMacMapping(pt,&user_macfeat_otftag[msp++]);
} else if ( strncmp(line,"MacFeat:",strlen("MacFeat:"))==0 ) {
ParseNewMacFeature(p,line);
}
continue;
}
switch ( pl->type ) {
case pr_encoding:
{ Encoding *enc = FindOrMakeEncoding(pt);
if ( enc==NULL )
enc = FindOrMakeEncoding("ISO8859-1");
if ( enc==NULL )
enc = &custom;
*((Encoding **) (pl->val)) = enc;
}
break;
case pr_namelist:
{ NameList *nl = NameListByName(pt);
if ( strcmp(pt,"NULL")==0 && pl->val != &namelist_for_new_fonts )
*((NameList **) (pl->val)) = NULL;
else if ( nl!=NULL )
*((NameList **) (pl->val)) = nl;
}
break;
case pr_bool: case pr_int:
sscanf( pt, "%d", (int *) pl->val );
break;
case pr_unicode:
if ( sscanf( pt, "U+%x", (int *) pl->val )!=1 )
if ( sscanf( pt, "u+%x", (int *) pl->val )!=1 )
sscanf( pt, "%x", (int *) pl->val );
break;
case pr_real: case pr_angle:
{ char *end;
*((float *) pl->val) = strtod(pt,&end);
if (( *end==',' || *end=='.' ) ) {
*end = (*end=='.')?',':'.';
*((float *) pl->val) = strtod(pt,NULL);
}
}
if ( pl->type == pr_angle )
*(float *) pl->val /= RAD2DEG;
break;
case pr_string: case pr_file:
if ( *pt=='\0' ) pt=NULL;
if ( pl->val!=NULL )
*((char **) (pl->val)) = copy(pt);
else
(pl->set)(copy(pt));
break;
}
}
fclose(p);
}
}
void Prefs_LoadDefaultPreferences( void )
{
char filename[PATH_MAX+1];
char* sharedir = getShareDir();
snprintf(filename,PATH_MAX,"%s/prefs", sharedir );
PrefsUI_LoadPrefs_FromFile( filename );
}
static void PrefsUI_LoadPrefs(void)
{
char *prefs = getPfaEditPrefs();
FILE *p;
char line[1100], path[PATH_MAX];
int i, j, ri=0, mn=0, ms=0, fn=0, ff=0, filt_max=0;
int msp=0, msc=0;
char *pt, *real_xdefs_filename = NULL;
struct prefs_list *pl;
LoadPfaEditEncodings();
LoadGroupList();
if ( prefs!=NULL && (p=fopen(prefs,"r"))!=NULL ) {
while ( fgets(line,sizeof(line),p)!=NULL ) {
if ( *line=='#' )
continue;
pt = strchr(line,':');
if ( pt==NULL )
continue;
for ( j=0; load_prefs_list[j]!=NULL; ++j ) {
for ( i=0; load_prefs_list[j][i].name!=NULL; ++i )
if ( strncmp(line,load_prefs_list[j][i].name,pt-line)==0 )
break;
if ( load_prefs_list[j][i].name!=NULL )
break;
}
pl = NULL;
if ( load_prefs_list[j]!=NULL )
pl = &load_prefs_list[j][i];
for ( ++pt; *pt=='\t'; ++pt );
if ( line[strlen(line)-1]=='\n' )
line[strlen(line)-1] = '\0';
if ( line[strlen(line)-1]=='\r' )
line[strlen(line)-1] = '\0';
if ( pl==NULL ) {
if ( strncmp(line,"Recent:",strlen("Recent:"))==0 && ri<RECENT_MAX )
RecentFiles[ri++] = copy(pt);
else if ( strncmp(line,"MenuScript:",strlen("MenuScript:"))==0 && ms<SCRIPT_MENU_MAX )
script_filenames[ms++] = copy(pt);
else if ( strncmp(line,"MenuName:",strlen("MenuName:"))==0 && mn<SCRIPT_MENU_MAX )
script_menu_names[mn++] = utf82u_copy(pt);
else if ( strncmp(line,"FontFilterName:",strlen("FontFilterName:"))==0 ) {
if ( fn>=filt_max )
user_font_filters = realloc(user_font_filters,((filt_max+=10)+1)*sizeof( struct openfilefilters));
user_font_filters[fn].filter = NULL;
user_font_filters[fn++].name = copy(pt);
user_font_filters[fn].name = NULL;
} else if ( strncmp(line,"FontFilter:",strlen("FontFilter:"))==0 ) {
if ( ff<filt_max )
user_font_filters[ff++].filter = copy(pt);
} else if ( strncmp(line,"MacMapCnt:",strlen("MacSetCnt:"))==0 ) {
sscanf( pt, "%d", &msc );
msp = 0;
user_macfeat_otftag = calloc(msc+1,sizeof(struct macsettingname));
} else if ( strncmp(line,"MacMapping:",strlen("MacMapping:"))==0 && msp<msc ) {
ParseMacMapping(pt,&user_macfeat_otftag[msp++]);
} else if ( strncmp(line,"MacFeat:",strlen("MacFeat:"))==0 ) {
ParseNewMacFeature(p,line);
}
continue;
}
switch ( pl->type ) {
case pr_encoding:
{ Encoding *enc = FindOrMakeEncoding(pt);
if ( enc==NULL )
enc = FindOrMakeEncoding("ISO8859-1");
if ( enc==NULL )
enc = &custom;
*((Encoding **) (pl->val)) = enc;
}
break;
case pr_namelist:
{ NameList *nl = NameListByName(pt);
if ( strcmp(pt,"NULL")==0 && pl->val != &namelist_for_new_fonts )
*((NameList **) (pl->val)) = NULL;
else if ( nl!=NULL )
*((NameList **) (pl->val)) = nl;
}
break;
case pr_bool: case pr_int:
sscanf( pt, "%d", (int *) pl->val );
break;
case pr_unicode:
if ( sscanf( pt, "U+%x", (int *) pl->val )!=1 )
if ( sscanf( pt, "u+%x", (int *) pl->val )!=1 )
sscanf( pt, "%x", (int *) pl->val );
break;
case pr_real: case pr_angle:
{ char *end;
*((float *) pl->val) = strtod(pt,&end);
if (( *end==',' || *end=='.' ) ) {
*end = (*end=='.')?',':'.';
*((float *) pl->val) = strtod(pt,NULL);
}
}
if ( pl->type == pr_angle )
*(float *) pl->val /= RAD2DEG;
break;
case pr_string: case pr_file:
if ( *pt=='\0' ) pt=NULL;
if ( pl->val!=NULL )
*((char **) (pl->val)) = copy(pt);
else
(pl->set)(copy(pt));
break;
}
}
fclose(p);
}
//
// If the user has no theme set, then use the default
//
real_xdefs_filename = xdefs_filename;
if ( !real_xdefs_filename )
{
// fprintf(stderr,"no xdefs_filename!\n");
// if (!quiet) {
// fprintf(stderr,"TESTING: getPixmapDir:%s\n", getPixmapDir() );
// fprintf(stderr,"TESTING: getShareDir:%s\n", getShareDir() );
// fprintf(stderr,"TESTING: GResourceProgramDir:%s\n", GResourceProgramDir );
// }
snprintf(path, PATH_MAX, "%s/%s", getPixmapDir(), "resources" );
// if (!quiet)
// fprintf(stderr,"trying default theme:%s\n", path );
real_xdefs_filename = path;
}
GResourceAddResourceFile(real_xdefs_filename,GResourceProgramName,true);
if ( othersubrsfile!=NULL && ReadOtherSubrsFile(othersubrsfile)<=0 )
fprintf( stderr, "Failed to read OtherSubrs from %s\n", othersubrsfile );
if ( glyph_2_name_map )
old_sfnt_flags |= ttf_flag_glyphmap;
LoadNamelistDir(NULL);
ProcessFileChooserPrefs();
GDrawEnableCairo( prefs_usecairo );
}
static void PrefsUI_SavePrefs(int not_if_script) {
char *prefs = getPfaEditPrefs();
FILE *p;
int i, j;
char *temp;
struct prefs_list *pl;
extern int running_script;
if ( prefs==NULL )
return;
if ( not_if_script && running_script )
return;
if ( (p=fopen(prefs,"w"))==NULL )
return;
GetFileChooserPrefs();
for ( j=0; prefs_list[j]!=NULL; ++j ) for ( i=0; prefs_list[j][i].name!=NULL; ++i ) {
pl = &prefs_list[j][i];
switch ( pl->type ) {
case pr_encoding:
fprintf( p, "%s:\t%s\n", pl->name, (*((Encoding **) (pl->val)))->enc_name );
break;
case pr_namelist:
fprintf( p, "%s:\t%s\n", pl->name, *((NameList **) (pl->val))==NULL ? "NULL" :
(*((NameList **) (pl->val)))->title );
break;
case pr_bool: case pr_int:
fprintf( p, "%s:\t%d\n", pl->name, *(int *) (pl->val) );
break;
case pr_unicode:
fprintf( p, "%s:\tU+%04x\n", pl->name, *(int *) (pl->val) );
break;
case pr_real:
fprintf( p, "%s:\t%g\n", pl->name, (double) *(float *) (pl->val) );
break;
case pr_string: case pr_file:
if ( (pl->val)!=NULL )
temp = *(char **) (pl->val);
else
temp = (char *) (pl->get());
if ( temp!=NULL )
fprintf( p, "%s:\t%s\n", pl->name, temp );
if ( (pl->val)==NULL )
free(temp);
break;
case pr_angle:
fprintf( p, "%s:\t%g\n", pl->name, ((double) *(float *) pl->val) * RAD2DEG );
break;
}
}
for ( i=0; i<RECENT_MAX && RecentFiles[i]!=NULL; ++i )
fprintf( p, "Recent:\t%s\n", RecentFiles[i]);
for ( i=0; i<SCRIPT_MENU_MAX && script_filenames[i]!=NULL; ++i ) {
fprintf( p, "MenuScript:\t%s\n", script_filenames[i]);
fprintf( p, "MenuName:\t%s\n", temp = u2utf8_copy(script_menu_names[i]));
free(temp);
}
if ( user_font_filters!=NULL ) {
for ( i=0; user_font_filters[i].name!=NULL; ++i ) {
fprintf( p, "FontFilterName:\t%s\n", user_font_filters[i].name);
fprintf( p, "FontFilter:\t%s\n", user_font_filters[i].filter);
}
}
if ( user_macfeat_otftag!=NULL && UserSettingsDiffer()) {
for ( i=0; user_macfeat_otftag[i].otf_tag!=0; ++i );
fprintf( p, "MacMapCnt: %d\n", i );
for ( i=0; user_macfeat_otftag[i].otf_tag!=0; ++i ) {
fprintf( p, "MacMapping: %d,%d %c%c%c%c\n",
user_macfeat_otftag[i].mac_feature_type,
user_macfeat_otftag[i].mac_feature_setting,
(int) (user_macfeat_otftag[i].otf_tag>>24),
(int) ((user_macfeat_otftag[i].otf_tag>>16)&0xff),
(int) ((user_macfeat_otftag[i].otf_tag>>8)&0xff),
(int) (user_macfeat_otftag[i].otf_tag&0xff) );
}
}
if ( UserFeaturesDiffer())
SFDDumpMacFeat(p,default_mac_feature_map);
fclose(p);
}
struct pref_data {
int done;
struct prefs_list* plist;
};
static int Prefs_ScriptBrowse(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
GWindow gw = GGadgetGetWindow(g);
GGadget *tf = GWidgetGetControl(gw,GGadgetGetCid(g)-SCRIPT_MENU_MAX);
char *cur = GGadgetGetTitle8(tf); char *ret;
if ( *cur=='\0' ) cur=NULL;
ret = gwwv_open_filename(_("Call Script"), cur, "*.pe", NULL);
free(cur);
if ( ret==NULL )
return(true);
GGadgetSetTitle8(tf,ret);
free(ret);
}
return( true );
}
static int Prefs_BrowseFile(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
GWindow gw = GGadgetGetWindow(g);
GGadget *tf = GWidgetGetControl(gw,GGadgetGetCid(g)-CID_PrefsBrowseOffset);
char *cur = GGadgetGetTitle8(tf); char *ret;
struct prefs_list *pl = GGadgetGetUserData(tf);
ret = gwwv_open_filename(pl->name, *cur=='\0'? NULL : cur, NULL, NULL);
free(cur);
if ( ret==NULL )
return(true);
GGadgetSetTitle8(tf,ret);
free(ret);
}
return( true );
}
static GTextInfo *Pref_MappingList(int use_user) {
struct macsettingname *msn = use_user && user_macfeat_otftag!=NULL ?
user_macfeat_otftag :
macfeat_otftag;
GTextInfo *ti;
int i;
char buf[60];
for ( i=0; msn[i].otf_tag!=0; ++i );
ti = calloc(i+1,sizeof( GTextInfo ));
for ( i=0; msn[i].otf_tag!=0; ++i ) {
sprintf(buf,"%3d,%2d %c%c%c%c",
msn[i].mac_feature_type, msn[i].mac_feature_setting,
(int) (msn[i].otf_tag>>24), (int) ((msn[i].otf_tag>>16)&0xff), (int) ((msn[i].otf_tag>>8)&0xff), (int) (msn[i].otf_tag&0xff) );
ti[i].text = uc_copy(buf);
}
return( ti );
}
void GListAddStr(GGadget *list,unichar_t *str, void *ud) {
int32 i,len;
GTextInfo **ti = GGadgetGetList(list,&len);
GTextInfo **replace = malloc((len+2)*sizeof(GTextInfo *));
replace[len+1] = calloc(1,sizeof(GTextInfo));
for ( i=0; i<len; ++i ) {
replace[i] = malloc(sizeof(GTextInfo));
*replace[i] = *ti[i];
replace[i]->text = u_copy(ti[i]->text);
}
replace[i] = calloc(1,sizeof(GTextInfo));
replace[i]->fg = replace[i]->bg = COLOR_DEFAULT;
replace[i]->text = str;
replace[i]->userdata = ud;
GGadgetSetList(list,replace,false);
}
void GListReplaceStr(GGadget *list,int index, unichar_t *str, void *ud) {
int32 i,len;
GTextInfo **ti = GGadgetGetList(list,&len);
GTextInfo **replace = malloc((len+2)*sizeof(GTextInfo *));
for ( i=0; i<len; ++i ) {
replace[i] = malloc(sizeof(GTextInfo));
*replace[i] = *ti[i];
if ( i!=index )
replace[i]->text = u_copy(ti[i]->text);
}
replace[i] = calloc(1,sizeof(GTextInfo));
replace[index]->text = str;
replace[index]->userdata = ud;
GGadgetSetList(list,replace,false);
}
struct setdata {
GWindow gw;
GGadget *list;
GGadget *flist;
GGadget *feature;
GGadget *set_code;
GGadget *otf;
GGadget *ok;
GGadget *cancel;
int index;
int done;
unichar_t *ret;
};
static int set_e_h(GWindow gw, GEvent *event) {
struct setdata *sd = GDrawGetUserData(gw);
int i;
int32 len;
GTextInfo **ti;
const unichar_t *ret1; unichar_t *end;
int on, feat, val1, val2;
unichar_t ubuf[4];
char buf[40];
if ( event->type==et_close ) {
sd->done = true;
} else if ( event->type==et_char ) {
if ( event->u.chr.keysym == GK_F1 || event->u.chr.keysym == GK_Help ) {
help("prefs.html#Features");
return( true );
}
return( false );
} else if ( event->type==et_controlevent && event->u.control.subtype == et_buttonactivate ) {
if ( event->u.control.g == sd->cancel ) {
sd->done = true;
} else if ( event->u.control.g == sd->ok ) {
ret1 = _GGadgetGetTitle(sd->set_code);
on = u_strtol(ret1,&end,10);
if ( *end!='\0' ) {
ff_post_error(_("Bad Number"),_("Bad Number"));
return( true );
}
ret1 = _GGadgetGetTitle(sd->feature);
feat = u_strtol(ret1,&end,10);
if ( *end!='\0' && *end!=' ' ) {
ff_post_error(_("Bad Number"),_("Bad Number"));
return( true );
}
ti = GGadgetGetList(sd->list,&len);
for ( i=0; i<len; ++i ) if ( i!=sd->index ) {
val1 = u_strtol(ti[i]->text,&end,10);
val2 = u_strtol(end+1,NULL,10);
if ( val1==feat && val2==on ) {
static char *buts[3];
buts[0] = _("_Yes");
buts[1] = _("_No");
buts[2] = NULL;
if ( gwwv_ask(_("This feature, setting combination is already used"),(const char **) buts,0,1,
_("This feature, setting combination is already used\nDo you really wish to reuse it?"))==1 )
return( true );
}
}
ret1 = _GGadgetGetTitle(sd->otf);
if ( (ubuf[0] = ret1[0])==0 )
ubuf[0] = ubuf[1] = ubuf[2] = ubuf[3] = ' ';
else if ( (ubuf[1] = ret1[1])==0 )
ubuf[1] = ubuf[2] = ubuf[3] = ' ';
else if ( (ubuf[2] = ret1[2])==0 )
ubuf[2] = ubuf[3] = ' ';
else if ( (ubuf[3] = ret1[3])==0 )
ubuf[3] = ' ';
len = u_strlen(ret1);
if ( len<2 || len>4 || ubuf[0]>=0x7f || ubuf[1]>=0x7f || ubuf[2]>=0x7f || ubuf[3]>=0x7f ) {
ff_post_error(_("Tag too long"),_("Feature tags must be exactly 4 ASCII characters"));
return( true );
}
sprintf(buf,"%3d,%2d %c%c%c%c",
feat, on,
ubuf[0], ubuf[1], ubuf[2], ubuf[3]);
sd->done = true;
sd->ret = uc_copy(buf);
}
}
return( true );
}
static unichar_t *AskSetting(struct macsettingname *temp,GGadget *list, int index,GGadget *flist) {
GRect pos;
GWindow gw;
GWindowAttrs wattrs;
GGadgetCreateData gcd[17];
GTextInfo label[17];
struct setdata sd;
char buf[20];
unichar_t ubuf3[6];
int32 len, i;
GTextInfo **ti;
memset(&sd,0,sizeof(sd));
sd.list = list;
sd.flist = flist;
sd.index = index;
memset(&wattrs,0,sizeof(wattrs));
wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_restrict|wam_isdlg;
wattrs.event_masks = ~(1<<et_charup);
wattrs.restrict_input_to_me = 1;
wattrs.is_dlg = 1;
wattrs.undercursor = 1;
wattrs.cursor = ct_pointer;
wattrs.utf8_window_title = _("Mapping");
pos.x = pos.y = 0;
pos.width = GGadgetScale(GDrawPointsToPixels(NULL,240));
pos.height = GDrawPointsToPixels(NULL,120);
gw = GDrawCreateTopWindow(NULL,&pos,set_e_h,&sd,&wattrs);
sd.gw = gw;
memset(gcd,0,sizeof(gcd));
memset(label,0,sizeof(label));
label[0].text = (unichar_t *) _("_Feature:");
label[0].text_is_1byte = true;
label[0].text_in_resource = true;
gcd[0].gd.label = &label[0];
gcd[0].gd.pos.x = 5; gcd[0].gd.pos.y = 5+4;
gcd[0].gd.flags = gg_enabled|gg_visible;
gcd[0].creator = GLabelCreate;
gcd[1].gd.pos.x = 50; gcd[1].gd.pos.y = 5; gcd[1].gd.pos.width = 170;
gcd[1].gd.flags = gg_enabled|gg_visible;
gcd[1].creator = GListButtonCreate;
label[2].text = (unichar_t *) _("Setting");
label[2].text_is_1byte = true;
gcd[2].gd.label = &label[2];
gcd[2].gd.pos.x = 5; gcd[2].gd.pos.y = gcd[0].gd.pos.y+26;
gcd[2].gd.flags = gg_enabled|gg_visible;
gcd[2].creator = GLabelCreate;
sprintf( buf, "%d", temp->mac_feature_setting );
label[3].text = (unichar_t *) buf;
label[3].text_is_1byte = true;
gcd[3].gd.label = &label[3];
gcd[3].gd.pos.x = gcd[1].gd.pos.x; gcd[3].gd.pos.y = gcd[2].gd.pos.y-4; gcd[3].gd.pos.width = 50;
gcd[3].gd.flags = gg_enabled|gg_visible;
gcd[3].creator = GTextFieldCreate;
label[4].text = (unichar_t *) _("_Tag:");
label[4].text_is_1byte = true;
label[4].text_in_resource = true;
gcd[4].gd.label = &label[4];
gcd[4].gd.pos.x = 5; gcd[4].gd.pos.y = gcd[3].gd.pos.y+26;
gcd[4].gd.flags = gg_enabled|gg_visible;
gcd[4].creator = GLabelCreate;
ubuf3[0] = temp->otf_tag>>24; ubuf3[1] = (temp->otf_tag>>16)&0xff; ubuf3[2] = (temp->otf_tag>>8)&0xff; ubuf3[3] = temp->otf_tag&0xff; ubuf3[4] = 0;
label[5].text = ubuf3;
gcd[5].gd.label = &label[5];
gcd[5].gd.pos.x = gcd[3].gd.pos.x; gcd[5].gd.pos.y = gcd[4].gd.pos.y-4; gcd[5].gd.pos.width = 50;
gcd[5].gd.flags = gg_enabled|gg_visible;
/*gcd[5].gd.u.list = tags;*/
gcd[5].creator = GTextFieldCreate;
gcd[6].gd.pos.x = 13-3; gcd[6].gd.pos.y = gcd[5].gd.pos.y+30;
gcd[6].gd.pos.width = -1; gcd[6].gd.pos.height = 0;
gcd[6].gd.flags = gg_visible | gg_enabled | gg_but_default;
label[6].text = (unichar_t *) _("_OK");
label[6].text_is_1byte = true;
label[6].text_in_resource = true;
gcd[6].gd.label = &label[6];
/*gcd[6].gd.handle_controlevent = Prefs_Ok;*/
gcd[6].creator = GButtonCreate;
gcd[7].gd.pos.x = -13; gcd[7].gd.pos.y = gcd[7-1].gd.pos.y+3;
gcd[7].gd.pos.width = -1; gcd[7].gd.pos.height = 0;
gcd[7].gd.flags = gg_visible | gg_enabled | gg_but_cancel;
label[7].text = (unichar_t *) _("_Cancel");
label[7].text_is_1byte = true;
label[7].text_in_resource = true;
gcd[7].gd.label = &label[7];
gcd[7].creator = GButtonCreate;
GGadgetsCreate(gw,gcd);
sd.feature = gcd[1].ret;
sd.set_code = gcd[3].ret;
sd.otf = gcd[5].ret;
sd.ok = gcd[6].ret;
sd.cancel = gcd[7].ret;
ti = GGadgetGetList(flist,&len);
GGadgetSetList(sd.feature,ti,true);
for ( i=0; i<len; ++i ) {
int val = u_strtol(ti[i]->text,NULL,10);
if ( val==temp->mac_feature_type ) {
GGadgetSetTitle(sd.feature,ti[i]->text);
break;
}
}
GDrawSetVisible(gw,true);
GWidgetIndicateFocusGadget(gcd[1].ret);
while ( !sd.done )
GDrawProcessOneEvent(NULL);
GDrawDestroyWindow(gw);
return( sd.ret );
}
static void ChangeSetting(GGadget *list,int index,GGadget *flist) {
struct macsettingname temp;
int32 len;
GTextInfo **ti = GGadgetGetList(list,&len);
char *str;
unichar_t *ustr;
str = cu_copy(ti[index]->text);
ParseMacMapping(str,&temp);
free(str);
if ( (ustr=AskSetting(&temp,list,index,flist))==NULL )
return;
GListReplaceStr(list,index,ustr,NULL);
}
static int Pref_NewMapping(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
GWindow gw = GGadgetGetWindow(g);
GGadget *list = GWidgetGetControl(gw,CID_Mapping);
GGadget *flist = GWidgetGetControl(GDrawGetParentWindow(gw),CID_Features);
struct macsettingname temp;
unichar_t *str;
memset(&temp,0,sizeof(temp));
temp.mac_feature_type = -1;
if ( (str=AskSetting(&temp,list,-1,flist))==NULL )
return( true );
GListAddStr(list,str,NULL);
/*free(str);*/
}
return( true );
}
static int Pref_DelMapping(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
GWindow gw = GGadgetGetWindow(g);
GListDelSelected(GWidgetGetControl(gw,CID_Mapping));
GGadgetSetEnabled(GWidgetGetControl(gw,CID_MappingDel),false);
GGadgetSetEnabled(GWidgetGetControl(gw,CID_MappingEdit),false);
}
return( true );
}
static int Pref_EditMapping(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
GWindow gw = GDrawGetParentWindow(GGadgetGetWindow(g));
GGadget *list = GWidgetGetControl(gw,CID_Mapping);
GGadget *flist = GWidgetGetControl(gw,CID_Features);
ChangeSetting(list,GGadgetGetFirstListSelectedItem(list),flist);
}
return( true );
}
static int Pref_MappingSel(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_listselected ) {
int32 len;
GTextInfo **ti = GGadgetGetList(g,&len);
GWindow gw = GGadgetGetWindow(g);
int i, sel_cnt=0;
for ( i=0; i<len; ++i )
if ( ti[i]->selected ) ++sel_cnt;
GGadgetSetEnabled(GWidgetGetControl(gw,CID_MappingDel),sel_cnt!=0);
GGadgetSetEnabled(GWidgetGetControl(gw,CID_MappingEdit),sel_cnt==1);
} else if ( e->type==et_controlevent && e->u.control.subtype == et_listdoubleclick ) {
GGadget *flist = GWidgetGetControl( GDrawGetParentWindow(GGadgetGetWindow(g)),CID_Features);
ChangeSetting(g,e->u.control.u.list.changed_index!=-1?e->u.control.u.list.changed_index:
GGadgetGetFirstListSelectedItem(g),flist);
}
return( true );
}
static int Pref_DefaultMapping(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
GGadget *list = GWidgetGetControl(GGadgetGetWindow(g),CID_Mapping);
GTextInfo *ti, **arr;
uint16 cnt;
ti = Pref_MappingList(false);
arr = GTextInfoArrayFromList(ti,&cnt);
GGadgetSetList(list,arr,false);
GTextInfoListFree(ti);
}
return( true );
}
static int Prefs_Ok(GGadget *g, GEvent *e) {
int i, j, mi;
int err=0, enc;
struct pref_data *p;
GWindow gw;
const unichar_t *ret;
const unichar_t *names[SCRIPT_MENU_MAX], *scripts[SCRIPT_MENU_MAX];
struct prefs_list *pl;
GTextInfo **list;
int32 len;
int maxl, t;
char *str;
real dangle;
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
gw = GGadgetGetWindow(g);
p = GDrawGetUserData(gw);
for ( i=0; i<SCRIPT_MENU_MAX; ++i ) {
names[i] = _GGadgetGetTitle(GWidgetGetControl(gw,CID_ScriptMNameBase+i));
scripts[i] = _GGadgetGetTitle(GWidgetGetControl(gw,CID_ScriptMFileBase+i));
if ( *names[i]=='\0' ) names[i] = NULL;
if ( *scripts[i]=='\0' ) scripts[i] = NULL;
if ( scripts[i]==NULL && names[i]!=NULL ) {
ff_post_error(_("Menu name with no associated script"),_("Menu name with no associated script"));
return( true );
} else if ( scripts[i]!=NULL && names[i]==NULL ) {
ff_post_error(_("Script with no associated menu name"),_("Script with no associated menu name"));
return( true );
}
}
for ( i=mi=0; i<SCRIPT_MENU_MAX; ++i ) {
if ( names[i]!=NULL ) {
names[mi] = names[i];
scripts[mi] = scripts[i];
++mi;
}
}
for ( j=0; visible_prefs_list[j].tab_name!=0; ++j ) for ( i=0; visible_prefs_list[j].pl[i].name!=NULL; ++i ) {
pl = &visible_prefs_list[j].pl[i];
/* before assigning values, check for any errors */
/* if any errors, then NO values should be assigned, in case they cancel */
if ( pl->dontdisplay )
continue;
if ( pl->type==pr_int ) {
GetInt8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
} else if ( pl->type==pr_real ) {
GetReal8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
} else if ( pl->type==pr_angle ) {
dangle = GetReal8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
if ( dangle > 90 || dangle < 0 ) {
GGadgetProtest8(pl->name);
err = true;
}
} else if ( pl->type==pr_unicode ) {
GetUnicodeChar8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
}
}
if ( err )
return( true );
for ( j=0; visible_prefs_list[j].tab_name!=0; ++j ) for ( i=0; visible_prefs_list[j].pl[i].name!=NULL; ++i ) {
pl = &visible_prefs_list[j].pl[i];
if ( pl->dontdisplay )
continue;
switch( pl->type ) {
case pr_int:
*((int *) (pl->val)) = GetInt8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
break;
case pr_unicode:
*((int *) (pl->val)) = GetUnicodeChar8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
break;
case pr_bool:
*((int *) (pl->val)) = GGadgetIsChecked(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
break;
case pr_real:
*((float *) (pl->val)) = GetReal8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
break;
case pr_encoding:
{ Encoding *e;
e = ParseEncodingNameFromList(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
if ( e!=NULL )
*((Encoding **) (pl->val)) = e;
enc = 1; /* So gcc doesn't complain about unused. It is unused, but why add the ifdef and make the code even messier? Sigh. icc complains anyway */
}
break;
case pr_namelist:
{ NameList *nl;
GTextInfo *ti = GGadgetGetListItemSelected(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
if ( ti!=NULL ) {
char *name = u2utf8_copy(ti->text);
nl = NameListByName(name);
free(name);
if ( nl!=NULL && nl->uses_unicode && !allow_utf8_glyphnames)
ff_post_error(_("Namelist contains non-ASCII names"),_("Glyph names should be limited to characters in the ASCII character set, but there are names in this namelist which use characters outside that range."));
else if ( nl!=NULL )
*((NameList **) (pl->val)) = nl;
}
}
break;
case pr_string: case pr_file:
ret = _GGadgetGetTitle(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
if ( pl->val!=NULL ) {
free( *((char **) (pl->val)) );
*((char **) (pl->val)) = NULL;
if ( ret!=NULL && *ret!='\0' )
*((char **) (pl->val)) = /* u2def_*/ cu_copy(ret);
} else {
char *cret = cu_copy(ret);
(pl->set)(cret);
free(cret);
}
break;
case pr_angle:
*((float *) (pl->val)) = GetReal8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err)/RAD2DEG;
break;
}
}
for ( i=0; i<SCRIPT_MENU_MAX; ++i ) {
free(script_menu_names[i]); script_menu_names[i] = NULL;
free(script_filenames[i]); script_filenames[i] = NULL;
}
for ( i=0; i<mi; ++i ) {
script_menu_names[i] = u_copy(names[i]);
script_filenames[i] = u2def_copy(scripts[i]);
}
list = GGadgetGetList(GWidgetGetControl(gw,CID_Mapping),&len);
UserSettingsFree();
user_macfeat_otftag = malloc((len+1)*sizeof(struct macsettingname));
user_macfeat_otftag[len].otf_tag = 0;
maxl = 0;
for ( i=0; i<len; ++i ) {
t = u_strlen(list[i]->text);
if ( t>maxl ) maxl = t;
}
str = malloc(maxl+3);
for ( i=0; i<len; ++i ) {
u2encoding_strncpy(str,list[i]->text,maxl+1,e_mac);
ParseMacMapping(str,&user_macfeat_otftag[i]);
}
free(str);
Prefs_ReplaceMacFeatures(GWidgetGetControl(gw,CID_Features));
if ( xuid!=NULL ) {
char *pt;
for ( pt=xuid; *pt==' ' ; ++pt );
if ( *pt=='[' ) { /* People who know PS well, might want to put brackets arround the xuid base array, but I don't want them */
pt = copy(pt+1);
if (xuid != NULL) free( xuid );
xuid = pt;
}
for ( pt=xuid+strlen(xuid)-1; pt>xuid && *pt==' '; --pt );
if ( pt >= xuid && *pt==']' ) *pt = '\0';
}
p->done = true;
PrefsUI_SavePrefs(true);
if ( maxundoes==0 ) { FontView *fv;
for ( fv=fv_list ; fv!=NULL; fv=(FontView *) (fv->b.next) )
SFRemoveUndoes(fv->b.sf,NULL,NULL);
}
if ( othersubrsfile!=NULL && ReadOtherSubrsFile(othersubrsfile)<=0 )
fprintf( stderr, "Failed to read OtherSubrs from %s\n", othersubrsfile );
GDrawEnableCairo(prefs_usecairo);
int force_redraw_charviews = 0;
if( prefs_oldval_cvEditHandleSize != prefs_cvEditHandleSize )
force_redraw_charviews = 1;
if( prefs_oldval_cvInactiveHandleAlpha != prefs_cvInactiveHandleAlpha )
force_redraw_charviews = 1;
if( force_redraw_charviews )
{
FontView *fv;
for ( fv=fv_list ; fv!=NULL; fv=(FontView *) (fv->b.next) )
{
FVRedrawAllCharViews( fv );
}
}
}
return( true );
}
static int Prefs_Cancel(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
struct pref_data *p = GDrawGetUserData(GGadgetGetWindow(g));
MacFeatListFree(GGadgetGetUserData((GWidgetGetControl(
GGadgetGetWindow(g),CID_Features))));
p->done = true;
}
return( true );
}
static int e_h(GWindow gw, GEvent *event) {
if ( event->type==et_close ) {
struct pref_data *p = GDrawGetUserData(gw);
p->done = true;
if(GWidgetGetControl(gw,CID_Features)) {
MacFeatListFree(GGadgetGetUserData((GWidgetGetControl(gw,CID_Features))));
}
} else if ( event->type==et_char ) {
if ( event->u.chr.keysym == GK_F1 || event->u.chr.keysym == GK_Help ) {
help("prefs.html");
return( true );
}
return( false );
}
return( true );
}
static void PrefsInit(void) {
static int done = false;
int i;
if ( done )
return;
done = true;
for ( i=0; visible_prefs_list[i].tab_name!=NULL; ++i )
visible_prefs_list[i].tab_name = _(visible_prefs_list[i].tab_name);
}
void DoPrefs(void) {
GRect pos;
GWindow gw;
GWindowAttrs wattrs;
GGadgetCreateData *pgcd, gcd[5], sgcd[45], mgcd[3], mfgcd[9], msgcd[9];
GGadgetCreateData mfboxes[3], *mfarray[14];
GGadgetCreateData mpboxes[3], *mparray[14];
GGadgetCreateData sboxes[2], *sarray[50];
GGadgetCreateData mboxes[3], *varray[5], *harray[8];
GTextInfo *plabel, **list, label[5], slabel[45], *plabels[TOPICS+5], mflabels[9], mslabels[9];
GTabInfo aspects[TOPICS+5], subaspects[3];
GGadgetCreateData **hvarray, boxes[2*TOPICS];
struct pref_data p;
int i, gc, sgc, j, k, line, line_max, y, y2, ii, si;
int32 llen;
char buf[20];
int gcnt[20];
static unichar_t nullstr[] = { 0 };
struct prefs_list *pl;
char *tempstr;
FontRequest rq;
GFont *font;
PrefsInit();
MfArgsInit();
for ( k=line_max=0; visible_prefs_list[k].tab_name!=0; ++k ) {
for ( i=line=gcnt[k]=0; visible_prefs_list[k].pl[i].name!=NULL; ++i ) {
if ( visible_prefs_list[k].pl[i].dontdisplay )
continue;
gcnt[k] += 2;
if ( visible_prefs_list[k].pl[i].type==pr_bool ) ++gcnt[k];
else if ( visible_prefs_list[k].pl[i].type==pr_file ) ++gcnt[k];
else if ( visible_prefs_list[k].pl[i].type==pr_angle ) ++gcnt[k];
++line;
}
if ( visible_prefs_list[k].pl == args_list ) {
gcnt[k] += 6;
line += 6;
}
if ( line>line_max ) line_max = line;
}
prefs_oldval_cvEditHandleSize = prefs_cvEditHandleSize;
prefs_oldval_cvInactiveHandleAlpha = prefs_cvInactiveHandleAlpha;
memset(&p,'\0',sizeof(p));
memset(&wattrs,0,sizeof(wattrs));
wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_restrict|wam_isdlg;
wattrs.event_masks = ~(1<<et_charup);
wattrs.restrict_input_to_me = 1;
wattrs.is_dlg = 1;
wattrs.undercursor = 1;
wattrs.cursor = ct_pointer;
wattrs.utf8_window_title = _("Preferences");
pos.x = pos.y = 0;
pos.width = GGadgetScale(GDrawPointsToPixels(NULL,350));
pos.height = GDrawPointsToPixels(NULL,line_max*26+69);
gw = GDrawCreateTopWindow(NULL,&pos,e_h,&p,&wattrs);
memset(sgcd,0,sizeof(sgcd));
memset(slabel,0,sizeof(slabel));
memset(&mfgcd,0,sizeof(mfgcd));
memset(&msgcd,0,sizeof(msgcd));
memset(&mflabels,0,sizeof(mflabels));
memset(&mslabels,0,sizeof(mslabels));
memset(&mfboxes,0,sizeof(mfboxes));
memset(&mpboxes,0,sizeof(mpboxes));
memset(&sboxes,0,sizeof(sboxes));
memset(&boxes,0,sizeof(boxes));
GCDFillMacFeat(mfgcd,mflabels,250,default_mac_feature_map, true, mfboxes, mfarray);
sgc = 0;
msgcd[sgc].gd.pos.x = 6; msgcd[sgc].gd.pos.y = 6;
msgcd[sgc].gd.pos.width = 250; msgcd[sgc].gd.pos.height = 16*12+10;
msgcd[sgc].gd.flags = gg_visible | gg_enabled | gg_list_alphabetic | gg_list_multiplesel;
msgcd[sgc].gd.cid = CID_Mapping;
msgcd[sgc].gd.u.list = Pref_MappingList(true);
msgcd[sgc].gd.handle_controlevent = Pref_MappingSel;
msgcd[sgc++].creator = GListCreate;
mparray[0] = &msgcd[sgc-1];
msgcd[sgc].gd.pos.x = 6; msgcd[sgc].gd.pos.y = msgcd[sgc-1].gd.pos.y+msgcd[sgc-1].gd.pos.height+10;
msgcd[sgc].gd.flags = gg_visible | gg_enabled;
mslabels[sgc].text = (unichar_t *) S_("MacMap|_New...");
mslabels[sgc].text_is_1byte = true;
mslabels[sgc].text_in_resource = true;
msgcd[sgc].gd.label = &mslabels[sgc];
msgcd[sgc].gd.handle_controlevent = Pref_NewMapping;
msgcd[sgc++].creator = GButtonCreate;
mparray[4] = GCD_Glue; mparray[5] = &msgcd[sgc-1];
msgcd[sgc].gd.pos.x = msgcd[sgc-1].gd.pos.x+10+GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor);
msgcd[sgc].gd.pos.y = msgcd[sgc-1].gd.pos.y;
msgcd[sgc].gd.flags = gg_visible ;
mslabels[sgc].text = (unichar_t *) _("_Delete");
mslabels[sgc].text_is_1byte = true;
mslabels[sgc].text_in_resource = true;
msgcd[sgc].gd.label = &mslabels[sgc];
msgcd[sgc].gd.cid = CID_MappingDel;
msgcd[sgc].gd.handle_controlevent = Pref_DelMapping;
msgcd[sgc++].creator = GButtonCreate;
mparray[5] = GCD_Glue; mparray[6] = &msgcd[sgc-1];
msgcd[sgc].gd.pos.x = msgcd[sgc-1].gd.pos.x+10+GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor);
msgcd[sgc].gd.pos.y = msgcd[sgc-1].gd.pos.y;
msgcd[sgc].gd.flags = gg_visible ;
mslabels[sgc].text = (unichar_t *) _("_Edit...");
mslabels[sgc].text_is_1byte = true;
mslabels[sgc].text_in_resource = true;
msgcd[sgc].gd.label = &mslabels[sgc];
msgcd[sgc].gd.cid = CID_MappingEdit;
msgcd[sgc].gd.handle_controlevent = Pref_EditMapping;
msgcd[sgc++].creator = GButtonCreate;
mparray[7] = GCD_Glue; mparray[8] = &msgcd[sgc-1];
msgcd[sgc].gd.pos.x = msgcd[sgc-1].gd.pos.x+10+GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor);
msgcd[sgc].gd.pos.y = msgcd[sgc-1].gd.pos.y;
msgcd[sgc].gd.flags = gg_visible | gg_enabled;
mslabels[sgc].text = (unichar_t *) S_("MacMapping|Default");
mslabels[sgc].text_is_1byte = true;
mslabels[sgc].text_in_resource = true;
msgcd[sgc].gd.label = &mslabels[sgc];
msgcd[sgc].gd.handle_controlevent = Pref_DefaultMapping;
msgcd[sgc++].creator = GButtonCreate;
mparray[9] = GCD_Glue; mparray[10] = &msgcd[sgc-1];
mparray[11] = GCD_Glue; mparray[12] = NULL;
mpboxes[2].gd.flags = gg_enabled|gg_visible;
mpboxes[2].gd.u.boxelements = mparray+4;
mpboxes[2].creator = GHBoxCreate;
mparray[1] = GCD_Glue;
mparray[2] = &mpboxes[2];
mparray[3] = NULL;
mpboxes[0].gd.flags = gg_enabled|gg_visible;
mpboxes[0].gd.u.boxelements = mparray;
mpboxes[0].creator = GVBoxCreate;
sgc = 0;
y2=5;
si = 0;
slabel[sgc].text = (unichar_t *) _("Menu Name");
slabel[sgc].text_is_1byte = true;
sgcd[sgc].gd.label = &slabel[sgc];
sgcd[sgc].gd.popup_msg = (unichar_t *) _("You may create a script menu containing up to 10 frequently used scripts.\nEach entry in the menu needs both a name to display in the menu and\na script file to execute. The menu name may contain any unicode characters.\nThe button labeled \"...\" will allow you to browse for a script file.");
sgcd[sgc].gd.pos.x = 8;
sgcd[sgc].gd.pos.y = y2;
sgcd[sgc].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
sgcd[sgc++].creator = GLabelCreate;
sarray[si++] = &sgcd[sgc-1];
slabel[sgc].text = (unichar_t *) _("Script File");
slabel[sgc].text_is_1byte = true;
sgcd[sgc].gd.label = &slabel[sgc];
sgcd[sgc].gd.popup_msg = (unichar_t *) _("You may create a script menu containing up to 10 frequently used scripts\nEach entry in the menu needs both a name to display in the menu and\na script file to execute. The menu name may contain any unicode characters.\nThe button labeled \"...\" will allow you to browse for a script file.");
sgcd[sgc].gd.pos.x = 110;
sgcd[sgc].gd.pos.y = y2;
sgcd[sgc].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
sgcd[sgc++].creator = GLabelCreate;
sarray[si++] = &sgcd[sgc-1];
sarray[si++] = GCD_Glue;
sarray[si++] = NULL;
y2 += 14;
for ( i=0; i<SCRIPT_MENU_MAX; ++i ) {
sgcd[sgc].gd.pos.x = 8; sgcd[sgc].gd.pos.y = y2;
sgcd[sgc].gd.flags = gg_visible | gg_enabled | gg_text_xim;
slabel[sgc].text = script_menu_names[i]==NULL?nullstr:script_menu_names[i];
sgcd[sgc].gd.label = &slabel[sgc];
sgcd[sgc].gd.cid = i+CID_ScriptMNameBase;
sgcd[sgc++].creator = GTextFieldCreate;
sarray[si++] = &sgcd[sgc-1];
sgcd[sgc].gd.pos.x = 110; sgcd[sgc].gd.pos.y = y2;
sgcd[sgc].gd.flags = gg_visible | gg_enabled;
slabel[sgc].text = (unichar_t *) (script_filenames[i]==NULL?"":script_filenames[i]);
slabel[sgc].text_is_1byte = true;
sgcd[sgc].gd.label = &slabel[sgc];
sgcd[sgc].gd.cid = i+CID_ScriptMFileBase;
sgcd[sgc++].creator = GTextFieldCreate;
sarray[si++] = &sgcd[sgc-1];
sgcd[sgc].gd.pos.x = 210; sgcd[sgc].gd.pos.y = y2;
sgcd[sgc].gd.flags = gg_visible | gg_enabled;
slabel[sgc].text = (unichar_t *) _("...");
slabel[sgc].text_is_1byte = true;
sgcd[sgc].gd.label = &slabel[sgc];
sgcd[sgc].gd.cid = i+CID_ScriptMBrowseBase;
sgcd[sgc].gd.handle_controlevent = Prefs_ScriptBrowse;
sgcd[sgc++].creator = GButtonCreate;
sarray[si++] = &sgcd[sgc-1];
sarray[si++] = NULL;
y2 += 26;
}
sarray[si++] = GCD_Glue; sarray[si++] = GCD_Glue; sarray[si++] = GCD_Glue;
sarray[si++] = NULL;
sarray[si++] = NULL;
sboxes[0].gd.flags = gg_enabled|gg_visible;
sboxes[0].gd.u.boxelements = sarray;
sboxes[0].creator = GHVBoxCreate;
memset(&mgcd,0,sizeof(mgcd));
memset(&mgcd,0,sizeof(mgcd));
memset(&subaspects,'\0',sizeof(subaspects));
memset(&label,0,sizeof(label));
memset(&gcd,0,sizeof(gcd));
memset(&aspects,'\0',sizeof(aspects));
aspects[0].selected = true;
for ( k=0; visible_prefs_list[k].tab_name!=0; ++k ) {
pgcd = calloc(gcnt[k]+4,sizeof(GGadgetCreateData));
plabel = calloc(gcnt[k]+4,sizeof(GTextInfo));
hvarray = calloc((gcnt[k]+6)*5+2,sizeof(GGadgetCreateData *));
aspects[k].text = (unichar_t *) visible_prefs_list[k].tab_name;
aspects[k].text_is_1byte = true;
aspects[k].gcd = &boxes[2*k];
aspects[k].nesting = visible_prefs_list[k].nest;
plabels[k] = plabel;
gc = si = 0;
for ( i=line=0, y=5; visible_prefs_list[k].pl[i].name!=NULL; ++i ) {
pl = &visible_prefs_list[k].pl[i];
if ( pl->dontdisplay )
continue;
plabel[gc].text = (unichar_t *) _(pl->name);
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.label = &plabel[gc];
pgcd[gc].gd.mnemonic = '\0';
pgcd[gc].gd.popup_msg = (unichar_t *) _(pl->popup);
pgcd[gc].gd.pos.x = 8;
pgcd[gc].gd.pos.y = y + 6;
pgcd[gc].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
pgcd[gc++].creator = GLabelCreate;
hvarray[si++] = &pgcd[gc-1];
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.label = &plabel[gc];
pgcd[gc].gd.mnemonic = '\0';
pgcd[gc].gd.popup_msg = (unichar_t *) _(pl->popup);
pgcd[gc].gd.pos.x = 110;
pgcd[gc].gd.pos.y = y;
pgcd[gc].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
pgcd[gc].data = pl;
pgcd[gc].gd.cid = k*CID_PrefsOffset+CID_PrefsBase+i;
switch ( pl->type ) {
case pr_bool:
plabel[gc].text = (unichar_t *) _("On");
pgcd[gc].gd.pos.y += 3;
pgcd[gc++].creator = GRadioCreate;
hvarray[si++] = &pgcd[gc-1];
pgcd[gc] = pgcd[gc-1];
pgcd[gc].gd.pos.x += 50;
pgcd[gc].gd.cid = 0;
pgcd[gc].gd.label = &plabel[gc];
plabel[gc].text = (unichar_t *) _("Off");
plabel[gc].text_is_1byte = true;
hvarray[si++] = &pgcd[gc];
hvarray[si++] = GCD_Glue;
if ( *((int *) pl->val))
pgcd[gc-1].gd.flags |= gg_cb_on;
else
pgcd[gc].gd.flags |= gg_cb_on;
++gc;
y += 22;
break;
case pr_int:
sprintf(buf,"%d", *((int *) pl->val));
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
y += 26;
break;
case pr_unicode:
/*sprintf(buf,"U+%04x", *((int *) pl->val));*/
{ char *pt; pt=buf; pt=utf8_idpb(pt,*((int *)pl->val),UTF8IDPB_NOZERO); *pt='\0'; }
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
y += 26;
break;
case pr_real:
sprintf(buf,"%g", *((float *) pl->val));
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
y += 26;
break;
case pr_encoding:
pgcd[gc].gd.u.list = GetEncodingTypes();
pgcd[gc].gd.label = EncodingTypesFindEnc(pgcd[gc].gd.u.list,
*(Encoding **) pl->val);
for ( ii=0; pgcd[gc].gd.u.list[ii].text!=NULL ||pgcd[gc].gd.u.list[ii].line; ++ii )
if ( pgcd[gc].gd.u.list[ii].userdata!=NULL &&
(strcmp(pgcd[gc].gd.u.list[ii].userdata,"Compacted")==0 ||
strcmp(pgcd[gc].gd.u.list[ii].userdata,"Original")==0 ))
pgcd[gc].gd.u.list[ii].disabled = true;
pgcd[gc].creator = GListFieldCreate;
pgcd[gc].gd.pos.width = 160;
if ( pgcd[gc].gd.label==NULL ) pgcd[gc].gd.label = &encodingtypes[0];
++gc;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_ColSpan; hvarray[si++] = GCD_ColSpan;
y += 28;
break;
case pr_namelist:
{ char **nlnames = AllNamelistNames();
int cnt;
GTextInfo *namelistnames;
for ( cnt=0; nlnames[cnt]!=NULL; ++cnt);
namelistnames = calloc(cnt+1,sizeof(GTextInfo));
for ( cnt=0; nlnames[cnt]!=NULL; ++cnt) {
namelistnames[cnt].text = (unichar_t *) nlnames[cnt];
namelistnames[cnt].text_is_1byte = true;
if ( strcmp(_((*(NameList **) (pl->val))->title),nlnames[cnt])==0 ) {
namelistnames[cnt].selected = true;
pgcd[gc].gd.label = &namelistnames[cnt];
}
}
pgcd[gc].gd.u.list = namelistnames;
pgcd[gc].creator = GListButtonCreate;
pgcd[gc].gd.pos.width = 160;
++gc;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_ColSpan; hvarray[si++] = GCD_ColSpan;
y += 28;
} break;
case pr_string: case pr_file:
if ( pl->set==SetAutoTraceArgs || ((char **) pl->val)==&mf_args )
pgcd[gc].gd.pos.width = 160;
if ( pl->val!=NULL )
tempstr = *((char **) (pl->val));
else
tempstr = (char *) ((pl->get)());
if ( tempstr!=NULL )
plabel[gc].text = /* def2u_*/ uc_copy( tempstr );
else if ( ((char **) pl->val)==&BDFFoundry )
plabel[gc].text = /* def2u_*/ uc_copy( "FontForge" );
else
plabel[gc].text = /* def2u_*/ uc_copy( "" );
plabel[gc].text_is_1byte = false;
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
if ( pl->type==pr_file ) {
pgcd[gc] = pgcd[gc-1];
pgcd[gc-1].gd.pos.width = 140;
hvarray[si++] = GCD_ColSpan;
pgcd[gc].gd.pos.x += 145;
pgcd[gc].gd.cid += CID_PrefsBrowseOffset;
pgcd[gc].gd.label = &plabel[gc];
plabel[gc].text = (unichar_t *) "...";
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.handle_controlevent = Prefs_BrowseFile;
pgcd[gc++].creator = GButtonCreate;
hvarray[si++] = &pgcd[gc-1];
} else if ( pl->set==SetAutoTraceArgs || ((char **) pl->val)==&mf_args ) {
hvarray[si++] = GCD_ColSpan;
hvarray[si++] = GCD_Glue;
} else {
hvarray[si++] = GCD_Glue;
hvarray[si++] = GCD_Glue;
}
y += 26;
if ( pl->val==NULL )
free(tempstr);
break;
case pr_angle:
sprintf(buf,"%g", *((float *) pl->val) * RAD2DEG);
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
plabel[gc].text = (unichar_t *) U_("°");
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.label = &plabel[gc];
pgcd[gc].gd.pos.x = pgcd[gc-1].gd.pos.x+gcd[gc-1].gd.pos.width+2; pgcd[gc].gd.pos.y = pgcd[gc-1].gd.pos.y;
pgcd[gc].gd.flags = gg_enabled|gg_visible;
pgcd[gc++].creator = GLabelCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue;
y += 26;
break;
}
++line;
hvarray[si++] = NULL;
}
if ( visible_prefs_list[k].pl == args_list ) {
static char *text[] = {
/* GT: See the long comment at "Property|New" */
/* GT: This and the next few strings show a limitation of my widget set which */
/* GT: cannot handle multi-line text labels. These strings should be concatenated */
/* GT: (after striping off "Prefs_App|") together, translated, and then broken up */
/* GT: to fit the dialog. There is an extra blank line, not used in English, */
/* GT: into which your text may extend if needed. */
N_("Prefs_App|Normally FontForge will find applications by searching for"),
N_("Prefs_App|them in your PATH environment variable, if you want"),
N_("Prefs_App|to alter that behavior you may set an environment"),
N_("Prefs_App|variable giving the full path spec of the application."),
N_("Prefs_App|FontForge recognizes BROWSER, MF and AUTOTRACE."),
N_("Prefs_App| "), /* A blank line */
NULL };
y += 8;
for ( i=0; text[i]!=0; ++i ) {
plabel[gc].text = (unichar_t *) S_(text[i]);
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.label = &plabel[gc];
pgcd[gc].gd.pos.x = 8;
pgcd[gc].gd.pos.y = y;
pgcd[gc].gd.flags = gg_visible | gg_enabled;
pgcd[gc++].creator = GLabelCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_ColSpan; hvarray[si++] = GCD_ColSpan;
hvarray[si++] = NULL;
y += 12;
}
}
if ( y>y2 ) y2 = y;
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
hvarray[si++] = NULL;
hvarray[si++] = NULL;
boxes[2*k].gd.flags = gg_enabled|gg_visible;
boxes[2*k].gd.u.boxelements = hvarray;
boxes[2*k].creator = GHVBoxCreate;
}
aspects[k].text = (unichar_t *) _("Script Menu");
aspects[k].text_is_1byte = true;
aspects[k++].gcd = sboxes;
subaspects[0].text = (unichar_t *) _("Features");
subaspects[0].text_is_1byte = true;
subaspects[0].gcd = mfboxes;
subaspects[1].text = (unichar_t *) _("Mapping");
subaspects[1].text_is_1byte = true;
subaspects[1].gcd = mpboxes;
mgcd[0].gd.pos.x = 4; gcd[0].gd.pos.y = 6;
mgcd[0].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-20;
mgcd[0].gd.pos.height = y2;
mgcd[0].gd.u.tabs = subaspects;
mgcd[0].gd.flags = gg_visible | gg_enabled;
mgcd[0].creator = GTabSetCreate;
aspects[k].text = (unichar_t *) _("Mac");
aspects[k].text_is_1byte = true;
aspects[k++].gcd = mgcd;
gc = 0;
gcd[gc].gd.pos.x = gcd[gc].gd.pos.y = 2;
gcd[gc].gd.pos.width = pos.width-4; gcd[gc].gd.pos.height = pos.height-2;
gcd[gc].gd.flags = gg_enabled | gg_visible | gg_pos_in_pixels;
gcd[gc++].creator = GGroupCreate;
gcd[gc].gd.pos.x = 4; gcd[gc].gd.pos.y = 6;
gcd[gc].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-8;
gcd[gc].gd.pos.height = y2+20+18+4;
gcd[gc].gd.u.tabs = aspects;
gcd[gc].gd.flags = gg_visible | gg_enabled | gg_tabset_vert;
gcd[gc++].creator = GTabSetCreate;
varray[0] = &gcd[gc-1]; varray[1] = NULL;
y = gcd[gc-1].gd.pos.y+gcd[gc-1].gd.pos.height;
gcd[gc].gd.pos.x = 30-3; gcd[gc].gd.pos.y = y+5-3;
gcd[gc].gd.pos.width = -1; gcd[gc].gd.pos.height = 0;
gcd[gc].gd.flags = gg_visible | gg_enabled | gg_but_default;
label[gc].text = (unichar_t *) _("_OK");
label[gc].text_is_1byte = true;
label[gc].text_in_resource = true;
gcd[gc].gd.mnemonic = 'O';
gcd[gc].gd.label = &label[gc];
gcd[gc].gd.handle_controlevent = Prefs_Ok;
gcd[gc++].creator = GButtonCreate;
harray[0] = GCD_Glue; harray[1] = &gcd[gc-1]; harray[2] = GCD_Glue; harray[3] = GCD_Glue;
gcd[gc].gd.pos.x = -30; gcd[gc].gd.pos.y = gcd[gc-1].gd.pos.y+3;
gcd[gc].gd.pos.width = -1; gcd[gc].gd.pos.height = 0;
gcd[gc].gd.flags = gg_visible | gg_enabled | gg_but_cancel;
label[gc].text = (unichar_t *) _("_Cancel");
label[gc].text_is_1byte = true;
label[gc].text_in_resource = true;
gcd[gc].gd.label = &label[gc];
gcd[gc].gd.mnemonic = 'C';
gcd[gc].gd.handle_controlevent = Prefs_Cancel;
gcd[gc++].creator = GButtonCreate;
harray[4] = GCD_Glue; harray[5] = &gcd[gc-1]; harray[6] = GCD_Glue; harray[7] = NULL;
memset(mboxes,0,sizeof(mboxes));
mboxes[2].gd.flags = gg_enabled|gg_visible;
mboxes[2].gd.u.boxelements = harray;
mboxes[2].creator = GHBoxCreate;
varray[2] = &mboxes[2];
varray[3] = NULL;
varray[4] = NULL;
mboxes[0].gd.pos.x = mboxes[0].gd.pos.y = 2;
mboxes[0].gd.flags = gg_enabled|gg_visible;
mboxes[0].gd.u.boxelements = varray;
mboxes[0].creator = GHVGroupCreate;
y = GDrawPointsToPixels(NULL,y+37);
gcd[0].gd.pos.height = y-4;
GGadgetsCreate(gw,mboxes);
GTextInfoListFree(mfgcd[0].gd.u.list);
GTextInfoListFree(msgcd[0].gd.u.list);
GHVBoxSetExpandableRow(mboxes[0].ret,0);
GHVBoxSetExpandableCol(mboxes[2].ret,gb_expandgluesame);
GHVBoxSetExpandableRow(mfboxes[0].ret,0);
GHVBoxSetExpandableCol(mfboxes[2].ret,gb_expandgluesame);
GHVBoxSetExpandableRow(mpboxes[0].ret,0);
GHVBoxSetExpandableCol(mpboxes[2].ret,gb_expandgluesame);
GHVBoxSetExpandableRow(sboxes[0].ret,gb_expandglue);
for ( k=0; k<TOPICS; ++k )
GHVBoxSetExpandableRow(boxes[2*k].ret,gb_expandglue);
memset(&rq,0,sizeof(rq));
rq.utf8_family_name = MONO_UI_FAMILIES;
rq.point_size = 12;
rq.weight = 400;
font = GDrawInstanciateFont(gw,&rq);
GGadgetSetFont(mfgcd[0].ret,font);
GGadgetSetFont(msgcd[0].ret,font);
GHVBoxFitWindow(mboxes[0].ret);
for ( k=0; visible_prefs_list[k].tab_name!=0; ++k ) for ( gc=0,i=0; visible_prefs_list[k].pl[i].name!=NULL; ++i ) {
GGadgetCreateData *gcd = aspects[k].gcd[0].gd.u.boxelements[0];
pl = &visible_prefs_list[k].pl[i];
if ( pl->dontdisplay )
continue;
switch ( pl->type ) {
case pr_bool:
++gc;
break;
case pr_encoding: {
GGadget *g = gcd[gc+1].ret;
list = GGadgetGetList(g,&llen);
for ( j=0; j<llen ; ++j ) {
if ( list[j]->text!=NULL &&
(void *) (intpt) ( *((int *) pl->val)) == list[j]->userdata )
list[j]->selected = true;
else
list[j]->selected = false;
}
if ( gcd[gc+1].gd.u.list!=encodingtypes )
GTextInfoListFree(gcd[gc+1].gd.u.list);
} break;
case pr_namelist:
free(gcd[gc+1].gd.u.list);
break;
case pr_string: case pr_file: case pr_int: case pr_real: case pr_unicode: case pr_angle:
free(plabels[k][gc+1].text);
if ( pl->type==pr_file || pl->type==pr_angle )
++gc;
break;
}
gc += 2;
}
for ( k=0; visible_prefs_list[k].tab_name!=0; ++k ) {
free(aspects[k].gcd->gd.u.boxelements[0]);
free(aspects[k].gcd->gd.u.boxelements);
free(plabels[k]);
}
GWidgetHidePalettes();
GDrawSetVisible(gw,true);
while ( !p.done )
GDrawProcessOneEvent(NULL);
GDrawDestroyWindow(gw);
}
void RecentFilesRemember(char *filename) {
int i,j;
for ( i=0; i<RECENT_MAX && RecentFiles[i]!=NULL; ++i )
if ( strcmp(RecentFiles[i],filename)==0 )
break;
if ( i<RECENT_MAX && RecentFiles[i]!=NULL ) {
if ( i!=0 ) {
filename = RecentFiles[i];
for ( j=i; j>0; --j )
RecentFiles[j] = RecentFiles[j-1];
RecentFiles[0] = filename;
}
} else {
if ( RecentFiles[RECENT_MAX-1]!=NULL )
free( RecentFiles[RECENT_MAX-1]);
for ( i=RECENT_MAX-1; i>0; --i )
RecentFiles[i] = RecentFiles[i-1];
RecentFiles[0] = copy(filename);
}
PrefsUI_SavePrefs(true);
}
void LastFonts_Save(void) {
FontView *fv, *next;
char buffer[1024];
char *ffdir = getFontForgeUserDir(Config);
FILE *preserve = NULL;
if ( ffdir ) {
sprintf(buffer, "%s/FontsOpenAtLastQuit", ffdir);
preserve = fopen(buffer,"w");
free(ffdir);
}
for ( fv = fv_list; fv!=NULL; fv = next ) {
next = (FontView *) (fv->b.next);
if ( preserve ) {
SplineFont *sf = fv->b.cidmaster?fv->b.cidmaster:fv->b.sf;
fprintf(preserve, "%s\n", sf->filename?sf->filename:sf->origname);
}
}
if ( preserve )
fclose(preserve);
}
struct prefs_interface gdraw_prefs_interface = {
PrefsUI_SavePrefs,
PrefsUI_LoadPrefs,
PrefsUI_GetPrefs,
PrefsUI_SetPrefs,
PrefsUI_getFontForgeShareDir,
PrefsUI_SetDefaults
};
static void change_res_filename(const char *newname) {
free(xdefs_filename);
xdefs_filename = copy( newname );
SavePrefs(true);
}
void DoXRes(void) {
extern GResInfo fontview_ri;
MVColInit();
CVColInit();
GResEdit(&fontview_ri,xdefs_filename,change_res_filename);
}
struct prefs_list pointer_dialog_list[] = {
{ N_("ArrowMoveSize"), pr_real, &arrowAmount, NULL, NULL, '\0', NULL, 0, N_("The number of em-units by which an arrow key will move a selected point") },
{ N_("ArrowAccelFactor"), pr_real, &arrowAccelFactor, NULL, NULL, '\0', NULL, 0, N_("Holding down the Shift key will speed up arrow key motion by this factor") },
{ N_("InterpolateCPsOnMotion"), pr_bool, &interpCPsOnMotion, NULL, NULL, '\0', NULL, 0, N_("When moving one end point of a spline but not the other\ninterpolate the control points between the two.") },
PREFS_LIST_EMPTY
};
struct prefs_list ruler_dialog_list[] = {
{ N_("SnapDistanceMeasureTool"), pr_real, &snapdistancemeasuretool, NULL, NULL, '\0', NULL, 0, N_("When the measure tool is active and when the mouse pointer is within this many pixels\nof one of the various interesting features (baseline,\nwidth, grid splines, etc.) the pointer will snap\nto that feature.") },
{ N_("MeasureToolShowHorizontalVertical"), pr_bool, &measuretoolshowhorizontolvertical, NULL, NULL, '\0', NULL, 0, N_("Have the measure tool show horizontal and vertical distances on the canvas.") },
PREFS_LIST_EMPTY
};
static int PrefsSubSet_Ok(GGadget *g, GEvent *e) {
GWindow gw = GGadgetGetWindow(g);
struct pref_data *p = GDrawGetUserData(GGadgetGetWindow(g));
struct prefs_list* plist = p->plist;
struct prefs_list* pl = plist;
int i=0,j=0;
int err=0, enc;
const unichar_t *ret;
p->done = true;
for ( i=0, pl=plist; pl->name; ++i, ++pl ) {
switch( pl->type ) {
case pr_int:
*((int *) (pl->val)) = GetInt8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
break;
case pr_unicode:
*((int *) (pl->val)) = GetUnicodeChar8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
break;
case pr_bool:
*((int *) (pl->val)) = GGadgetIsChecked(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
break;
case pr_real:
*((float *) (pl->val)) = GetReal8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
break;
case pr_encoding:
{ Encoding *e;
e = ParseEncodingNameFromList(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
if ( e!=NULL )
*((Encoding **) (pl->val)) = e;
enc = 1; /* So gcc doesn't complain about unused. It is unused, but why add the ifdef and make the code even messier? Sigh. icc complains anyway */
}
break;
case pr_namelist:
{ NameList *nl;
GTextInfo *ti = GGadgetGetListItemSelected(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
if ( ti!=NULL ) {
char *name = u2utf8_copy(ti->text);
nl = NameListByName(name);
free(name);
if ( nl!=NULL && nl->uses_unicode && !allow_utf8_glyphnames)
ff_post_error(_("Namelist contains non-ASCII names"),_("Glyph names should be limited to characters in the ASCII character set, but there are names in this namelist which use characters outside that range."));
else if ( nl!=NULL )
*((NameList **) (pl->val)) = nl;
}
}
break;
case pr_string: case pr_file:
ret = _GGadgetGetTitle(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
if ( pl->val!=NULL ) {
free( *((char **) (pl->val)) );
*((char **) (pl->val)) = NULL;
if ( ret!=NULL && *ret!='\0' )
*((char **) (pl->val)) = /* u2def_*/ cu_copy(ret);
} else {
char *cret = cu_copy(ret);
(pl->set)(cret);
free(cret);
}
break;
case pr_angle:
*((float *) (pl->val)) = GetReal8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err)/RAD2DEG;
break;
}
}
return( true );
}
static void PrefsSubSetDlg(CharView *cv,char* windowTitle,struct prefs_list* plist) {
struct prefs_list* pl = plist;
GRect pos;
GWindow gw;
GWindowAttrs wattrs;
GGadgetCreateData *pgcd, gcd[20], sgcd[45], mgcd[3], mfgcd[9], msgcd[9];
GGadgetCreateData mfboxes[3], *mfarray[14];
GGadgetCreateData mpboxes[3];
GGadgetCreateData sboxes[2];
GGadgetCreateData mboxes[3], mboxes2[5], *varray[5], *harray[8];
GTextInfo *plabel, label[20], slabel[45], mflabels[9], mslabels[9];
GTabInfo aspects[TOPICS+5], subaspects[3];
GGadgetCreateData **hvarray, boxes[2*TOPICS];
struct pref_data p;
int line = 0,line_max = 3;
int i = 0, gc = 0, ii, y=0, si=0, k=0;
char buf[20];
char *tempstr;
PrefsInit();
MfArgsInit();
line_max=0;
for ( i=0, pl=plist; pl->name; ++i, ++pl ) {
++line_max;
}
int itemCount = 100;
pgcd = calloc(itemCount,sizeof(GGadgetCreateData));
plabel = calloc(itemCount,sizeof(GTextInfo));
hvarray = calloc((itemCount)*5,sizeof(GGadgetCreateData *));
memset(&p,'\0',sizeof(p));
memset(&wattrs,0,sizeof(wattrs));
memset(sgcd,0,sizeof(sgcd));
memset(slabel,0,sizeof(slabel));
memset(&mfgcd,0,sizeof(mfgcd));
memset(&msgcd,0,sizeof(msgcd));
memset(&mflabels,0,sizeof(mflabels));
memset(&mslabels,0,sizeof(mslabels));
memset(&mfboxes,0,sizeof(mfboxes));
memset(&mpboxes,0,sizeof(mpboxes));
memset(&sboxes,0,sizeof(sboxes));
memset(&boxes,0,sizeof(boxes));
memset(&mgcd,0,sizeof(mgcd));
memset(&mgcd,0,sizeof(mgcd));
memset(&subaspects,'\0',sizeof(subaspects));
memset(&label,0,sizeof(label));
memset(&gcd,0,sizeof(gcd));
memset(&aspects,'\0',sizeof(aspects));
GCDFillMacFeat(mfgcd,mflabels,250,default_mac_feature_map, true, mfboxes, mfarray);
p.plist = plist;
wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_restrict|wam_isdlg;
wattrs.event_masks = ~(1<<et_charup);
wattrs.restrict_input_to_me = 1;
wattrs.is_dlg = 1;
wattrs.undercursor = 1;
wattrs.cursor = ct_pointer;
wattrs.utf8_window_title = windowTitle;
pos.x = pos.y = 0;
pos.width = GGadgetScale(GDrawPointsToPixels(NULL,340));
pos.height = GDrawPointsToPixels(NULL,line_max*26+25);
gw = GDrawCreateTopWindow(NULL,&pos,e_h,&p,&wattrs);
for ( i=0, pl=plist; pl->name; ++i, ++pl ) {
plabel[gc].text = (unichar_t *) _(pl->name);
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.label = &plabel[gc];
pgcd[gc].gd.mnemonic = '\0';
pgcd[gc].gd.popup_msg = (unichar_t *) 0;//_(pl->popup);
pgcd[gc].gd.pos.x = 8;
pgcd[gc].gd.pos.y = y + 6;
pgcd[gc].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
pgcd[gc++].creator = GLabelCreate;
hvarray[si++] = &pgcd[gc-1];
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.label = &plabel[gc];
pgcd[gc].gd.mnemonic = '\0';
pgcd[gc].gd.popup_msg = (unichar_t *) 0;//_(pl->popup);
pgcd[gc].gd.pos.x = 110;
pgcd[gc].gd.pos.y = y;
pgcd[gc].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
pgcd[gc].data = pl;
pgcd[gc].gd.cid = k*CID_PrefsOffset+CID_PrefsBase+i;
switch ( pl->type ) {
case pr_bool:
plabel[gc].text = (unichar_t *) _("On");
pgcd[gc].gd.pos.y += 3;
pgcd[gc++].creator = GRadioCreate;
hvarray[si++] = &pgcd[gc-1];
pgcd[gc] = pgcd[gc-1];
pgcd[gc].gd.pos.x += 50;
pgcd[gc].gd.cid = 0;
pgcd[gc].gd.label = &plabel[gc];
plabel[gc].text = (unichar_t *) _("Off");
plabel[gc].text_is_1byte = true;
hvarray[si++] = &pgcd[gc];
hvarray[si++] = GCD_Glue;
if ( *((int *) pl->val))
pgcd[gc-1].gd.flags |= gg_cb_on;
else
pgcd[gc].gd.flags |= gg_cb_on;
++gc;
y += 22;
break;
case pr_int:
sprintf(buf,"%d", *((int *) pl->val));
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
y += 26;
break;
case pr_unicode:
/*sprintf(buf,"U+%04x", *((int *) pl->val));*/
{ char *pt; pt=buf; pt=utf8_idpb(pt,*((int *)pl->val),UTF8IDPB_NOZERO); *pt='\0'; }
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
y += 26;
break;
case pr_real:
sprintf(buf,"%g", *((float *) pl->val));
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
y += 26;
break;
case pr_encoding:
pgcd[gc].gd.u.list = GetEncodingTypes();
pgcd[gc].gd.label = EncodingTypesFindEnc(pgcd[gc].gd.u.list,
*(Encoding **) pl->val);
for ( ii=0; pgcd[gc].gd.u.list[ii].text!=NULL ||pgcd[gc].gd.u.list[ii].line; ++ii )
if ( pgcd[gc].gd.u.list[ii].userdata!=NULL &&
(strcmp(pgcd[gc].gd.u.list[ii].userdata,"Compacted")==0 ||
strcmp(pgcd[gc].gd.u.list[ii].userdata,"Original")==0 ))
pgcd[gc].gd.u.list[ii].disabled = true;
pgcd[gc].creator = GListFieldCreate;
pgcd[gc].gd.pos.width = 160;
if ( pgcd[gc].gd.label==NULL ) pgcd[gc].gd.label = &encodingtypes[0];
++gc;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_ColSpan; hvarray[si++] = GCD_ColSpan;
y += 28;
break;
case pr_namelist:
{ char **nlnames = AllNamelistNames();
int cnt;
GTextInfo *namelistnames;
for ( cnt=0; nlnames[cnt]!=NULL; ++cnt);
namelistnames = calloc(cnt+1,sizeof(GTextInfo));
for ( cnt=0; nlnames[cnt]!=NULL; ++cnt) {
namelistnames[cnt].text = (unichar_t *) nlnames[cnt];
namelistnames[cnt].text_is_1byte = true;
if ( strcmp(_((*(NameList **) (pl->val))->title),nlnames[cnt])==0 ) {
namelistnames[cnt].selected = true;
pgcd[gc].gd.label = &namelistnames[cnt];
}
}
pgcd[gc].gd.u.list = namelistnames;
pgcd[gc].creator = GListButtonCreate;
pgcd[gc].gd.pos.width = 160;
++gc;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_ColSpan; hvarray[si++] = GCD_ColSpan;
y += 28;
} break;
case pr_string: case pr_file:
if ( pl->set==SetAutoTraceArgs || ((char **) pl->val)==&mf_args )
pgcd[gc].gd.pos.width = 160;
if ( pl->val!=NULL )
tempstr = *((char **) (pl->val));
else
tempstr = (char *) ((pl->get)());
if ( tempstr!=NULL )
plabel[gc].text = /* def2u_*/ uc_copy( tempstr );
else if ( ((char **) pl->val)==&BDFFoundry )
plabel[gc].text = /* def2u_*/ uc_copy( "FontForge" );
else
plabel[gc].text = /* def2u_*/ uc_copy( "" );
plabel[gc].text_is_1byte = false;
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
if ( pl->type==pr_file ) {
pgcd[gc] = pgcd[gc-1];
pgcd[gc-1].gd.pos.width = 140;
hvarray[si++] = GCD_ColSpan;
pgcd[gc].gd.pos.x += 145;
pgcd[gc].gd.cid += CID_PrefsBrowseOffset;
pgcd[gc].gd.label = &plabel[gc];
plabel[gc].text = (unichar_t *) "...";
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.handle_controlevent = Prefs_BrowseFile;
pgcd[gc++].creator = GButtonCreate;
hvarray[si++] = &pgcd[gc-1];
} else if ( pl->set==SetAutoTraceArgs || ((char **) pl->val)==&mf_args ) {
hvarray[si++] = GCD_ColSpan;
hvarray[si++] = GCD_Glue;
} else {
hvarray[si++] = GCD_Glue;
hvarray[si++] = GCD_Glue;
}
y += 26;
if ( pl->val==NULL )
free(tempstr);
break;
case pr_angle:
sprintf(buf,"%g", *((float *) pl->val) * RAD2DEG);
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
plabel[gc].text = (unichar_t *) U_("°");
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.label = &plabel[gc];
pgcd[gc].gd.pos.x = pgcd[gc-1].gd.pos.x+gcd[gc-1].gd.pos.width+2; pgcd[gc].gd.pos.y = pgcd[gc-1].gd.pos.y;
pgcd[gc].gd.flags = gg_enabled|gg_visible;
pgcd[gc++].creator = GLabelCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue;
y += 26;
break;
}
++line;
hvarray[si++] = NULL;
}
harray[4] = 0;
harray[5] = 0;
harray[6] = 0;
harray[7] = 0;
gcd[gc].gd.pos.x = 30-3;
gcd[gc].gd.pos.y = y+5-3;
gcd[gc].gd.pos.width = -1;
gcd[gc].gd.pos.height = 0;
gcd[gc].gd.flags = gg_visible | gg_enabled | gg_but_default;
label[gc].text = (unichar_t *) _("_OK");
label[gc].text_is_1byte = true;
label[gc].text_in_resource = true;
gcd[gc].gd.mnemonic = 'O';
gcd[gc].gd.label = &label[gc];
gcd[gc].gd.handle_controlevent = PrefsSubSet_Ok;
gcd[gc++].creator = GButtonCreate;
harray[0] = GCD_Glue; harray[1] = &gcd[gc-1]; harray[2] = GCD_Glue; harray[3] = GCD_Glue;
memset(mboxes,0,sizeof(mboxes));
memset(mboxes2,0,sizeof(mboxes2));
mboxes[2].gd.pos.x = 2;
mboxes[2].gd.pos.y = 20;
mboxes[2].gd.flags = gg_enabled|gg_visible;
mboxes[2].gd.u.boxelements = harray;
mboxes[2].creator = GHBoxCreate;
mboxes[0].gd.pos.x = mboxes[0].gd.pos.y = 2;
mboxes[0].gd.flags = gg_enabled|gg_visible;
mboxes[0].gd.u.boxelements = hvarray;
mboxes[0].creator = GHVGroupCreate;
varray[0] = &mboxes[0];
varray[1] = &mboxes[2];
varray[2] = 0;
varray[3] = 0;
varray[4] = 0;
/* varray[0] = &mboxes[2]; */
/* varray[1] = 0;//&mboxes[2]; */
/* varray[2] = 0; */
/* varray[3] = 0; */
/* varray[4] = 0; */
mboxes2[0].gd.pos.x = 4;
mboxes2[0].gd.pos.y = 4;
mboxes2[0].gd.flags = gg_enabled|gg_visible;
mboxes2[0].gd.u.boxelements = varray;
mboxes2[0].creator = GVBoxCreate;
GGadgetsCreate(gw,mboxes2);
GDrawSetVisible(gw,true);
while ( !p.done )
GDrawProcessOneEvent(NULL);
GDrawDestroyWindow(gw);
}
void PointerDlg(CharView *cv) {
PrefsSubSetDlg( cv, _("Arrow Options"), pointer_dialog_list );
}
void RulerDlg(CharView *cv) {
PrefsSubSetDlg( cv, _("Ruler Options"), ruler_dialog_list );
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1050_2 |
crossvul-cpp_data_good_341_10 | /*
* util.c: utility functions used by OpenSC command line tools.
*
* Copyright (C) 2011 OpenSC Project developers
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#ifndef _WIN32
#include <termios.h>
#else
#include <conio.h>
#endif
#include <ctype.h>
#include "util.h"
#include "ui/notify.h"
int
is_string_valid_atr(const char *atr_str)
{
unsigned char atr[SC_MAX_ATR_SIZE];
size_t atr_len = sizeof(atr);
if (sc_hex_to_bin(atr_str, atr, &atr_len))
return 0;
if (atr_len < 2)
return 0;
if (atr[0] != 0x3B && atr[0] != 0x3F)
return 0;
return 1;
}
int
util_connect_card_ex(sc_context_t *ctx, sc_card_t **cardp,
const char *reader_id, int do_wait, int do_lock, int verbose)
{
struct sc_reader *reader = NULL, *found = NULL;
struct sc_card *card = NULL;
int r;
sc_notify_init();
if (do_wait) {
unsigned int event;
if (sc_ctx_get_reader_count(ctx) == 0) {
fprintf(stderr, "Waiting for a reader to be attached...\n");
r = sc_wait_for_event(ctx, SC_EVENT_READER_ATTACHED, &found, &event, -1, NULL);
if (r < 0) {
fprintf(stderr, "Error while waiting for a reader: %s\n", sc_strerror(r));
return 3;
}
r = sc_ctx_detect_readers(ctx);
if (r < 0) {
fprintf(stderr, "Error while refreshing readers: %s\n", sc_strerror(r));
return 3;
}
}
fprintf(stderr, "Waiting for a card to be inserted...\n");
r = sc_wait_for_event(ctx, SC_EVENT_CARD_INSERTED, &found, &event, -1, NULL);
if (r < 0) {
fprintf(stderr, "Error while waiting for a card: %s\n", sc_strerror(r));
return 3;
}
reader = found;
}
else if (sc_ctx_get_reader_count(ctx) == 0) {
fprintf(stderr, "No smart card readers found.\n");
return 1;
}
else {
if (!reader_id) {
unsigned int i;
/* Automatically try to skip to a reader with a card if reader not specified */
for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) {
reader = sc_ctx_get_reader(ctx, i);
if (sc_detect_card_presence(reader) & SC_READER_CARD_PRESENT) {
fprintf(stderr, "Using reader with a card: %s\n", reader->name);
goto autofound;
}
}
/* If no reader had a card, default to the first reader */
reader = sc_ctx_get_reader(ctx, 0);
}
else {
/* If the reader identifier looks like an ATR, try to find the reader with that card */
if (is_string_valid_atr(reader_id)) {
unsigned char atr_buf[SC_MAX_ATR_SIZE];
size_t atr_buf_len = sizeof(atr_buf);
unsigned int i;
sc_hex_to_bin(reader_id, atr_buf, &atr_buf_len);
/* Loop readers, looking for a card with ATR */
for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) {
struct sc_reader *rdr = sc_ctx_get_reader(ctx, i);
if (!(sc_detect_card_presence(rdr) & SC_READER_CARD_PRESENT))
continue;
else if (rdr->atr.len != atr_buf_len)
continue;
else if (memcmp(rdr->atr.value, atr_buf, rdr->atr.len))
continue;
fprintf(stderr, "Matched ATR in reader: %s\n", rdr->name);
reader = rdr;
goto autofound;
}
}
else {
char *endptr = NULL;
unsigned int num;
errno = 0;
num = strtol(reader_id, &endptr, 0);
if (!errno && endptr && *endptr == '\0')
reader = sc_ctx_get_reader(ctx, num);
else
reader = sc_ctx_get_reader_by_name(ctx, reader_id);
}
}
autofound:
if (!reader) {
fprintf(stderr, "Reader \"%s\" not found (%d reader(s) detected)\n",
reader_id, sc_ctx_get_reader_count(ctx));
return 1;
}
if (sc_detect_card_presence(reader) <= 0) {
fprintf(stderr, "Card not present.\n");
return 3;
}
}
if (verbose)
printf("Connecting to card in reader %s...\n", reader->name);
r = sc_connect_card(reader, &card);
if (r < 0) {
fprintf(stderr, "Failed to connect to card: %s\n", sc_strerror(r));
return 1;
}
if (verbose)
printf("Using card driver %s.\n", card->driver->name);
if (do_lock) {
r = sc_lock(card);
if (r < 0) {
fprintf(stderr, "Failed to lock card: %s\n", sc_strerror(r));
sc_disconnect_card(card);
return 1;
}
}
*cardp = card;
return 0;
}
int
util_connect_card(sc_context_t *ctx, sc_card_t **cardp,
const char *reader_id, int do_wait, int verbose)
{
return util_connect_card_ex(ctx, cardp, reader_id, do_wait, 1, verbose);
}
void util_print_binary(FILE *f, const u8 *buf, int count)
{
int i;
for (i = 0; i < count; i++) {
unsigned char c = buf[i];
const char *format;
if (!isprint(c))
format = "\\x%02X";
else
format = "%c";
fprintf(f, format, c);
}
(void) fflush(f);
}
void util_hex_dump(FILE *f, const u8 *in, int len, const char *sep)
{
int i;
for (i = 0; i < len; i++) {
if (sep != NULL && i)
fprintf(f, "%s", sep);
fprintf(f, "%02X", in[i]);
}
}
void util_hex_dump_asc(FILE *f, const u8 *in, size_t count, int addr)
{
int lines = 0;
while (count) {
char ascbuf[17];
size_t i;
if (addr >= 0) {
fprintf(f, "%08X: ", addr);
addr += 16;
}
for (i = 0; i < count && i < 16; i++) {
fprintf(f, "%02X ", *in);
if (isprint(*in))
ascbuf[i] = *in;
else
ascbuf[i] = '.';
in++;
}
count -= i;
ascbuf[i] = 0;
for (; i < 16 && lines; i++)
fprintf(f, " ");
fprintf(f, "%s\n", ascbuf);
lines++;
}
}
NORETURN void
util_print_usage_and_die(const char *app_name, const struct option options[],
const char *option_help[], const char *args)
{
int i;
int header_shown = 0;
if (args)
printf("Usage: %s [OPTIONS] %s\n", app_name, args);
else
printf("Usage: %s [OPTIONS]\n", app_name);
for (i = 0; options[i].name; i++) {
char buf[40];
const char *arg_str;
/* Skip "hidden" options */
if (option_help[i] == NULL)
continue;
if (!header_shown++)
printf("Options:\n");
switch (options[i].has_arg) {
case 1:
arg_str = " <arg>";
break;
case 2:
arg_str = " [arg]";
break;
default:
arg_str = "";
break;
}
if (isascii(options[i].val) &&
isprint(options[i].val) && !isspace(options[i].val))
sprintf(buf, "-%c, --%s%s", options[i].val, options[i].name, arg_str);
else
sprintf(buf, " --%s%s", options[i].name, arg_str);
/* print the line - wrap if necessary */
if (strlen(buf) > 28) {
printf(" %s\n", buf);
buf[0] = '\0';
}
printf(" %-28s %s\n", buf, option_help[i]);
}
exit(2);
}
const char * util_acl_to_str(const sc_acl_entry_t *e)
{
static char line[80], buf[20];
unsigned int acl;
if (e == NULL)
return "N/A";
line[0] = 0;
while (e != NULL) {
acl = e->method;
switch (acl) {
case SC_AC_UNKNOWN:
return "N/A";
case SC_AC_NEVER:
return "NEVR";
case SC_AC_NONE:
return "NONE";
case SC_AC_CHV:
strcpy(buf, "CHV");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "%d", e->key_ref);
break;
case SC_AC_TERM:
strcpy(buf, "TERM");
break;
case SC_AC_PRO:
strcpy(buf, "PROT");
break;
case SC_AC_AUT:
strcpy(buf, "AUTH");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 4, "%d", e->key_ref);
break;
case SC_AC_SEN:
strcpy(buf, "Sec.Env. ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
case SC_AC_SCB:
strcpy(buf, "Sec.ControlByte ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "Ox%X", e->key_ref);
break;
case SC_AC_IDA:
strcpy(buf, "PKCS#15 AuthID ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
default:
strcpy(buf, "????");
break;
}
strncat(line, buf, sizeof line);
strncat(line, " ", sizeof line);
e = e->next;
}
line[(sizeof line)-1] = '\0'; /* make sure it's NUL terminated */
line[strlen(line)-1] = 0; /* get rid of trailing space */
return line;
}
NORETURN void
util_fatal(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\nAborting.\n");
va_end(ap);
sc_notify_close();
exit(1);
}
void
util_error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
void
util_warn(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "warning: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
int
util_getpass (char **lineptr, size_t *len, FILE *stream)
{
#define MAX_PASS_SIZE 128
char *buf;
size_t i;
int ch = 0;
#ifndef _WIN32
struct termios old, new;
fflush(stdout);
if (tcgetattr (fileno (stdout), &old) != 0)
return -1;
new = old;
new.c_lflag &= ~ECHO;
if (tcsetattr (fileno (stdout), TCSAFLUSH, &new) != 0)
return -1;
#endif
buf = calloc(1, MAX_PASS_SIZE);
if (!buf)
return -1;
for (i = 0; i < MAX_PASS_SIZE - 1; i++) {
#ifndef _WIN32
ch = getchar();
#else
ch = _getch();
#endif
if (ch == 0 || ch == 3)
break;
if (ch == '\n' || ch == '\r')
break;
buf[i] = (char) ch;
}
#ifndef _WIN32
tcsetattr (fileno (stdout), TCSAFLUSH, &old);
fputs("\n", stdout);
#endif
if (ch == 0 || ch == 3) {
free(buf);
return -1;
}
if (*lineptr && (!len || *len < i+1)) {
free(*lineptr);
*lineptr = NULL;
}
if (*lineptr) {
memcpy(*lineptr,buf,i+1);
memset(buf, 0, MAX_PASS_SIZE);
free(buf);
} else {
*lineptr = buf;
if (len)
*len = MAX_PASS_SIZE;
}
return i;
}
size_t
util_get_pin(const char *input, const char **pin)
{
size_t inputlen = strlen(input);
size_t pinlen = 0;
if(inputlen > 4 && strncasecmp(input, "env:", 4) == 0) {
// Get a PIN from a environment variable
*pin = getenv(input + 4);
pinlen = *pin ? strlen(*pin) : 0;
} else {
//Just use the input
*pin = input;
pinlen = inputlen;
}
return pinlen;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_341_10 |
crossvul-cpp_data_bad_5112_0 | /* cosine.c
*
* CoSine IPNOS L2 debug output parsing
* Copyright (c) 2002 by Motonori Shindo <motonori@shin.do>
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include "wtap-int.h"
#include "cosine.h"
#include "file_wrappers.h"
#include <stdlib.h>
#include <string.h>
/*
IPNOS: CONFIG VPN(100) VR(1.1.1.1)# diags
ipnos diags: Control (1/0) :: layer-2 ?
Registered commands for area "layer-2"
apply-pkt-log-profile Configure packet logging on an interface
create-pkt-log-profile Set packet-log-profile to be used for packet logging (see layer-2 pkt-log)
detail Get Layer 2 low-level details
ipnos diags: Control (1/0) :: layer-2 create ?
create-pkt-log-profile <pkt-log-profile-id ctl-tx-trace-length ctl-rx-trace-length data-tx-trace-length data-rx-trace-length pe-logging-or-control-blade>
ipnos diags: Control (1/0) :: layer-2 create 1 32 32 0 0 0
ipnos diags: Control (1/0) :: layer-2 create 2 32 32 100 100 0
ipnos diags: Control (1/0) :: layer-2 apply ?
apply-pkt-log-profile <slot port channel subif pkt-log-profile-id>
ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 1
Successfully applied packet-log-profile on LI
-- Note that only the control packets are logged because the data packet size parameters are 0 in profile 1
IPNOS: CONFIG VPN(200) VR(3.3.3.3)# ping 20.20.20.43
vpn 200 : [max tries 4, timeout 5 seconds, data length 64 bytes, ttl 255]
ping #1 ok, RTT 0.000 seconds
ping #2 ok, RTT 0.000 seconds
ping #3 ok, RTT 0.000 seconds
ping #4 ok, RTT 0.000 seconds
[finished]
IPNOS: CONFIG VPN(200) VR(3.3.3.3)# 2000-2-1,18:19:46.8: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
2000-2-1,18:19:46.8: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000]
2000-2-1,18:19:46.8: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
2000-2-1,18:19:46.8: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x8030000]
ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 0
Successfully applied packet-log-profile on LI
ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 2
Successfully applied packet-log-profile on LI
-- Note that both control and data packets are logged because the data packet size parameter is 100 in profile 2
Please ignore the event-log messages getting mixed up with the ping command
ping 20.20.20.43 cou2000-2-1,18:20:17.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
00 D0 D8 D2 FF 03 C0 21 09 29 00 08 6B 60 84 AA
2000-2-1,18:20:17.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000]
00 D0 D8 D2 FF 03 C0 21 09 29 00 08 6D FE FA AA
2000-2-1,18:20:17.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
00 D0 D8 D2 FF 03 C0 21 0A 29 00 08 6B 60 84 AA
2000-2-1,18:20:17.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x8030000]
00 D0 D8 D2 FF 03 C0 21 0A 29 00 08 6D FE FA AA
nt 1 length 500
vpn 200 : [max tries 1, timeout 5 seconds, data length 500 bytes, ttl 255]
2000-2-1,18:20:24.1: l2-tx (PPP:3/7/1:100), Length:536, Pro:1, Off:8, Pri:7, RM:0, Err:0 [0x4070, 0x801]
00 D0 D8 D2 FF 03 00 21 45 00 02 10 00 27 00 00
FF 01 69 51 14 14 14 22 14 14 14 2B 08 00 AD B8
00 03 00 01 10 11 12 13 14 15 16 17 18 19 1A 1B
1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B
2C 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B
3C 3D 3E 3F 40 41 42 43 44 45 46 47 48 49 4A 4B
4C 4D 4E 4F
ping #1 ok, RTT 0.010 seconds
2000-2-1,18:20:24.1: l2-rx (PPP:3/7/1:100), Length:536, Pro:1, Off:8, Pri:7, RM:0, Err:0 [0x4071, 0x30801]
00 D0 D8 D2 FF 03 00 21 45 00 02 10 00 23 00 00
FF 01 69 55 14 14 14 2B 14 14 14 22 00 00 B5 B8
00 03 00 01 10 11 12 13 14 15 16 17 18 19 1A 1B
1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B
2C 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B
3C 3D 3E 3F 40 41 42 43 44 45 46 47 48 49 4A 4B
4C 4D 4E 4F
[finished]
IPNOS: CONFIG VPN(200) VR(3.3.3.3)# 2000-2-1,18:20:27.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
00 D0 D8 D2 FF 03 C0 21 09 2A 00 08 6B 60 84 AA
2000-2-1,18:20:27.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000]
00 D0 D8 D2 FF 03 C0 21 09 2A 00 08 6D FE FA AA
2000-2-1,18:20:27.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
00 D0 D8 D2 FF 03 C0 21 0A 2A 00 08 6B 60 84 AA
2000-2-1,18:20:27.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000]
00 D0 D8 D2 FF 03 C0 21 0A 2A 00 08 6D FE FA AA
ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 0
Successfully applied packet-log-profile on LI
ipnos diags: Control (1/0) ::
*/
/* XXX TODO:
o Handle a case where an empty line doesn't exists as a delimiter of
each packet. If the output is sent to a control blade and
displayed as an event log, there's always an empty line between
each packet output, but it may not be true when it is an PE
output.
o Some telnet client on Windows may put in a line break at 80
columns when it save the session to a text file ("CRT" is such an
example). I don't think it's a good idea for the telnet client to
do so, but CRT is widely used in Windows community, I should
take care of that in the future.
*/
/* Magic text to check for CoSine L2 debug output */
#define COSINE_HDR_MAGIC_STR1 "l2-tx"
#define COSINE_HDR_MAGIC_STR2 "l2-rx"
/* Magic text for start of packet */
#define COSINE_REC_MAGIC_STR1 COSINE_HDR_MAGIC_STR1
#define COSINE_REC_MAGIC_STR2 COSINE_HDR_MAGIC_STR2
#define COSINE_HEADER_LINES_TO_CHECK 200
#define COSINE_LINE_LENGTH 240
#define COSINE_MAX_PACKET_LEN 65536
static gboolean empty_line(const gchar *line);
static gint64 cosine_seek_next_packet(wtap *wth, int *err, gchar **err_info,
char *hdr);
static gboolean cosine_check_file_type(wtap *wth, int *err, gchar **err_info);
static gboolean cosine_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset);
static gboolean cosine_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info);
static int parse_cosine_rec_hdr(struct wtap_pkthdr *phdr, const char *line,
int *err, gchar **err_info);
static gboolean parse_cosine_hex_dump(FILE_T fh, struct wtap_pkthdr *phdr,
int pkt_len, Buffer* buf, int *err, gchar **err_info);
static int parse_single_hex_dump_line(char* rec, guint8 *buf,
guint byte_offset);
/* Returns TRUE if the line appears to be an empty line. Otherwise it
returns FALSE. */
static gboolean empty_line(const gchar *line)
{
while (*line) {
if (g_ascii_isspace(*line)) {
line++;
continue;
} else {
break;
}
}
if (*line == '\0')
return TRUE;
else
return FALSE;
}
/* Seeks to the beginning of the next packet, and returns the
byte offset. Copy the header line to hdr. Returns -1 on failure,
and sets "*err" to the error and sets "*err_info" to null or an
additional error string. */
static gint64 cosine_seek_next_packet(wtap *wth, int *err, gchar **err_info,
char *hdr)
{
gint64 cur_off;
char buf[COSINE_LINE_LENGTH];
while (1) {
cur_off = file_tell(wth->fh);
if (cur_off == -1) {
/* Error */
*err = file_error(wth->fh, err_info);
return -1;
}
if (file_gets(buf, sizeof(buf), wth->fh) == NULL) {
*err = file_error(wth->fh, err_info);
return -1;
}
if (strstr(buf, COSINE_REC_MAGIC_STR1) ||
strstr(buf, COSINE_REC_MAGIC_STR2)) {
g_strlcpy(hdr, buf, COSINE_LINE_LENGTH);
return cur_off;
}
}
return -1;
}
/* Look through the first part of a file to see if this is
* a CoSine L2 debug output.
*
* Returns TRUE if it is, FALSE if it isn't or if we get an I/O error;
* if we get an I/O error, "*err" will be set to a non-zero value and
* "*err_info" will be set to null or an additional error string.
*/
static gboolean cosine_check_file_type(wtap *wth, int *err, gchar **err_info)
{
char buf[COSINE_LINE_LENGTH];
gsize reclen;
guint line;
buf[COSINE_LINE_LENGTH-1] = '\0';
for (line = 0; line < COSINE_HEADER_LINES_TO_CHECK; line++) {
if (file_gets(buf, COSINE_LINE_LENGTH, wth->fh) == NULL) {
/* EOF or error. */
*err = file_error(wth->fh, err_info);
return FALSE;
}
reclen = strlen(buf);
if (reclen < strlen(COSINE_HDR_MAGIC_STR1) ||
reclen < strlen(COSINE_HDR_MAGIC_STR2)) {
continue;
}
if (strstr(buf, COSINE_HDR_MAGIC_STR1) ||
strstr(buf, COSINE_HDR_MAGIC_STR2)) {
return TRUE;
}
}
*err = 0;
return FALSE;
}
wtap_open_return_val cosine_open(wtap *wth, int *err, gchar **err_info)
{
/* Look for CoSine header */
if (!cosine_check_file_type(wth, err, err_info)) {
if (*err != 0 && *err != WTAP_ERR_SHORT_READ)
return WTAP_OPEN_ERROR;
return WTAP_OPEN_NOT_MINE;
}
if (file_seek(wth->fh, 0L, SEEK_SET, err) == -1) /* rewind */
return WTAP_OPEN_ERROR;
wth->file_encap = WTAP_ENCAP_COSINE;
wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_COSINE;
wth->snapshot_length = 0; /* not known */
wth->subtype_read = cosine_read;
wth->subtype_seek_read = cosine_seek_read;
wth->file_tsprec = WTAP_TSPREC_CSEC;
return WTAP_OPEN_MINE;
}
/* Find the next packet and parse it; called from wtap_read(). */
static gboolean cosine_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset)
{
gint64 offset;
int pkt_len;
char line[COSINE_LINE_LENGTH];
/* Find the next packet */
offset = cosine_seek_next_packet(wth, err, err_info, line);
if (offset < 0)
return FALSE;
*data_offset = offset;
/* Parse the header */
pkt_len = parse_cosine_rec_hdr(&wth->phdr, line, err, err_info);
if (pkt_len == -1)
return FALSE;
/* Convert the ASCII hex dump to binary data */
return parse_cosine_hex_dump(wth->fh, &wth->phdr, pkt_len,
wth->frame_buffer, err, err_info);
}
/* Used to read packets in random-access fashion */
static gboolean
cosine_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr,
Buffer *buf, int *err, gchar **err_info)
{
int pkt_len;
char line[COSINE_LINE_LENGTH];
if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
return FALSE;
if (file_gets(line, COSINE_LINE_LENGTH, wth->random_fh) == NULL) {
*err = file_error(wth->random_fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Parse the header */
pkt_len = parse_cosine_rec_hdr(phdr, line, err, err_info);
if (pkt_len == -1)
return FALSE;
/* Convert the ASCII hex dump to binary data */
return parse_cosine_hex_dump(wth->random_fh, phdr, pkt_len, buf, err,
err_info);
}
/* Parses a packet record header. There are two possible formats:
1) output to a control blade with date and time
2002-5-10,20:1:31.4: l2-tx (FR:3/7/1:1), Length:18, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
2) output to PE without date and time
l2-tx (FR:3/7/1:1), Length:18, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0] */
static int
parse_cosine_rec_hdr(struct wtap_pkthdr *phdr, const char *line,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
int num_items_scanned;
int yy, mm, dd, hr, min, sec, csec, pkt_len;
int pro, off, pri, rm, error;
guint code1, code2;
char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = "";
struct tm tm;
if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:",
&yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) {
/* appears to be output to a control blade */
num_items_scanned = sscanf(line,
"%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]",
&yy, &mm, &dd, &hr, &min, &sec, &csec,
direction, if_name, &pkt_len,
&pro, &off, &pri, &rm, &error,
&code1, &code2);
if (num_items_scanned != 17) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: purported control blade line doesn't have code values");
return -1;
}
} else {
/* appears to be output to PE */
num_items_scanned = sscanf(line,
"%5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]",
direction, if_name, &pkt_len,
&pro, &off, &pri, &rm, &error,
&code1, &code2);
if (num_items_scanned != 10) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: header line is neither control blade nor PE output");
return -1;
}
yy = mm = dd = hr = min = sec = csec = 0;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
tm.tm_year = yy - 1900;
tm.tm_mon = mm - 1;
tm.tm_mday = dd;
tm.tm_hour = hr;
tm.tm_min = min;
tm.tm_sec = sec;
tm.tm_isdst = -1;
phdr->ts.secs = mktime(&tm);
phdr->ts.nsecs = csec * 10000000;
phdr->len = pkt_len;
/* XXX need to handle other encapsulations like Cisco HDLC,
Frame Relay and ATM */
if (strncmp(if_name, "TEST:", 5) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_TEST;
} else if (strncmp(if_name, "PPoATM:", 7) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM;
} else if (strncmp(if_name, "PPoFR:", 6) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR;
} else if (strncmp(if_name, "ATM:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_ATM;
} else if (strncmp(if_name, "FR:", 3) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_FR;
} else if (strncmp(if_name, "HDLC:", 5) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_HDLC;
} else if (strncmp(if_name, "PPP:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPP;
} else if (strncmp(if_name, "ETH:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_ETH;
} else {
pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN;
}
if (strncmp(direction, "l2-tx", 5) == 0) {
pseudo_header->cosine.direction = COSINE_DIR_TX;
} else if (strncmp(direction, "l2-rx", 5) == 0) {
pseudo_header->cosine.direction = COSINE_DIR_RX;
}
g_strlcpy(pseudo_header->cosine.if_name, if_name,
COSINE_MAX_IF_NAME_LEN);
pseudo_header->cosine.pro = pro;
pseudo_header->cosine.off = off;
pseudo_header->cosine.pri = pri;
pseudo_header->cosine.rm = rm;
pseudo_header->cosine.err = error;
return pkt_len;
}
/* Converts ASCII hex dump to binary data. Returns TRUE on success,
FALSE if any error is encountered. */
static gboolean
parse_cosine_hex_dump(FILE_T fh, struct wtap_pkthdr *phdr, int pkt_len,
Buffer* buf, int *err, gchar **err_info)
{
guint8 *pd;
gchar line[COSINE_LINE_LENGTH];
int i, hex_lines, n, caplen = 0;
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, COSINE_MAX_PACKET_LEN);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (empty_line(line)) {
break;
}
if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers");
return FALSE;
}
caplen += n;
}
phdr->caplen = caplen;
return TRUE;
}
/* Take a string representing one line from a hex dump and converts
* the text to binary data. We place the bytes in the buffer at the
* specified offset.
*
* Returns number of bytes successfully read, -1 if bad. */
static int
parse_single_hex_dump_line(char* rec, guint8 *buf, guint byte_offset)
{
int num_items_scanned, i;
unsigned int bytes[16];
num_items_scanned = sscanf(rec, "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
&bytes[0], &bytes[1], &bytes[2], &bytes[3],
&bytes[4], &bytes[5], &bytes[6], &bytes[7],
&bytes[8], &bytes[9], &bytes[10], &bytes[11],
&bytes[12], &bytes[13], &bytes[14], &bytes[15]);
if (num_items_scanned == 0)
return -1;
if (num_items_scanned > 16)
num_items_scanned = 16;
for (i=0; i<num_items_scanned; i++) {
buf[byte_offset + i] = (guint8)bytes[i];
}
return num_items_scanned;
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5112_0 |
crossvul-cpp_data_bad_2540_0 | /* $Id: upnpreplyparse.c,v 1.19 2015/07/15 10:29:11 nanard Exp $ */
/* MiniUPnP project
* http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/
* (c) 2006-2015 Thomas Bernard
* This software is subject to the conditions detailed
* in the LICENCE file provided within the distribution */
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "upnpreplyparse.h"
#include "minixml.h"
static void
NameValueParserStartElt(void * d, const char * name, int l)
{
struct NameValueParserData * data = (struct NameValueParserData *)d;
data->topelt = 1;
if(l>63)
l = 63;
memcpy(data->curelt, name, l);
data->curelt[l] = '\0';
data->cdata = NULL;
data->cdatalen = 0;
}
static void
NameValueParserEndElt(void * d, const char * name, int l)
{
struct NameValueParserData * data = (struct NameValueParserData *)d;
struct NameValue * nv;
(void)name;
(void)l;
if(!data->topelt)
return;
if(strcmp(data->curelt, "NewPortListing") != 0)
{
int l;
/* standard case. Limited to n chars strings */
l = data->cdatalen;
nv = malloc(sizeof(struct NameValue));
if(nv == NULL)
{
/* malloc error */
#ifdef DEBUG
fprintf(stderr, "%s: error allocating memory",
"NameValueParserEndElt");
#endif /* DEBUG */
return;
}
if(l>=(int)sizeof(nv->value))
l = sizeof(nv->value) - 1;
strncpy(nv->name, data->curelt, 64);
nv->name[63] = '\0';
if(data->cdata != NULL)
{
memcpy(nv->value, data->cdata, l);
nv->value[l] = '\0';
}
else
{
nv->value[0] = '\0';
}
nv->l_next = data->l_head; /* insert in list */
data->l_head = nv;
}
data->cdata = NULL;
data->cdatalen = 0;
data->topelt = 0;
}
static void
NameValueParserGetData(void * d, const char * datas, int l)
{
struct NameValueParserData * data = (struct NameValueParserData *)d;
if(strcmp(data->curelt, "NewPortListing") == 0)
{
/* specific case for NewPortListing which is a XML Document */
data->portListing = malloc(l + 1);
if(!data->portListing)
{
/* malloc error */
#ifdef DEBUG
fprintf(stderr, "%s: error allocating memory",
"NameValueParserGetData");
#endif /* DEBUG */
return;
}
memcpy(data->portListing, datas, l);
data->portListing[l] = '\0';
data->portListingLength = l;
}
else
{
/* standard case. */
data->cdata = datas;
data->cdatalen = l;
}
}
void
ParseNameValue(const char * buffer, int bufsize,
struct NameValueParserData * data)
{
struct xmlparser parser;
data->l_head = NULL;
data->portListing = NULL;
data->portListingLength = 0;
/* init xmlparser object */
parser.xmlstart = buffer;
parser.xmlsize = bufsize;
parser.data = data;
parser.starteltfunc = NameValueParserStartElt;
parser.endeltfunc = NameValueParserEndElt;
parser.datafunc = NameValueParserGetData;
parser.attfunc = 0;
parsexml(&parser);
}
void
ClearNameValueList(struct NameValueParserData * pdata)
{
struct NameValue * nv;
if(pdata->portListing)
{
free(pdata->portListing);
pdata->portListing = NULL;
pdata->portListingLength = 0;
}
while((nv = pdata->l_head) != NULL)
{
pdata->l_head = nv->l_next;
free(nv);
}
}
char *
GetValueFromNameValueList(struct NameValueParserData * pdata,
const char * Name)
{
struct NameValue * nv;
char * p = NULL;
for(nv = pdata->l_head;
(nv != NULL) && (p == NULL);
nv = nv->l_next)
{
if(strcmp(nv->name, Name) == 0)
p = nv->value;
}
return p;
}
#if 0
/* useless now that minixml ignores namespaces by itself */
char *
GetValueFromNameValueListIgnoreNS(struct NameValueParserData * pdata,
const char * Name)
{
struct NameValue * nv;
char * p = NULL;
char * pname;
for(nv = pdata->head.lh_first;
(nv != NULL) && (p == NULL);
nv = nv->entries.le_next)
{
pname = strrchr(nv->name, ':');
if(pname)
pname++;
else
pname = nv->name;
if(strcmp(pname, Name)==0)
p = nv->value;
}
return p;
}
#endif
/* debug all-in-one function
* do parsing then display to stdout */
#ifdef DEBUG
void
DisplayNameValueList(char * buffer, int bufsize)
{
struct NameValueParserData pdata;
struct NameValue * nv;
ParseNameValue(buffer, bufsize, &pdata);
for(nv = pdata.l_head;
nv != NULL;
nv = nv->l_next)
{
printf("%s = %s\n", nv->name, nv->value);
}
ClearNameValueList(&pdata);
}
#endif /* DEBUG */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2540_0 |
crossvul-cpp_data_bad_4779_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M M AAA PPPP %
% MM MM A A P P %
% M M M AAAAA PPPP %
% M M A A P %
% M M A A P %
% %
% %
% Read/Write Image Colormaps As An Image File. %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% 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/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/histogram.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteMAPImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d M A P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadMAPImage() reads an image of raw RGB colormap and colormap index
% bytes 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 ReadMAPImage method is:
%
% Image *ReadMAPImage(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 *ReadMAPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
depth,
packet_size,
quantum;
ssize_t
count,
y;
unsigned char
*colormap,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
image->storage_class=PseudoClass;
status=AcquireImageColormap(image,(size_t)
(image->offset != 0 ? image->offset : 256));
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Read image colormap.
*/
count=ReadBlob(image,packet_size*image->colors,colormap);
if (count != (ssize_t) (packet_size*image->colors))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
p=colormap;
if (image->depth <= 8)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].blue=ScaleCharToQuantum(*p++);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
quantum=(*p++ << 8);
quantum|=(*p++);
image->colormap[i].red=(Quantum) quantum;
quantum=(*p++ << 8);
quantum|=(*p++);
image->colormap[i].green=(Quantum) quantum;
quantum=(*p++ << 8);
quantum|=(*p++);
image->colormap[i].blue=(Quantum) quantum;
}
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
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));
}
/*
Read image pixels.
*/
packet_size=(size_t) (depth/8);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
count=ReadBlob(image,(size_t) packet_size*image->columns,pixels);
if (count != (ssize_t) (packet_size*image->columns))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p);
p++;
if (image->colors > 256)
{
index=ConstrainColormapIndex(image,((size_t) index << 8)+(*p));
p++;
}
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (y < (ssize_t) image->rows)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r M A P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterMAPImage() adds attributes for the MAP 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 RegisterMAPImage method is:
%
% size_t RegisterMAPImage(void)
%
*/
ModuleExport size_t RegisterMAPImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("MAP");
entry->decoder=(DecodeImageHandler *) ReadMAPImage;
entry->encoder=(EncodeImageHandler *) WriteMAPImage;
entry->adjoin=MagickFalse;
entry->format_type=ExplicitFormatType;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Colormap intensities and indices");
entry->module=ConstantString("MAP");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r M A P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterMAPImage() removes format registrations made by the
% MAP module from the list of supported formats.
%
% The format of the UnregisterMAPImage method is:
%
% UnregisterMAPImage(void)
%
*/
ModuleExport void UnregisterMAPImage(void)
{
(void) UnregisterMagickInfo("MAP");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M A P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteMAPImage() writes an image to a file as red, green, and blue
% colormap bytes followed by the colormap indexes.
%
% The format of the WriteMAPImage method is:
%
% MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
%
*/
static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
depth,
packet_size;
ssize_t
y;
unsigned char
*colormap,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Allocate colormap.
*/
if (IsPaletteImage(image,&image->exception) == MagickFalse)
(void) SetImageType(image,PaletteType);
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Write colormap to file.
*/
q=colormap;
if (image->depth <= 8)
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) image->colormap[i].red;
*q++=(unsigned char) image->colormap[i].green;
*q++=(unsigned char) image->colormap[i].blue;
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) ((size_t) image->colormap[i].red >> 8);
*q++=(unsigned char) image->colormap[i].red;
*q++=(unsigned char) ((size_t) image->colormap[i].green >> 8);
*q++=(unsigned char) image->colormap[i].green;
*q++=(unsigned char) ((size_t) image->colormap[i].blue >> 8);
*q++=(unsigned char) image->colormap[i].blue;
}
(void) WriteBlob(image,packet_size*image->colors,colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
/*
Write image pixels to file.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->colors > 256)
*q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8);
*q++=(unsigned char) GetPixelIndex(indexes+x);
}
(void) WriteBlob(image,(size_t) (q-pixels),pixels);
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4779_1 |
crossvul-cpp_data_good_5484_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS GGGG IIIII %
% SS G I %
% SSS G GG I %
% SS G G I %
% SSSSS GGG IIIII %
% %
% %
% Read/Write Irix RGB Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% 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 "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/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
/*
Typedef declaractions.
*/
typedef struct _SGIInfo
{
unsigned short
magic;
unsigned char
storage,
bytes_per_pixel;
unsigned short
dimension,
columns,
rows,
depth;
size_t
minimum_value,
maximum_value,
sans;
char
name[80];
size_t
pixel_format;
unsigned char
filler[404];
} SGIInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WriteSGIImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s S G I %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsSGI() returns MagickTrue if the image format type, identified by the
% magick string, is SGI.
%
% The format of the IsSGI method is:
%
% MagickBooleanType IsSGI(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 IsSGI(const unsigned char *magick,const size_t length)
{
if (length < 2)
return(MagickFalse);
if (memcmp(magick,"\001\332",2) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadSGIImage() reads a SGI RGB 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 ReadSGIImage method is:
%
% Image *ReadSGIImage(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 SGIDecode(const size_t bytes_per_pixel,
ssize_t number_packets,unsigned char *packets,ssize_t number_pixels,
unsigned char *pixels)
{
register unsigned char
*p,
*q;
size_t
pixel;
ssize_t
count;
p=packets;
q=pixels;
if (bytes_per_pixel == 2)
{
for ( ; number_pixels > 0; )
{
if (number_packets-- == 0)
return(MagickFalse);
pixel=(size_t) (*p++) << 8;
pixel|=(*p++);
count=(ssize_t) (pixel & 0x7f);
if (count == 0)
break;
if (count > (ssize_t) number_pixels)
return(MagickFalse);
number_pixels-=count;
if ((pixel & 0x80) != 0)
for ( ; count != 0; count--)
{
if (number_packets-- == 0)
return(MagickFalse);
*q=(*p++);
*(q+1)=(*p++);
q+=8;
}
else
{
if (number_packets-- == 0)
return(MagickFalse);
pixel=(size_t) (*p++) << 8;
pixel|=(*p++);
for ( ; count != 0; count--)
{
*q=(unsigned char) (pixel >> 8);
*(q+1)=(unsigned char) pixel;
q+=8;
}
}
}
return(MagickTrue);
}
for ( ; number_pixels > 0; )
{
if (number_packets-- == 0)
return(MagickFalse);
pixel=(size_t) (*p++);
count=(ssize_t) (pixel & 0x7f);
if (count == 0)
break;
if (count > (ssize_t) number_pixels)
return(MagickFalse);
number_pixels-=count;
if ((pixel & 0x80) != 0)
for ( ; count != 0; count--)
{
if (number_packets-- == 0)
return(MagickFalse);
*q=(*p++);
q+=4;
}
else
{
if (number_packets-- == 0)
return(MagickFalse);
pixel=(size_t) (*p++);
for ( ; count != 0; count--)
{
*q=(unsigned char) pixel;
q+=4;
}
}
}
return(MagickTrue);
}
static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
SGIInfo
iris_info;
size_t
bytes_per_pixel,
quantum;
ssize_t
count,
y,
z;
unsigned char
*pixels;
/*
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 SGI raster header.
*/
iris_info.magic=ReadBlobMSBShort(image);
do
{
/*
Verify SGI identifier.
*/
if (iris_info.magic != 0x01DA)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.storage=(unsigned char) ReadBlobByte(image);
switch (iris_info.storage)
{
case 0x00: image->compression=NoCompression; break;
case 0x01: image->compression=RLECompression; break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image);
if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.dimension=ReadBlobMSBShort(image);
if ((iris_info.dimension == 0) || (iris_info.dimension > 3))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.columns=ReadBlobMSBShort(image);
iris_info.rows=ReadBlobMSBShort(image);
iris_info.depth=ReadBlobMSBShort(image);
if ((iris_info.depth == 0) || (iris_info.depth > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.minimum_value=ReadBlobMSBLong(image);
iris_info.maximum_value=ReadBlobMSBLong(image);
iris_info.sans=ReadBlobMSBLong(image);
count=ReadBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
if ((size_t) count != sizeof(iris_info.name))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.name[sizeof(iris_info.name)-1]='\0';
if (*iris_info.name != '\0')
(void) SetImageProperty(image,"label",iris_info.name,exception);
iris_info.pixel_format=ReadBlobMSBLong(image);
if (iris_info.pixel_format != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler);
if ((size_t) count != sizeof(iris_info.filler))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=iris_info.columns;
image->rows=iris_info.rows;
image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.pixel_format == 0)
image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel,
MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.depth < 3)
{
image->storage_class=PseudoClass;
image->colors=(size_t) (iris_info.bytes_per_pixel > 1 ? 65535 : 256);
}
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));
/*
Allocate SGI pixels.
*/
bytes_per_pixel=(size_t) iris_info.bytes_per_pixel;
number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows;
if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t)
(4*bytes_per_pixel*number_pixels)))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4*
bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((int) iris_info.storage != 0x01)
{
unsigned char
*scanline;
/*
Read standard image format.
*/
scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns,
bytes_per_pixel*sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels+bytes_per_pixel*z;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline);
if (EOFBlob(image) != MagickFalse)
break;
if (bytes_per_pixel == 2)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[2*x];
*(p+1)=scanline[2*x+1];
p+=8;
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[x];
p+=4;
}
}
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
}
else
{
MemoryInfo
*packet_info;
size_t
*runlength;
ssize_t
offset,
*offsets;
unsigned char
*packets;
unsigned int
data_order;
/*
Read runlength-encoded image format.
*/
offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL*
sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
if (offsets == (ssize_t *) NULL)
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
if (runlength == (size_t *) NULL)
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info == (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
offsets[i]=(ssize_t) ReadBlobMSBSignedLong(image);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
{
runlength[i]=ReadBlobMSBLong(image);
if (runlength[i] > (4*(size_t) iris_info.columns+10))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Check data order.
*/
offset=0;
data_order=0;
for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++)
for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++)
{
if (offsets[y+z*iris_info.rows] < offset)
data_order=1;
offset=offsets[y+z*iris_info.rows];
}
offset=(ssize_t) TellBlob(image);
if (data_order == 1)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset,
SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
(ssize_t) iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
p+=(iris_info.columns*4*bytes_per_pixel);
}
}
}
else
{
MagickOffsetType
position;
position=TellBlob(image);
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset,
SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
(ssize_t) iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
p+=(iris_info.columns*4*bytes_per_pixel);
}
offset=(ssize_t) SeekBlob(image,position,SEEK_SET);
}
packet_info=RelinquishVirtualMemory(packet_info);
runlength=(size_t *) RelinquishMagickMemory(runlength);
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
}
/*
Initialize image structure.
*/
image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
/*
Convert SGI raster image to pixel packets.
*/
if (image->storage_class == DirectClass)
{
/*
Convert SGI image to DirectClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleShortToQuantum((unsigned short)
((*(p+0) << 8) | (*(p+1)))),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short)
((*(p+2) << 8) | (*(p+3)))),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short)
((*(p+4) << 8) | (*(p+5)))),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleShortToQuantum((unsigned short)
((*(p+6) << 8) | (*(p+7)))),q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p),q);
SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q);
SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create grayscale map.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert SGI image to PseudoClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=(*p << 8);
quantum|=(*(p+1));
SetPixelIndex(image,(Quantum) quantum,q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p,q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
iris_info.magic=ReadBlobMSBShort(image);
if (iris_info.magic == 0x01DA)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (iris_info.magic == 0x01DA);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterSGIImage() adds properties for the SGI 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 RegisterSGIImage method is:
%
% size_t RegisterSGIImage(void)
%
*/
ModuleExport size_t RegisterSGIImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("SGI","SGI","Irix RGB image");
entry->decoder=(DecodeImageHandler *) ReadSGIImage;
entry->encoder=(EncodeImageHandler *) WriteSGIImage;
entry->magick=(IsImageFormatHandler *) IsSGI;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterSGIImage() removes format registrations made by the
% SGI module from the list of supported formats.
%
% The format of the UnregisterSGIImage method is:
%
% UnregisterSGIImage(void)
%
*/
ModuleExport void UnregisterSGIImage(void)
{
(void) UnregisterMagickInfo("SGI");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteSGIImage() writes an image in SGI RGB encoded image format.
%
% The format of the WriteSGIImage method is:
%
% MagickBooleanType WriteSGIImage(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 size_t SGIEncode(unsigned char *pixels,size_t length,
unsigned char *packets)
{
short
runlength;
register unsigned char
*p,
*q;
unsigned char
*limit,
*mark;
p=pixels;
limit=p+length*4;
q=packets;
while (p < limit)
{
mark=p;
p+=8;
while ((p < limit) && ((*(p-8) != *(p-4)) || (*(p-4) != *p)))
p+=4;
p-=8;
length=(size_t) (p-mark) >> 2;
while (length != 0)
{
runlength=(short) (length > 126 ? 126 : length);
length-=runlength;
*q++=(unsigned char) (0x80 | runlength);
for ( ; runlength > 0; runlength--)
{
*q++=(*mark);
mark+=4;
}
}
mark=p;
p+=4;
while ((p < limit) && (*p == *mark))
p+=4;
length=(size_t) (p-mark) >> 2;
while (length != 0)
{
runlength=(short) (length > 126 ? 126 : length);
length-=runlength;
*q++=(unsigned char) runlength;
*q++=(*mark);
}
}
*q++='\0';
return((size_t) (q-packets));
}
static MagickBooleanType WriteSGIImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
CompressionType
compression;
const char
*value;
MagickBooleanType
status;
MagickOffsetType
scene;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
SGIInfo
iris_info;
register const Quantum
*p;
register ssize_t
i,
x;
register unsigned char
*q;
ssize_t
y,
z;
unsigned char
*pixels,
*packets;
/*
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);
if ((image->columns > 65535UL) || (image->rows > 65535UL))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
/*
Initialize SGI raster file header.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) ResetMagickMemory(&iris_info,0,sizeof(iris_info));
iris_info.magic=0x01DA;
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
if (image->depth > 8)
compression=NoCompression;
if (compression == NoCompression)
iris_info.storage=(unsigned char) 0x00;
else
iris_info.storage=(unsigned char) 0x01;
iris_info.bytes_per_pixel=(unsigned char) (image->depth > 8 ? 2 : 1);
iris_info.dimension=3;
iris_info.columns=(unsigned short) image->columns;
iris_info.rows=(unsigned short) image->rows;
if (image->alpha_trait != UndefinedPixelTrait)
iris_info.depth=4;
else
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse))
{
iris_info.dimension=2;
iris_info.depth=1;
}
else
iris_info.depth=3;
}
iris_info.minimum_value=0;
iris_info.maximum_value=(size_t) (image->depth <= 8 ?
1UL*ScaleQuantumToChar(QuantumRange) :
1UL*ScaleQuantumToShort(QuantumRange));
/*
Write SGI header.
*/
(void) WriteBlobMSBShort(image,iris_info.magic);
(void) WriteBlobByte(image,iris_info.storage);
(void) WriteBlobByte(image,iris_info.bytes_per_pixel);
(void) WriteBlobMSBShort(image,iris_info.dimension);
(void) WriteBlobMSBShort(image,iris_info.columns);
(void) WriteBlobMSBShort(image,iris_info.rows);
(void) WriteBlobMSBShort(image,iris_info.depth);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.minimum_value);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.maximum_value);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.sans);
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(iris_info.name,value,sizeof(iris_info.name));
(void) WriteBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.pixel_format);
(void) WriteBlob(image,sizeof(iris_info.filler),iris_info.filler);
/*
Allocate SGI pixels.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((4*iris_info.bytes_per_pixel*number_pixels) !=
((MagickSizeType) (size_t) (4*iris_info.bytes_per_pixel*number_pixels)))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory((size_t) number_pixels,4*
iris_info.bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Convert image pixels to uncompressed SGI 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;
if (image->depth <= 8)
for (x=0; x < (ssize_t) image->columns; x++)
{
register unsigned char
*q;
q=(unsigned char *) pixels;
q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x;
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
register unsigned short
*q;
q=(unsigned short *) pixels;
q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x;
*q++=ScaleQuantumToShort(GetPixelRed(image,p));
*q++=ScaleQuantumToShort(GetPixelGreen(image,p));
*q++=ScaleQuantumToShort(GetPixelBlue(image,p));
*q++=ScaleQuantumToShort(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
switch (compression)
{
case NoCompression:
{
/*
Write uncompressed SGI pixels.
*/
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (image->depth <= 8)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
register unsigned char
*q;
q=(unsigned char *) pixels;
q+=y*(4*iris_info.columns)+4*x+z;
(void) WriteBlobByte(image,*q);
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
register unsigned short
*q;
q=(unsigned short *) pixels;
q+=y*(4*iris_info.columns)+4*x+z;
(void) WriteBlobMSBShort(image,*q);
}
}
}
break;
}
default:
{
MemoryInfo
*packet_info;
size_t
length,
number_packets,
*runlength;
ssize_t
offset,
*offsets;
/*
Convert SGI uncompressed pixels.
*/
offsets=(ssize_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((2*(size_t) iris_info.columns+10)*
image->rows,4*sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
if (offsets != (ssize_t *) NULL)
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
if (runlength != (size_t *) NULL)
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info != (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
offset=512+4*2*((ssize_t) iris_info.rows*iris_info.depth);
number_packets=0;
q=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
length=SGIEncode(q+z,(size_t) iris_info.columns,packets+
number_packets);
number_packets+=length;
offsets[y+z*iris_info.rows]=offset;
runlength[y+z*iris_info.rows]=(size_t) length;
offset+=(ssize_t) length;
}
q+=(iris_info.columns*4);
}
/*
Write out line start and length tables and runlength-encoded pixels.
*/
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
(void) WriteBlobMSBLong(image,(unsigned int) offsets[i]);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
(void) WriteBlobMSBLong(image,(unsigned int) runlength[i]);
(void) WriteBlob(image,number_packets,packets);
/*
Relinquish resources.
*/
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
runlength=(size_t *) RelinquishMagickMemory(runlength);
packet_info=RelinquishVirtualMemory(packet_info);
break;
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5484_0 |
crossvul-cpp_data_good_3115_0 | /*
* HID driver for Corsair devices
*
* Supported devices:
* - Vengeance K90 Keyboard
*
* Copyright (c) 2015 Clement Vuchener
*/
/*
* 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/hid.h>
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/leds.h>
#include "hid-ids.h"
#define CORSAIR_USE_K90_MACRO (1<<0)
#define CORSAIR_USE_K90_BACKLIGHT (1<<1)
struct k90_led {
struct led_classdev cdev;
int brightness;
struct work_struct work;
bool removed;
};
struct k90_drvdata {
struct k90_led record_led;
};
struct corsair_drvdata {
unsigned long quirks;
struct k90_drvdata *k90;
struct k90_led *backlight;
};
#define K90_GKEY_COUNT 18
static int corsair_usage_to_gkey(unsigned int usage)
{
/* G1 (0xd0) to G16 (0xdf) */
if (usage >= 0xd0 && usage <= 0xdf)
return usage - 0xd0 + 1;
/* G17 (0xe8) to G18 (0xe9) */
if (usage >= 0xe8 && usage <= 0xe9)
return usage - 0xe8 + 17;
return 0;
}
static unsigned short corsair_gkey_map[K90_GKEY_COUNT] = {
BTN_TRIGGER_HAPPY1,
BTN_TRIGGER_HAPPY2,
BTN_TRIGGER_HAPPY3,
BTN_TRIGGER_HAPPY4,
BTN_TRIGGER_HAPPY5,
BTN_TRIGGER_HAPPY6,
BTN_TRIGGER_HAPPY7,
BTN_TRIGGER_HAPPY8,
BTN_TRIGGER_HAPPY9,
BTN_TRIGGER_HAPPY10,
BTN_TRIGGER_HAPPY11,
BTN_TRIGGER_HAPPY12,
BTN_TRIGGER_HAPPY13,
BTN_TRIGGER_HAPPY14,
BTN_TRIGGER_HAPPY15,
BTN_TRIGGER_HAPPY16,
BTN_TRIGGER_HAPPY17,
BTN_TRIGGER_HAPPY18,
};
module_param_array_named(gkey_codes, corsair_gkey_map, ushort, NULL, S_IRUGO);
MODULE_PARM_DESC(gkey_codes, "Key codes for the G-keys");
static unsigned short corsair_record_keycodes[2] = {
BTN_TRIGGER_HAPPY19,
BTN_TRIGGER_HAPPY20
};
module_param_array_named(recordkey_codes, corsair_record_keycodes, ushort,
NULL, S_IRUGO);
MODULE_PARM_DESC(recordkey_codes, "Key codes for the MR (start and stop record) button");
static unsigned short corsair_profile_keycodes[3] = {
BTN_TRIGGER_HAPPY21,
BTN_TRIGGER_HAPPY22,
BTN_TRIGGER_HAPPY23
};
module_param_array_named(profilekey_codes, corsair_profile_keycodes, ushort,
NULL, S_IRUGO);
MODULE_PARM_DESC(profilekey_codes, "Key codes for the profile buttons");
#define CORSAIR_USAGE_SPECIAL_MIN 0xf0
#define CORSAIR_USAGE_SPECIAL_MAX 0xff
#define CORSAIR_USAGE_MACRO_RECORD_START 0xf6
#define CORSAIR_USAGE_MACRO_RECORD_STOP 0xf7
#define CORSAIR_USAGE_PROFILE 0xf1
#define CORSAIR_USAGE_M1 0xf1
#define CORSAIR_USAGE_M2 0xf2
#define CORSAIR_USAGE_M3 0xf3
#define CORSAIR_USAGE_PROFILE_MAX 0xf3
#define CORSAIR_USAGE_META_OFF 0xf4
#define CORSAIR_USAGE_META_ON 0xf5
#define CORSAIR_USAGE_LIGHT 0xfa
#define CORSAIR_USAGE_LIGHT_OFF 0xfa
#define CORSAIR_USAGE_LIGHT_DIM 0xfb
#define CORSAIR_USAGE_LIGHT_MEDIUM 0xfc
#define CORSAIR_USAGE_LIGHT_BRIGHT 0xfd
#define CORSAIR_USAGE_LIGHT_MAX 0xfd
/* USB control protocol */
#define K90_REQUEST_BRIGHTNESS 49
#define K90_REQUEST_MACRO_MODE 2
#define K90_REQUEST_STATUS 4
#define K90_REQUEST_GET_MODE 5
#define K90_REQUEST_PROFILE 20
#define K90_MACRO_MODE_SW 0x0030
#define K90_MACRO_MODE_HW 0x0001
#define K90_MACRO_LED_ON 0x0020
#define K90_MACRO_LED_OFF 0x0040
/*
* LED class devices
*/
#define K90_BACKLIGHT_LED_SUFFIX "::backlight"
#define K90_RECORD_LED_SUFFIX "::record"
static enum led_brightness k90_backlight_get(struct led_classdev *led_cdev)
{
int ret;
struct k90_led *led = container_of(led_cdev, struct k90_led, cdev);
struct device *dev = led->cdev.dev->parent;
struct usb_interface *usbif = to_usb_interface(dev->parent);
struct usb_device *usbdev = interface_to_usbdev(usbif);
int brightness;
char *data;
data = kmalloc(8, GFP_KERNEL);
if (!data)
return -ENOMEM;
ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0),
K90_REQUEST_STATUS,
USB_DIR_IN | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, 0, 0, data, 8,
USB_CTRL_SET_TIMEOUT);
if (ret < 0) {
dev_warn(dev, "Failed to get K90 initial state (error %d).\n",
ret);
ret = -EIO;
goto out;
}
brightness = data[4];
if (brightness < 0 || brightness > 3) {
dev_warn(dev,
"Read invalid backlight brightness: %02hhx.\n",
data[4]);
ret = -EIO;
goto out;
}
ret = brightness;
out:
kfree(data);
return ret;
}
static enum led_brightness k90_record_led_get(struct led_classdev *led_cdev)
{
struct k90_led *led = container_of(led_cdev, struct k90_led, cdev);
return led->brightness;
}
static void k90_brightness_set(struct led_classdev *led_cdev,
enum led_brightness brightness)
{
struct k90_led *led = container_of(led_cdev, struct k90_led, cdev);
led->brightness = brightness;
schedule_work(&led->work);
}
static void k90_backlight_work(struct work_struct *work)
{
int ret;
struct k90_led *led = container_of(work, struct k90_led, work);
struct device *dev;
struct usb_interface *usbif;
struct usb_device *usbdev;
if (led->removed)
return;
dev = led->cdev.dev->parent;
usbif = to_usb_interface(dev->parent);
usbdev = interface_to_usbdev(usbif);
ret = usb_control_msg(usbdev, usb_sndctrlpipe(usbdev, 0),
K90_REQUEST_BRIGHTNESS,
USB_DIR_OUT | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, led->brightness, 0,
NULL, 0, USB_CTRL_SET_TIMEOUT);
if (ret != 0)
dev_warn(dev, "Failed to set backlight brightness (error: %d).\n",
ret);
}
static void k90_record_led_work(struct work_struct *work)
{
int ret;
struct k90_led *led = container_of(work, struct k90_led, work);
struct device *dev;
struct usb_interface *usbif;
struct usb_device *usbdev;
int value;
if (led->removed)
return;
dev = led->cdev.dev->parent;
usbif = to_usb_interface(dev->parent);
usbdev = interface_to_usbdev(usbif);
if (led->brightness > 0)
value = K90_MACRO_LED_ON;
else
value = K90_MACRO_LED_OFF;
ret = usb_control_msg(usbdev, usb_sndctrlpipe(usbdev, 0),
K90_REQUEST_MACRO_MODE,
USB_DIR_OUT | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, value, 0, NULL, 0,
USB_CTRL_SET_TIMEOUT);
if (ret != 0)
dev_warn(dev, "Failed to set record LED state (error: %d).\n",
ret);
}
/*
* Keyboard attributes
*/
static ssize_t k90_show_macro_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
struct usb_interface *usbif = to_usb_interface(dev->parent);
struct usb_device *usbdev = interface_to_usbdev(usbif);
const char *macro_mode;
char *data;
data = kmalloc(2, GFP_KERNEL);
if (!data)
return -ENOMEM;
ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0),
K90_REQUEST_GET_MODE,
USB_DIR_IN | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, 0, 0, data, 2,
USB_CTRL_SET_TIMEOUT);
if (ret < 0) {
dev_warn(dev, "Failed to get K90 initial mode (error %d).\n",
ret);
ret = -EIO;
goto out;
}
switch (data[0]) {
case K90_MACRO_MODE_HW:
macro_mode = "HW";
break;
case K90_MACRO_MODE_SW:
macro_mode = "SW";
break;
default:
dev_warn(dev, "K90 in unknown mode: %02hhx.\n",
data[0]);
ret = -EIO;
goto out;
}
ret = snprintf(buf, PAGE_SIZE, "%s\n", macro_mode);
out:
kfree(data);
return ret;
}
static ssize_t k90_store_macro_mode(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int ret;
struct usb_interface *usbif = to_usb_interface(dev->parent);
struct usb_device *usbdev = interface_to_usbdev(usbif);
__u16 value;
if (strncmp(buf, "SW", 2) == 0)
value = K90_MACRO_MODE_SW;
else if (strncmp(buf, "HW", 2) == 0)
value = K90_MACRO_MODE_HW;
else
return -EINVAL;
ret = usb_control_msg(usbdev, usb_sndctrlpipe(usbdev, 0),
K90_REQUEST_MACRO_MODE,
USB_DIR_OUT | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, value, 0, NULL, 0,
USB_CTRL_SET_TIMEOUT);
if (ret != 0) {
dev_warn(dev, "Failed to set macro mode.\n");
return ret;
}
return count;
}
static ssize_t k90_show_current_profile(struct device *dev,
struct device_attribute *attr,
char *buf)
{
int ret;
struct usb_interface *usbif = to_usb_interface(dev->parent);
struct usb_device *usbdev = interface_to_usbdev(usbif);
int current_profile;
char *data;
data = kmalloc(8, GFP_KERNEL);
if (!data)
return -ENOMEM;
ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0),
K90_REQUEST_STATUS,
USB_DIR_IN | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, 0, 0, data, 8,
USB_CTRL_SET_TIMEOUT);
if (ret < 0) {
dev_warn(dev, "Failed to get K90 initial state (error %d).\n",
ret);
ret = -EIO;
goto out;
}
current_profile = data[7];
if (current_profile < 1 || current_profile > 3) {
dev_warn(dev, "Read invalid current profile: %02hhx.\n",
data[7]);
ret = -EIO;
goto out;
}
ret = snprintf(buf, PAGE_SIZE, "%d\n", current_profile);
out:
kfree(data);
return ret;
}
static ssize_t k90_store_current_profile(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int ret;
struct usb_interface *usbif = to_usb_interface(dev->parent);
struct usb_device *usbdev = interface_to_usbdev(usbif);
int profile;
if (kstrtoint(buf, 10, &profile))
return -EINVAL;
if (profile < 1 || profile > 3)
return -EINVAL;
ret = usb_control_msg(usbdev, usb_sndctrlpipe(usbdev, 0),
K90_REQUEST_PROFILE,
USB_DIR_OUT | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, profile, 0, NULL, 0,
USB_CTRL_SET_TIMEOUT);
if (ret != 0) {
dev_warn(dev, "Failed to change current profile (error %d).\n",
ret);
return ret;
}
return count;
}
static DEVICE_ATTR(macro_mode, 0644, k90_show_macro_mode, k90_store_macro_mode);
static DEVICE_ATTR(current_profile, 0644, k90_show_current_profile,
k90_store_current_profile);
static struct attribute *k90_attrs[] = {
&dev_attr_macro_mode.attr,
&dev_attr_current_profile.attr,
NULL
};
static const struct attribute_group k90_attr_group = {
.attrs = k90_attrs,
};
/*
* Driver functions
*/
static int k90_init_backlight(struct hid_device *dev)
{
int ret;
struct corsair_drvdata *drvdata = hid_get_drvdata(dev);
size_t name_sz;
char *name;
drvdata->backlight = kzalloc(sizeof(struct k90_led), GFP_KERNEL);
if (!drvdata->backlight) {
ret = -ENOMEM;
goto fail_backlight_alloc;
}
name_sz =
strlen(dev_name(&dev->dev)) + sizeof(K90_BACKLIGHT_LED_SUFFIX);
name = kzalloc(name_sz, GFP_KERNEL);
if (!name) {
ret = -ENOMEM;
goto fail_name_alloc;
}
snprintf(name, name_sz, "%s" K90_BACKLIGHT_LED_SUFFIX,
dev_name(&dev->dev));
drvdata->backlight->removed = false;
drvdata->backlight->cdev.name = name;
drvdata->backlight->cdev.max_brightness = 3;
drvdata->backlight->cdev.brightness_set = k90_brightness_set;
drvdata->backlight->cdev.brightness_get = k90_backlight_get;
INIT_WORK(&drvdata->backlight->work, k90_backlight_work);
ret = led_classdev_register(&dev->dev, &drvdata->backlight->cdev);
if (ret != 0)
goto fail_register_cdev;
return 0;
fail_register_cdev:
kfree(drvdata->backlight->cdev.name);
fail_name_alloc:
kfree(drvdata->backlight);
drvdata->backlight = NULL;
fail_backlight_alloc:
return ret;
}
static int k90_init_macro_functions(struct hid_device *dev)
{
int ret;
struct corsair_drvdata *drvdata = hid_get_drvdata(dev);
struct k90_drvdata *k90;
size_t name_sz;
char *name;
k90 = kzalloc(sizeof(struct k90_drvdata), GFP_KERNEL);
if (!k90) {
ret = -ENOMEM;
goto fail_drvdata;
}
drvdata->k90 = k90;
/* Init LED device for record LED */
name_sz = strlen(dev_name(&dev->dev)) + sizeof(K90_RECORD_LED_SUFFIX);
name = kzalloc(name_sz, GFP_KERNEL);
if (!name) {
ret = -ENOMEM;
goto fail_record_led_alloc;
}
snprintf(name, name_sz, "%s" K90_RECORD_LED_SUFFIX,
dev_name(&dev->dev));
k90->record_led.removed = false;
k90->record_led.cdev.name = name;
k90->record_led.cdev.max_brightness = 1;
k90->record_led.cdev.brightness_set = k90_brightness_set;
k90->record_led.cdev.brightness_get = k90_record_led_get;
INIT_WORK(&k90->record_led.work, k90_record_led_work);
k90->record_led.brightness = 0;
ret = led_classdev_register(&dev->dev, &k90->record_led.cdev);
if (ret != 0)
goto fail_record_led;
/* Init attributes */
ret = sysfs_create_group(&dev->dev.kobj, &k90_attr_group);
if (ret != 0)
goto fail_sysfs;
return 0;
fail_sysfs:
k90->record_led.removed = true;
led_classdev_unregister(&k90->record_led.cdev);
cancel_work_sync(&k90->record_led.work);
fail_record_led:
kfree(k90->record_led.cdev.name);
fail_record_led_alloc:
kfree(k90);
fail_drvdata:
drvdata->k90 = NULL;
return ret;
}
static void k90_cleanup_backlight(struct hid_device *dev)
{
struct corsair_drvdata *drvdata = hid_get_drvdata(dev);
if (drvdata->backlight) {
drvdata->backlight->removed = true;
led_classdev_unregister(&drvdata->backlight->cdev);
cancel_work_sync(&drvdata->backlight->work);
kfree(drvdata->backlight->cdev.name);
kfree(drvdata->backlight);
}
}
static void k90_cleanup_macro_functions(struct hid_device *dev)
{
struct corsair_drvdata *drvdata = hid_get_drvdata(dev);
struct k90_drvdata *k90 = drvdata->k90;
if (k90) {
sysfs_remove_group(&dev->dev.kobj, &k90_attr_group);
k90->record_led.removed = true;
led_classdev_unregister(&k90->record_led.cdev);
cancel_work_sync(&k90->record_led.work);
kfree(k90->record_led.cdev.name);
kfree(k90);
}
}
static int corsair_probe(struct hid_device *dev, const struct hid_device_id *id)
{
int ret;
unsigned long quirks = id->driver_data;
struct corsair_drvdata *drvdata;
struct usb_interface *usbif = to_usb_interface(dev->dev.parent);
drvdata = devm_kzalloc(&dev->dev, sizeof(struct corsair_drvdata),
GFP_KERNEL);
if (drvdata == NULL)
return -ENOMEM;
drvdata->quirks = quirks;
hid_set_drvdata(dev, drvdata);
ret = hid_parse(dev);
if (ret != 0) {
hid_err(dev, "parse failed\n");
return ret;
}
ret = hid_hw_start(dev, HID_CONNECT_DEFAULT);
if (ret != 0) {
hid_err(dev, "hw start failed\n");
return ret;
}
if (usbif->cur_altsetting->desc.bInterfaceNumber == 0) {
if (quirks & CORSAIR_USE_K90_MACRO) {
ret = k90_init_macro_functions(dev);
if (ret != 0)
hid_warn(dev, "Failed to initialize K90 macro functions.\n");
}
if (quirks & CORSAIR_USE_K90_BACKLIGHT) {
ret = k90_init_backlight(dev);
if (ret != 0)
hid_warn(dev, "Failed to initialize K90 backlight.\n");
}
}
return 0;
}
static void corsair_remove(struct hid_device *dev)
{
k90_cleanup_macro_functions(dev);
k90_cleanup_backlight(dev);
hid_hw_stop(dev);
}
static int corsair_event(struct hid_device *dev, struct hid_field *field,
struct hid_usage *usage, __s32 value)
{
struct corsair_drvdata *drvdata = hid_get_drvdata(dev);
if (!drvdata->k90)
return 0;
switch (usage->hid & HID_USAGE) {
case CORSAIR_USAGE_MACRO_RECORD_START:
drvdata->k90->record_led.brightness = 1;
break;
case CORSAIR_USAGE_MACRO_RECORD_STOP:
drvdata->k90->record_led.brightness = 0;
break;
default:
break;
}
return 0;
}
static int corsair_input_mapping(struct hid_device *dev,
struct hid_input *input,
struct hid_field *field,
struct hid_usage *usage, unsigned long **bit,
int *max)
{
int gkey;
if ((usage->hid & HID_USAGE_PAGE) != HID_UP_KEYBOARD)
return 0;
gkey = corsair_usage_to_gkey(usage->hid & HID_USAGE);
if (gkey != 0) {
hid_map_usage_clear(input, usage, bit, max, EV_KEY,
corsair_gkey_map[gkey - 1]);
return 1;
}
if ((usage->hid & HID_USAGE) >= CORSAIR_USAGE_SPECIAL_MIN &&
(usage->hid & HID_USAGE) <= CORSAIR_USAGE_SPECIAL_MAX) {
switch (usage->hid & HID_USAGE) {
case CORSAIR_USAGE_MACRO_RECORD_START:
hid_map_usage_clear(input, usage, bit, max, EV_KEY,
corsair_record_keycodes[0]);
return 1;
case CORSAIR_USAGE_MACRO_RECORD_STOP:
hid_map_usage_clear(input, usage, bit, max, EV_KEY,
corsair_record_keycodes[1]);
return 1;
case CORSAIR_USAGE_M1:
hid_map_usage_clear(input, usage, bit, max, EV_KEY,
corsair_profile_keycodes[0]);
return 1;
case CORSAIR_USAGE_M2:
hid_map_usage_clear(input, usage, bit, max, EV_KEY,
corsair_profile_keycodes[1]);
return 1;
case CORSAIR_USAGE_M3:
hid_map_usage_clear(input, usage, bit, max, EV_KEY,
corsair_profile_keycodes[2]);
return 1;
default:
return -1;
}
}
return 0;
}
static const struct hid_device_id corsair_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_CORSAIR, USB_DEVICE_ID_CORSAIR_K90),
.driver_data = CORSAIR_USE_K90_MACRO |
CORSAIR_USE_K90_BACKLIGHT },
{}
};
MODULE_DEVICE_TABLE(hid, corsair_devices);
static struct hid_driver corsair_driver = {
.name = "corsair",
.id_table = corsair_devices,
.probe = corsair_probe,
.event = corsair_event,
.remove = corsair_remove,
.input_mapping = corsair_input_mapping,
};
module_hid_driver(corsair_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Clement Vuchener");
MODULE_DESCRIPTION("HID driver for Corsair devices");
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3115_0 |
crossvul-cpp_data_bad_4946_1 | #include "cache.h"
#include "commit.h"
#include "diff.h"
#include "revision.h"
#include "list-objects.h"
#include "pack.h"
#include "pack-bitmap.h"
#include "builtin.h"
#include "log-tree.h"
#include "graph.h"
#include "bisect.h"
static const char rev_list_usage[] =
"git rev-list [OPTION] <commit-id>... [ -- paths... ]\n"
" limiting output:\n"
" --max-count=<n>\n"
" --max-age=<epoch>\n"
" --min-age=<epoch>\n"
" --sparse\n"
" --no-merges\n"
" --min-parents=<n>\n"
" --no-min-parents\n"
" --max-parents=<n>\n"
" --no-max-parents\n"
" --remove-empty\n"
" --all\n"
" --branches\n"
" --tags\n"
" --remotes\n"
" --stdin\n"
" --quiet\n"
" ordering output:\n"
" --topo-order\n"
" --date-order\n"
" --reverse\n"
" formatting output:\n"
" --parents\n"
" --children\n"
" --objects | --objects-edge\n"
" --unpacked\n"
" --header | --pretty\n"
" --abbrev=<n> | --no-abbrev\n"
" --abbrev-commit\n"
" --left-right\n"
" --count\n"
" special purpose:\n"
" --bisect\n"
" --bisect-vars\n"
" --bisect-all"
;
static void finish_commit(struct commit *commit, void *data);
static void show_commit(struct commit *commit, void *data)
{
struct rev_list_info *info = data;
struct rev_info *revs = info->revs;
if (info->flags & REV_LIST_QUIET) {
finish_commit(commit, data);
return;
}
graph_show_commit(revs->graph);
if (revs->count) {
if (commit->object.flags & PATCHSAME)
revs->count_same++;
else if (commit->object.flags & SYMMETRIC_LEFT)
revs->count_left++;
else
revs->count_right++;
finish_commit(commit, data);
return;
}
if (info->show_timestamp)
printf("%lu ", commit->date);
if (info->header_prefix)
fputs(info->header_prefix, stdout);
if (!revs->graph)
fputs(get_revision_mark(revs, commit), stdout);
if (revs->abbrev_commit && revs->abbrev)
fputs(find_unique_abbrev(commit->object.oid.hash, revs->abbrev),
stdout);
else
fputs(oid_to_hex(&commit->object.oid), stdout);
if (revs->print_parents) {
struct commit_list *parents = commit->parents;
while (parents) {
printf(" %s", oid_to_hex(&parents->item->object.oid));
parents = parents->next;
}
}
if (revs->children.name) {
struct commit_list *children;
children = lookup_decoration(&revs->children, &commit->object);
while (children) {
printf(" %s", oid_to_hex(&children->item->object.oid));
children = children->next;
}
}
show_decorations(revs, commit);
if (revs->commit_format == CMIT_FMT_ONELINE)
putchar(' ');
else
putchar('\n');
if (revs->verbose_header && get_cached_commit_buffer(commit, NULL)) {
struct strbuf buf = STRBUF_INIT;
struct pretty_print_context ctx = {0};
ctx.abbrev = revs->abbrev;
ctx.date_mode = revs->date_mode;
ctx.date_mode_explicit = revs->date_mode_explicit;
ctx.fmt = revs->commit_format;
ctx.output_encoding = get_log_output_encoding();
pretty_print_commit(&ctx, commit, &buf);
if (revs->graph) {
if (buf.len) {
if (revs->commit_format != CMIT_FMT_ONELINE)
graph_show_oneline(revs->graph);
graph_show_commit_msg(revs->graph, &buf);
/*
* Add a newline after the commit message.
*
* Usually, this newline produces a blank
* padding line between entries, in which case
* we need to add graph padding on this line.
*
* However, the commit message may not end in a
* newline. In this case the newline simply
* ends the last line of the commit message,
* and we don't need any graph output. (This
* always happens with CMIT_FMT_ONELINE, and it
* happens with CMIT_FMT_USERFORMAT when the
* format doesn't explicitly end in a newline.)
*/
if (buf.len && buf.buf[buf.len - 1] == '\n')
graph_show_padding(revs->graph);
putchar('\n');
} else {
/*
* If the message buffer is empty, just show
* the rest of the graph output for this
* commit.
*/
if (graph_show_remainder(revs->graph))
putchar('\n');
if (revs->commit_format == CMIT_FMT_ONELINE)
putchar('\n');
}
} else {
if (revs->commit_format != CMIT_FMT_USERFORMAT ||
buf.len) {
fwrite(buf.buf, 1, buf.len, stdout);
putchar(info->hdr_termination);
}
}
strbuf_release(&buf);
} else {
if (graph_show_remainder(revs->graph))
putchar('\n');
}
maybe_flush_or_die(stdout, "stdout");
finish_commit(commit, data);
}
static void finish_commit(struct commit *commit, void *data)
{
if (commit->parents) {
free_commit_list(commit->parents);
commit->parents = NULL;
}
free_commit_buffer(commit);
}
static void finish_object(struct object *obj,
struct strbuf *path, const char *name,
void *cb_data)
{
struct rev_list_info *info = cb_data;
if (obj->type == OBJ_BLOB && !has_object_file(&obj->oid))
die("missing blob object '%s'", oid_to_hex(&obj->oid));
if (info->revs->verify_objects && !obj->parsed && obj->type != OBJ_COMMIT)
parse_object(obj->oid.hash);
}
static void show_object(struct object *obj,
struct strbuf *path, const char *component,
void *cb_data)
{
struct rev_list_info *info = cb_data;
finish_object(obj, path, component, cb_data);
if (info->flags & REV_LIST_QUIET)
return;
show_object_with_name(stdout, obj, path, component);
}
static void show_edge(struct commit *commit)
{
printf("-%s\n", oid_to_hex(&commit->object.oid));
}
static void print_var_str(const char *var, const char *val)
{
printf("%s='%s'\n", var, val);
}
static void print_var_int(const char *var, int val)
{
printf("%s=%d\n", var, val);
}
static int show_bisect_vars(struct rev_list_info *info, int reaches, int all)
{
int cnt, flags = info->flags;
char hex[GIT_SHA1_HEXSZ + 1] = "";
struct commit_list *tried;
struct rev_info *revs = info->revs;
if (!revs->commits)
return 1;
revs->commits = filter_skipped(revs->commits, &tried,
flags & BISECT_SHOW_ALL,
NULL, NULL);
/*
* revs->commits can reach "reaches" commits among
* "all" commits. If it is good, then there are
* (all-reaches) commits left to be bisected.
* On the other hand, if it is bad, then the set
* to bisect is "reaches".
* A bisect set of size N has (N-1) commits further
* to test, as we already know one bad one.
*/
cnt = all - reaches;
if (cnt < reaches)
cnt = reaches;
if (revs->commits)
sha1_to_hex_r(hex, revs->commits->item->object.oid.hash);
if (flags & BISECT_SHOW_ALL) {
traverse_commit_list(revs, show_commit, show_object, info);
printf("------\n");
}
print_var_str("bisect_rev", hex);
print_var_int("bisect_nr", cnt - 1);
print_var_int("bisect_good", all - reaches - 1);
print_var_int("bisect_bad", reaches - 1);
print_var_int("bisect_all", all);
print_var_int("bisect_steps", estimate_bisect_steps(all));
return 0;
}
static int show_object_fast(
const unsigned char *sha1,
enum object_type type,
int exclude,
uint32_t name_hash,
struct packed_git *found_pack,
off_t found_offset)
{
fprintf(stdout, "%s\n", sha1_to_hex(sha1));
return 1;
}
int cmd_rev_list(int argc, const char **argv, const char *prefix)
{
struct rev_info revs;
struct rev_list_info info;
int i;
int bisect_list = 0;
int bisect_show_vars = 0;
int bisect_find_all = 0;
int use_bitmap_index = 0;
git_config(git_default_config, NULL);
init_revisions(&revs, prefix);
revs.abbrev = DEFAULT_ABBREV;
revs.commit_format = CMIT_FMT_UNSPECIFIED;
argc = setup_revisions(argc, argv, &revs, NULL);
memset(&info, 0, sizeof(info));
info.revs = &revs;
if (revs.bisect)
bisect_list = 1;
if (DIFF_OPT_TST(&revs.diffopt, QUICK))
info.flags |= REV_LIST_QUIET;
for (i = 1 ; i < argc; i++) {
const char *arg = argv[i];
if (!strcmp(arg, "--header")) {
revs.verbose_header = 1;
continue;
}
if (!strcmp(arg, "--timestamp")) {
info.show_timestamp = 1;
continue;
}
if (!strcmp(arg, "--bisect")) {
bisect_list = 1;
continue;
}
if (!strcmp(arg, "--bisect-all")) {
bisect_list = 1;
bisect_find_all = 1;
info.flags |= BISECT_SHOW_ALL;
revs.show_decorations = 1;
continue;
}
if (!strcmp(arg, "--bisect-vars")) {
bisect_list = 1;
bisect_show_vars = 1;
continue;
}
if (!strcmp(arg, "--use-bitmap-index")) {
use_bitmap_index = 1;
continue;
}
if (!strcmp(arg, "--test-bitmap")) {
test_bitmap_walk(&revs);
return 0;
}
usage(rev_list_usage);
}
if (revs.commit_format != CMIT_FMT_UNSPECIFIED) {
/* The command line has a --pretty */
info.hdr_termination = '\n';
if (revs.commit_format == CMIT_FMT_ONELINE)
info.header_prefix = "";
else
info.header_prefix = "commit ";
}
else if (revs.verbose_header)
/* Only --header was specified */
revs.commit_format = CMIT_FMT_RAW;
if ((!revs.commits &&
(!(revs.tag_objects || revs.tree_objects || revs.blob_objects) &&
!revs.pending.nr)) ||
revs.diff)
usage(rev_list_usage);
if (revs.show_notes)
die(_("rev-list does not support display of notes"));
save_commit_buffer = (revs.verbose_header ||
revs.grep_filter.pattern_list ||
revs.grep_filter.header_list);
if (bisect_list)
revs.limited = 1;
if (use_bitmap_index && !revs.prune) {
if (revs.count && !revs.left_right && !revs.cherry_mark) {
uint32_t commit_count;
if (!prepare_bitmap_walk(&revs)) {
count_bitmap_commit_list(&commit_count, NULL, NULL, NULL);
printf("%d\n", commit_count);
return 0;
}
} else if (revs.tag_objects && revs.tree_objects && revs.blob_objects) {
if (!prepare_bitmap_walk(&revs)) {
traverse_bitmap_commit_list(&show_object_fast);
return 0;
}
}
}
if (prepare_revision_walk(&revs))
die("revision walk setup failed");
if (revs.tree_objects)
mark_edges_uninteresting(&revs, show_edge);
if (bisect_list) {
int reaches = reaches, all = all;
revs.commits = find_bisection(revs.commits, &reaches, &all,
bisect_find_all);
if (bisect_show_vars)
return show_bisect_vars(&info, reaches, all);
}
traverse_commit_list(&revs, show_commit, show_object, &info);
if (revs.count) {
if (revs.left_right && revs.cherry_mark)
printf("%d\t%d\t%d\n", revs.count_left, revs.count_right, revs.count_same);
else if (revs.left_right)
printf("%d\t%d\n", revs.count_left, revs.count_right);
else if (revs.cherry_mark)
printf("%d\t%d\n", revs.count_left + revs.count_right, revs.count_same);
else
printf("%d\n", revs.count_left + revs.count_right);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4946_1 |
crossvul-cpp_data_good_525_2 | /*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre
* Copyright (c) Telecom ParisTech 2000-2012
* All rights reserved
*
* This file is part of GPAC / FFMPEG module
*
* GPAC 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, or (at your option)
* any later version.
*
* GPAC 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; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include "ffmpeg_in.h"
#ifndef DISABLE_FFMPEG_DEMUX
/*default buffer is 200 ms per channel*/
#define FFD_DATA_BUFFER 800
//#define FFMPEG_DEMUX_ENABLE_MPEG2TS
//#if defined(__DARWIN__) || defined(__APPLE__)
#if !defined(WIN32) && !defined(_WIN32_WCE) && !defined(__SYMBIAN32__)
#include <errno.h>
#endif
/**
* New versions of ffmpeg do not declare AVERROR_NOMEM, AVERROR_IO, AVERROR_NOFMT
*/
#ifndef AVERROR_NOMEM
#define AVERROR_NOMEM AVERROR(ENOMEM)
#endif /* AVERROR_NOMEM */
#ifndef AVERROR_IO
#define AVERROR_IO AVERROR(EIO)
#endif /* AVERROR_IO */
#ifndef AVERROR_NOFMT
#define AVERROR_NOFMT AVERROR(EINVAL)
#endif /* AVERROR_NOFMT */
#if ((LIBAVFORMAT_VERSION_MAJOR == 54) && (LIBAVFORMAT_VERSION_MINOR >= 20)) || (LIBAVFORMAT_VERSION_MAJOR > 54)
#define av_find_stream_info(__c) avformat_find_stream_info(__c, NULL)
#define USE_AVFORMAT_OPEN_INPUT 1
#endif
#if defined(GPAC_ANDROID) && (LIBAVFORMAT_VERSION_MAJOR <= 52)
#ifndef FF_API_CLOSE_INPUT_FILE
#define FF_API_CLOSE_INPUT_FILE 1
#endif
#endif
static u32 FFDemux_Run(void *par)
{
AVPacket pkt;
s64 seek_to;
GF_NetworkCommand com;
GF_NetworkCommand map;
GF_SLHeader slh;
FFDemux *ffd = (FFDemux *) par;
memset(&map, 0, sizeof(GF_NetworkCommand));
map.command_type = GF_NET_CHAN_MAP_TIME;
memset(&com, 0, sizeof(GF_NetworkCommand));
com.command_type = GF_NET_BUFFER_QUERY;
memset(&slh, 0, sizeof(GF_SLHeader));
slh.compositionTimeStampFlag = slh.decodingTimeStampFlag = 1;
while (ffd->is_running) {
//nothing connected, wait
if (!ffd->video_ch && !ffd->audio_ch) {
gf_sleep(100);
continue;
}
if ((ffd->seek_time>=0) && ffd->seekable) {
seek_to = (s64) (AV_TIME_BASE*ffd->seek_time);
av_seek_frame(ffd->ctx, -1, seek_to, AVSEEK_FLAG_BACKWARD);
ffd->seek_time = -1;
}
pkt.stream_index = -1;
/*EOF*/
if (av_read_frame(ffd->ctx, &pkt) <0) break;
if (pkt.pts == AV_NOPTS_VALUE) pkt.pts = pkt.dts;
if (!pkt.dts) pkt.dts = pkt.pts;
slh.compositionTimeStamp = pkt.pts;
slh.decodingTimeStamp = pkt.dts;
gf_mx_p(ffd->mx);
/*blindly send audio as soon as video is init*/
if (ffd->audio_ch && (pkt.stream_index == ffd->audio_st) ) {
slh.compositionTimeStamp *= ffd->audio_tscale.num;
slh.decodingTimeStamp *= ffd->audio_tscale.num;
gf_service_send_packet(ffd->service, ffd->audio_ch, (char *) pkt.data, pkt.size, &slh, GF_OK);
}
else if (ffd->video_ch && (pkt.stream_index == ffd->video_st)) {
slh.compositionTimeStamp *= ffd->video_tscale.num;
slh.decodingTimeStamp *= ffd->video_tscale.num;
slh.randomAccessPointFlag = pkt.flags&AV_PKT_FLAG_KEY ? 1 : 0;
gf_service_send_packet(ffd->service, ffd->video_ch, (char *) pkt.data, pkt.size, &slh, GF_OK);
}
gf_mx_v(ffd->mx);
av_free_packet(&pkt);
/*sleep untill the buffer occupancy is too low - note that this work because all streams in this
demuxer are synchronized*/
while (ffd->audio_run || ffd->video_run) {
gf_service_command(ffd->service, &com, GF_OK);
if (com.buffer.occupancy < com.buffer.max)
break;
gf_sleep(1);
}
if (!ffd->audio_run && !ffd->video_run) break;
}
/*signal EOS*/
if (ffd->audio_ch) gf_service_send_packet(ffd->service, ffd->audio_ch, NULL, 0, NULL, GF_EOS);
if (ffd->video_ch) gf_service_send_packet(ffd->service, ffd->video_ch, NULL, 0, NULL, GF_EOS);
ffd->is_running = 2;
return 0;
}
static const char * FFD_MIME_TYPES[] = {
"video/x-mpeg", "mpg mpeg mp2 mpa mpe mpv2", "MPEG 1/2 Movies",
"video/x-mpeg-systems", "mpg mpeg mp2 mpa mpe mpv2", "MPEG 1/2 Movies",
"audio/basic", "snd au", "Basic Audio",
"audio/x-wav", "wav", "WAV Audio",
"audio/vnd.wave", "wav", "WAV Audio",
"video/x-ms-asf", "asf wma wmv asx asr", "WindowsMedia Movies",
"video/x-ms-wmv", "asf wma wmv asx asr", "WindowsMedia Movies",
"video/x-msvideo", "avi", "AVI Movies",
"video/x-ms-video", "avi", "AVI Movies",
"video/avi", "avi", "AVI Movies",
"video/vnd.avi", "avi", "AVI Movies",
"video/H263", "h263 263", "H263 Video",
"video/H264", "h264 264", "H264 Video",
"video/MPEG4", "cmp", "MPEG-4 Video",
/* We let ffmpeg handle mov because some QT files with uncompressed or adpcm audio use 1 audio sample
per MP4 sample which is a killer for our MP4 lib, whereas ffmpeg handles these as complete audio chunks
moreover ffmpeg handles cmov, we don't */
"video/quicktime", "mov qt", "QuickTime Movies",
/* Supported by latest versions of FFMPEG */
"video/webm", "webm", "Google WebM Movies",
"audio/webm", "webm", "Google WebM Music",
#ifdef FFMPEG_DEMUX_ENABLE_MPEG2TS
"video/mp2t", "ts", "MPEG 2 TS",
#endif
NULL
};
static u32 FFD_RegisterMimeTypes(const GF_InputService *plug) {
u32 i;
for (i = 0 ; FFD_MIME_TYPES[i]; i+=3)
gf_service_register_mime(plug, FFD_MIME_TYPES[i], FFD_MIME_TYPES[i+1], FFD_MIME_TYPES[i+2]);
return i/3;
}
static int open_file(AVFormatContext ** ic_ptr, const char * filename, AVInputFormat * fmt, void *ops) {
#ifdef USE_PRE_0_7
return av_open_input_file(ic_ptr, filename, fmt, 0, NULL);
#else
return avformat_open_input(ic_ptr, filename, fmt, (AVDictionary**)ops);
#endif
}
void ffd_parse_options(FFDemux *ffd, const char *url)
{
#ifdef USE_AVFORMAT_OPEN_INPUT
int res;
char *frag = (char*) strchr(url, '#');
if (frag) frag = frag+1;
if (ffd->options) return;
while (frag) {
char *mid, *sep = strchr(frag, ':');
if (sep) sep[0] = 0;
mid = strchr(frag, '=');
if (mid) {
mid[0] = 0;
res = av_dict_set(&ffd->options, frag, mid+1, 0);
if (res<0) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[FFMPEG Demuxer] Failed to set option %s:%s\n", frag, mid+1) );
}
mid[0] = '=';
}
if (!sep) break;
sep[0] = ':';
frag = sep+1;
}
#endif
}
static Bool FFD_CanHandleURL(GF_InputService *plug, const char *url)
{
Bool has_audio, has_video;
s32 i;
AVFormatContext *ctx;
AVOutputFormat *fmt_out;
Bool ret = GF_FALSE;
char *ext, szName[1024], szExt[20];
const char *szExtList;
FFDemux *ffd;
if (!plug || !url)
return GF_FALSE;
/*disable RTP/RTSP from ffmpeg*/
if (!strnicmp(url, "rtsp://", 7)) return GF_FALSE;
if (!strnicmp(url, "rtspu://", 8)) return GF_FALSE;
if (!strnicmp(url, "rtp://", 6)) return GF_FALSE;
if (!strnicmp(url, "plato://", 8)) return GF_FALSE;
if (!strnicmp(url, "udp://", 6)) return GF_FALSE;
if (!strnicmp(url, "tcp://", 6)) return GF_FALSE;
if (!strnicmp(url, "data:", 5)) return GF_FALSE;
ffd = (FFDemux*)plug->priv;
if (strlen(url) >= sizeof(szName))
return GF_FALSE;
strcpy(szName, url);
ext = strrchr(szName, '#');
if (ext) ext[0] = 0;
ext = strrchr(szName, '?');
if (ext) ext[0] = 0;
ext = strrchr(szName, '.');
if (ext && strlen(ext) > 19) ext = NULL;
if (ext && strlen(ext) > 1 && strlen(ext) <= sizeof(szExt)) {
strcpy(szExt, &ext[1]);
strlwr(szExt);
#ifndef FFMPEG_DEMUX_ENABLE_MPEG2TS
if (strstr("ts m2t mts dmb trp", szExt) ) return GF_FALSE;
#endif
/*note we forbid ffmpeg to handle files we support*/
if (!strcmp(szExt, "mp4") || !strcmp(szExt, "mpg4") || !strcmp(szExt, "m4a") || !strcmp(szExt, "m21")
|| !strcmp(szExt, "m4v") || !strcmp(szExt, "m4a")
|| !strcmp(szExt, "m4s") || !strcmp(szExt, "3gs")
|| !strcmp(szExt, "3gp") || !strcmp(szExt, "3gpp") || !strcmp(szExt, "3gp2") || !strcmp(szExt, "3g2")
|| !strcmp(szExt, "mp3")
|| !strcmp(szExt, "ac3")
|| !strcmp(szExt, "amr")
|| !strcmp(szExt, "bt") || !strcmp(szExt, "wrl") || !strcmp(szExt, "x3dv")
|| !strcmp(szExt, "xmt") || !strcmp(szExt, "xmta") || !strcmp(szExt, "x3d")
|| !strcmp(szExt, "jpg") || !strcmp(szExt, "jpeg") || !strcmp(szExt, "png")
) return GF_FALSE;
/*check any default stuff that should work with ffmpeg*/
{
u32 i;
for (i = 0 ; FFD_MIME_TYPES[i]; i+=3) {
if (gf_service_check_mime_register(plug, FFD_MIME_TYPES[i], FFD_MIME_TYPES[i+1], FFD_MIME_TYPES[i+2], ext))
return GF_TRUE;
}
}
}
ffd_parse_options(ffd, url);
ctx = NULL;
if (open_file(&ctx, szName, NULL, ffd->options ? &ffd->options : NULL)<0) {
AVInputFormat *av_in = NULL;
/*some extensions not supported by ffmpeg*/
if (ext && !strcmp(szExt, "cmp")) av_in = av_find_input_format("m4v");
if (open_file(&ctx, szName, av_in, ffd->options ? &ffd->options : NULL)<0) {
return GF_FALSE;
}
}
if (!ctx) goto exit;
if (av_find_stream_info(ctx) <0) goto exit;
/*figure out if we can use codecs or not*/
has_video = has_audio = GF_FALSE;
for(i = 0; i < (s32)ctx->nb_streams; i++) {
AVCodecContext *enc = ctx->streams[i]->codec;
switch(enc->codec_type) {
case AVMEDIA_TYPE_AUDIO:
if (!has_audio) has_audio = GF_TRUE;
break;
case AVMEDIA_TYPE_VIDEO:
if (!has_video) has_video= GF_TRUE;
break;
default:
break;
}
}
if (!has_audio && !has_video) goto exit;
ret = GF_TRUE;
#if ((LIBAVFORMAT_VERSION_MAJOR == 52) && (LIBAVFORMAT_VERSION_MINOR <= 47)) || (LIBAVFORMAT_VERSION_MAJOR < 52)
fmt_out = guess_stream_format(NULL, url, NULL);
#else
fmt_out = av_guess_format(NULL, url, NULL);
#endif
if (fmt_out) gf_service_register_mime(plug, fmt_out->mime_type, fmt_out->extensions, fmt_out->name);
else {
ext = strrchr(szName, '.');
if (ext) {
strcpy(szExt, &ext[1]);
strlwr(szExt);
szExtList = gf_modules_get_option((GF_BaseInterface *)plug, "MimeTypes", "application/x-ffmpeg");
if (!szExtList) {
gf_service_register_mime(plug, "application/x-ffmpeg", szExt, "Other Movies (FFMPEG)");
} else if (!strstr(szExtList, szExt)) {
u32 len;
char *buf;
len = (u32) (strlen(szExtList) + strlen(szExt) + 10);
buf = (char*)gf_malloc(sizeof(char)*len);
sprintf(buf, "\"%s ", szExt);
strcat(buf, &szExtList[1]);
gf_modules_set_option((GF_BaseInterface *)plug, "MimeTypes", "application/x-ffmpeg", buf);
gf_free(buf);
}
}
}
exit:
#if FF_API_CLOSE_INPUT_FILE
if (ctx) av_close_input_file(ctx);
#else
if (ctx) avformat_close_input(&ctx);
#endif
return ret;
}
static GF_ESD *FFD_GetESDescriptor(FFDemux *ffd, Bool for_audio)
{
GF_BitStream *bs;
Bool dont_use_sl;
GF_ESD *esd = (GF_ESD *) gf_odf_desc_esd_new(0);
esd->ESID = 1 + (for_audio ? ffd->audio_st : ffd->video_st);
esd->decoderConfig->streamType = for_audio ? GF_STREAM_AUDIO : GF_STREAM_VISUAL;
esd->decoderConfig->avgBitrate = esd->decoderConfig->maxBitrate = 0;
/*remap std object types - depending on input formats, FFMPEG may not have separate DSI from initial frame.
In this case we have no choice but using FFMPEG decoders*/
if (for_audio) {
AVCodecContext *dec = ffd->ctx->streams[ffd->audio_st]->codec;
esd->slConfig->timestampResolution = ffd->audio_tscale.den;
switch (dec->codec_id) {
case CODEC_ID_MP2:
esd->decoderConfig->objectTypeIndication = GPAC_OTI_AUDIO_MPEG1;
break;
case CODEC_ID_MP3:
esd->decoderConfig->objectTypeIndication = GPAC_OTI_AUDIO_MPEG2_PART3;
break;
case CODEC_ID_AAC:
if (!dec->extradata_size) goto opaque_audio;
esd->decoderConfig->objectTypeIndication = GPAC_OTI_AUDIO_AAC_MPEG4;
esd->decoderConfig->decoderSpecificInfo->dataLength = dec->extradata_size;
esd->decoderConfig->decoderSpecificInfo->data = (char*)gf_malloc(sizeof(char)*dec->extradata_size);
memcpy(esd->decoderConfig->decoderSpecificInfo->data,
dec->extradata,
sizeof(char)*dec->extradata_size);
break;
default:
opaque_audio:
esd->decoderConfig->objectTypeIndication = GPAC_OTI_MEDIA_FFMPEG;
bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
gf_bs_write_u32(bs, dec->codec_id);
gf_bs_write_u32(bs, dec->sample_rate);
gf_bs_write_u16(bs, dec->channels);
gf_bs_write_u16(bs, dec->frame_size);
gf_bs_write_u8(bs, 16);
gf_bs_write_u8(bs, 0);
/*ffmpeg specific*/
gf_bs_write_u16(bs, dec->block_align);
gf_bs_write_u32(bs, dec->bit_rate);
gf_bs_write_u32(bs, dec->codec_tag);
if (dec->extradata_size) {
gf_bs_write_data(bs, (char *) dec->extradata, dec->extradata_size);
}
gf_bs_get_content(bs, (char **) &esd->decoderConfig->decoderSpecificInfo->data, &esd->decoderConfig->decoderSpecificInfo->dataLength);
gf_bs_del(bs);
break;
}
dont_use_sl = ffd->unreliable_audio_timing;
} else {
AVCodecContext *dec = ffd->ctx->streams[ffd->video_st]->codec;
esd->slConfig->timestampResolution = ffd->video_tscale.den;
switch (dec->codec_id) {
case CODEC_ID_MPEG4:
/*there is a bug in fragmentation of raw H264 in ffmpeg, the NALU startcode (0x00000001) is split across
two frames - we therefore force internal ffmpeg codec ID to avoid NALU size recompute
at the decoder level*/
// case CODEC_ID_H264:
/*if dsi not detected force use ffmpeg*/
if (!dec->extradata_size) goto opaque_video;
/*otherwise use any MPEG-4 Visual*/
esd->decoderConfig->objectTypeIndication = (dec->codec_id==CODEC_ID_H264) ? GPAC_OTI_VIDEO_AVC : GPAC_OTI_VIDEO_MPEG4_PART2;
esd->decoderConfig->decoderSpecificInfo->dataLength = dec->extradata_size;
esd->decoderConfig->decoderSpecificInfo->data = (char*)gf_malloc(sizeof(char)*dec->extradata_size);
memcpy(esd->decoderConfig->decoderSpecificInfo->data,
dec->extradata,
sizeof(char)*dec->extradata_size);
break;
case CODEC_ID_MPEG1VIDEO:
esd->decoderConfig->objectTypeIndication = GPAC_OTI_VIDEO_MPEG1;
break;
case CODEC_ID_MPEG2VIDEO:
esd->decoderConfig->objectTypeIndication = GPAC_OTI_VIDEO_MPEG2_MAIN;
break;
case CODEC_ID_H263:
esd->decoderConfig->objectTypeIndication = GPAC_OTI_MEDIA_GENERIC;
bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
gf_bs_write_u32(bs, GF_4CC('s', '2', '6', '3') );
gf_bs_write_u16(bs, dec->width);
gf_bs_write_u16(bs, dec->height);
gf_bs_get_content(bs, (char **) &esd->decoderConfig->decoderSpecificInfo->data, &esd->decoderConfig->decoderSpecificInfo->dataLength);
gf_bs_del(bs);
break;
default:
opaque_video:
esd->decoderConfig->objectTypeIndication = GPAC_OTI_MEDIA_FFMPEG;
bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
gf_bs_write_u32(bs, dec->codec_id);
gf_bs_write_u16(bs, dec->width);
gf_bs_write_u16(bs, dec->height);
/*ffmpeg specific*/
gf_bs_write_u32(bs, dec->bit_rate);
gf_bs_write_u32(bs, dec->codec_tag);
gf_bs_write_u32(bs, dec->pix_fmt);
if (dec->extradata_size) {
gf_bs_write_data(bs, (char *) dec->extradata, dec->extradata_size);
}
gf_bs_get_content(bs, (char **) &esd->decoderConfig->decoderSpecificInfo->data, &esd->decoderConfig->decoderSpecificInfo->dataLength);
gf_bs_del(bs);
break;
}
dont_use_sl = GF_FALSE;
}
if (dont_use_sl) {
esd->slConfig->predefined = SLPredef_SkipSL;
} else {
/*only send full AUs*/
esd->slConfig->useAccessUnitStartFlag = esd->slConfig->useAccessUnitEndFlag = 0;
if (for_audio) {
esd->slConfig->hasRandomAccessUnitsOnlyFlag = 1;
} else {
esd->slConfig->useRandomAccessPointFlag = 1;
}
esd->slConfig->useTimestampsFlag = 1;
}
return esd;
}
static void FFD_SetupObjects(FFDemux *ffd)
{
GF_ESD *esd;
GF_ObjectDescriptor *od;
u32 audio_esid = 0;
if ((ffd->audio_st>=0) && (ffd->service_type != 1)) {
od = (GF_ObjectDescriptor *) gf_odf_desc_new(GF_ODF_OD_TAG);
esd = FFD_GetESDescriptor(ffd, GF_TRUE);
od->objectDescriptorID = esd->ESID;
audio_esid = esd->ESID;
gf_list_add(od->ESDescriptors, esd);
gf_service_declare_media(ffd->service, (GF_Descriptor*)od, (ffd->video_st>=0) ? GF_TRUE : GF_FALSE);
}
if ((ffd->video_st>=0) && (ffd->service_type != 2)) {
od = (GF_ObjectDescriptor *) gf_odf_desc_new(GF_ODF_OD_TAG);
esd = FFD_GetESDescriptor(ffd, GF_FALSE);
od->objectDescriptorID = esd->ESID;
esd->OCRESID = audio_esid;
gf_list_add(od->ESDescriptors, esd);
gf_service_declare_media(ffd->service, (GF_Descriptor*)od, GF_FALSE);
}
}
#ifdef USE_PRE_0_7
static int ff_url_read(void *h, unsigned char *buf, int size)
{
u32 retry = 10;
u32 read;
int full_size;
FFDemux *ffd = (FFDemux *)h;
full_size = 0;
if (ffd->buffer_used) {
if (ffd->buffer_used >= (u32) size) {
ffd->buffer_used-=size;
memcpy(ffd->buffer, ffd->buffer+size, sizeof(char)*ffd->buffer_used);
#ifdef FFMPEG_DUMP_REMOTE
if (ffd->outdbg) gf_fwrite(buf, size, 1, ffd->outdbg);
#endif
return size;
}
full_size += ffd->buffer_used;
buf += ffd->buffer_used;
size -= ffd->buffer_used;
ffd->buffer_used = 0;
}
while (size) {
GF_Err e = gf_dm_sess_fetch_data(ffd->dnload, buf, size, &read);
if (e==GF_EOS) break;
/*we're sync!!*/
if (e==GF_IP_NETWORK_EMPTY) {
if (!retry) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[FFMPEG Demuxer] timeout fetching bytes from network\n") );
return -1;
}
retry --;
gf_sleep(100);
continue;
}
if (e) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[FFMPEG Demuxer] error fetching bytes from network: %s\n", gf_error_to_string(e) ) );
return -1;
}
full_size += read;
if (read==size) break;
size -= read;
buf += read;
}
#ifdef FFMPEG_DUMP_REMOTE
if (ffd->outdbg) gf_fwrite(ffd->buffer, full_size, 1, ffd->outdbg);
#endif
return full_size ? (int) full_size : -1;
}
#endif /*USE_PRE_0_7*/
static GF_Err FFD_ConnectService(GF_InputService *plug, GF_ClientService *serv, const char *url)
{
GF_Err e;
s64 last_aud_pts;
u32 i;
s32 res;
Bool is_local;
const char *sOpt;
char *ext, szName[1024];
FFDemux *ffd = (FFDemux*)plug->priv;
AVInputFormat *av_in = NULL;
char szExt[20];
if (ffd->ctx) return GF_SERVICE_ERROR;
assert( url && strlen(url) < 1024);
strcpy(szName, url);
ext = strrchr(szName, '#');
ffd->service_type = 0;
ffd->service = serv;
if (ext) {
if (!stricmp(&ext[1], "video")) ffd->service_type = 1;
else if (!stricmp(&ext[1], "audio")) ffd->service_type = 2;
ext[0] = 0;
}
ffd_parse_options(ffd, url);
/*some extensions not supported by ffmpeg, overload input format*/
ext = strrchr(szName, '.');
strcpy(szExt, ext ? ext+1 : "");
strlwr(szExt);
if (!strcmp(szExt, "cmp")) av_in = av_find_input_format("m4v");
is_local = (strnicmp(url, "file://", 7) && strstr(url, "://")) ? GF_FALSE : GF_TRUE;
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[FFMPEG] opening file %s - local %d - av_in %08x\n", url, is_local, av_in));
if (!is_local) {
AVProbeData pd;
/*setup wraper for FFMPEG I/O*/
ffd->buffer_size = 8192;
sOpt = gf_modules_get_option((GF_BaseInterface *)plug, "FFMPEG", "IOBufferSize");
if (sOpt) ffd->buffer_size = atoi(sOpt);
ffd->buffer = (char*)gf_malloc(sizeof(char)*ffd->buffer_size);
#ifdef FFMPEG_DUMP_REMOTE
ffd->outdbg = gf_fopen("ffdeb.raw", "wb");
#endif
#ifdef USE_PRE_0_7
init_put_byte(&ffd->io, ffd->buffer, ffd->buffer_size, 0, ffd, ff_url_read, NULL, NULL);
ffd->io.is_streamed = 1;
#else
ffd->io.seekable = 1;
#endif
ffd->dnload = gf_service_download_new(ffd->service, url, GF_NETIO_SESSION_NOT_THREADED | GF_NETIO_SESSION_NOT_CACHED, NULL, ffd);
if (!ffd->dnload) return GF_URL_ERROR;
while (1) {
u32 read;
e = gf_dm_sess_fetch_data(ffd->dnload, ffd->buffer + ffd->buffer_used, ffd->buffer_size - ffd->buffer_used, &read);
if (e==GF_EOS) break;
/*we're sync!!*/
if (e==GF_IP_NETWORK_EMPTY) continue;
if (e) goto err_exit;
ffd->buffer_used += read;
if (ffd->buffer_used == ffd->buffer_size) break;
}
if (e==GF_EOS) {
const char *cache_file = gf_dm_sess_get_cache_name(ffd->dnload);
res = open_file(&ffd->ctx, cache_file, av_in, ffd->options ? &ffd->options : NULL);
} else {
pd.filename = szName;
pd.buf_size = ffd->buffer_used;
pd.buf = (u8 *) ffd->buffer;
av_in = av_probe_input_format(&pd, 1);
if (!av_in) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[FFMPEG] error probing file %s - probe start with %c %c %c %c\n", url, ffd->buffer[0], ffd->buffer[1], ffd->buffer[2], ffd->buffer[3]));
return GF_NOT_SUPPORTED;
}
/*setup downloader*/
av_in->flags |= AVFMT_NOFILE;
#ifdef USE_AVFORMAT_OPEN_INPUT /*commit ffmpeg 603b8bc2a109978c8499b06d2556f1433306eca7*/
res = avformat_open_input(&ffd->ctx, szName, av_in, NULL);
#else
res = av_open_input_stream(&ffd->ctx, &ffd->io, szName, av_in, NULL);
#endif
}
} else {
res = open_file(&ffd->ctx, szName, av_in, ffd->options ? &ffd->options : NULL);
}
switch (res) {
#ifndef _WIN32_WCE
case 0:
e = GF_OK;
break;
case AVERROR_IO:
e = GF_URL_ERROR;
goto err_exit;
case AVERROR_INVALIDDATA:
e = GF_NON_COMPLIANT_BITSTREAM;
goto err_exit;
case AVERROR_NOMEM:
e = GF_OUT_OF_MEM;
goto err_exit;
case AVERROR_NOFMT:
e = GF_NOT_SUPPORTED;
goto err_exit;
#endif
default:
e = GF_SERVICE_ERROR;
goto err_exit;
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[FFMPEG] looking for streams in %s - %d streams - type %s\n", ffd->ctx->filename, ffd->ctx->nb_streams, ffd->ctx->iformat->name));
#ifdef USE_AVFORMAT_OPEN_INPUT
res = avformat_find_stream_info(ffd->ctx, ffd->options ? &ffd->options : NULL);
#else
res = av_find_stream_info(ffd->ctx);
#endif
if (res <0) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[FFMPEG] cannot locate streams - error %d\n", res));
e = GF_NOT_SUPPORTED;
goto err_exit;
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[FFMPEG] file %s opened - %d streams\n", url, ffd->ctx->nb_streams));
/*figure out if we can use codecs or not*/
ffd->audio_st = ffd->video_st = -1;
for (i = 0; i < ffd->ctx->nb_streams; i++) {
AVCodecContext *enc = ffd->ctx->streams[i]->codec;
switch(enc->codec_type) {
case AVMEDIA_TYPE_AUDIO:
if ((ffd->audio_st<0) && (ffd->service_type!=1)) {
ffd->audio_st = i;
ffd->audio_tscale = ffd->ctx->streams[i]->time_base;
}
break;
case AVMEDIA_TYPE_VIDEO:
if ((ffd->video_st<0) && (ffd->service_type!=2)) {
ffd->video_st = i;
ffd->video_tscale = ffd->ctx->streams[i]->time_base;
}
break;
default:
break;
}
}
if ((ffd->service_type==1) && (ffd->video_st<0)) goto err_exit;
if ((ffd->service_type==2) && (ffd->audio_st<0)) goto err_exit;
if ((ffd->video_st<0) && (ffd->audio_st<0)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[FFMPEG] No supported streams in file\n"));
goto err_exit;
}
sOpt = gf_modules_get_option((GF_BaseInterface *)plug, "FFMPEG", "DataBufferMS");
ffd->data_buffer_ms = 0;
if (sOpt) ffd->data_buffer_ms = atoi(sOpt);
if (!ffd->data_buffer_ms) ffd->data_buffer_ms = FFD_DATA_BUFFER;
/*build seek*/
if (is_local) {
/*check we do have increasing pts. If not we can't rely on pts, we must skip SL
we assume video pts is always present*/
if (ffd->audio_st>=0) {
last_aud_pts = 0;
for (i=0; i<20; i++) {
AVPacket pkt;
pkt.stream_index = -1;
if (av_read_frame(ffd->ctx, &pkt) <0) break;
if (pkt.pts == AV_NOPTS_VALUE) pkt.pts = pkt.dts;
if (pkt.stream_index==ffd->audio_st) last_aud_pts = pkt.pts;
}
if (last_aud_pts*ffd->audio_tscale.den<10*ffd->audio_tscale.num) ffd->unreliable_audio_timing = GF_TRUE;
}
ffd->seekable = (av_seek_frame(ffd->ctx, -1, 0, AVSEEK_FLAG_BACKWARD)<0) ? GF_FALSE : GF_TRUE;
if (!ffd->seekable) {
#if FF_API_CLOSE_INPUT_FILE
av_close_input_file(ffd->ctx);
#else
avformat_close_input(&ffd->ctx);
#endif
ffd->ctx = NULL;
open_file(&ffd->ctx, szName, av_in, ffd->options ? &ffd->options : NULL);
av_find_stream_info(ffd->ctx);
}
}
/*let's go*/
gf_service_connect_ack(serv, NULL, GF_OK);
/*if (!ffd->service_type)*/ FFD_SetupObjects(ffd);
ffd->service_type = 0;
return GF_OK;
err_exit:
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[FFMPEG] Error opening file %s: %s\n", url, gf_error_to_string(e)));
#if FF_API_CLOSE_INPUT_FILE
if (ffd->ctx) av_close_input_file(ffd->ctx);
#else
if (ffd->ctx) avformat_close_input(&ffd->ctx);
#endif
ffd->ctx = NULL;
gf_service_connect_ack(serv, NULL, e);
return e;
}
static GF_Descriptor *FFD_GetServiceDesc(GF_InputService *plug, u32 expect_type, const char *sub_url)
{
GF_ObjectDescriptor *od;
GF_ESD *esd;
FFDemux *ffd = (FFDemux*)plug->priv;
if (!ffd->ctx) return NULL;
if (expect_type==GF_MEDIA_OBJECT_UNDEF) {
if (ffd->video_st>=0) expect_type=GF_MEDIA_OBJECT_VIDEO;
else if (ffd->audio_st>=0) expect_type=GF_MEDIA_OBJECT_AUDIO;
}
/*since we don't handle multitrack in ffmpeg, we don't need to check sub_url, only use expected type*/
if (expect_type==GF_MEDIA_OBJECT_AUDIO) {
if (ffd->audio_st<0) return NULL;
od = (GF_ObjectDescriptor *) gf_odf_desc_new(GF_ODF_OD_TAG);
od->objectDescriptorID = 1;
esd = FFD_GetESDescriptor(ffd, GF_TRUE);
/*if session join, setup sync*/
if (ffd->video_ch) esd->OCRESID = ffd->video_st+1;
gf_list_add(od->ESDescriptors, esd);
ffd->service_type = 2;
return (GF_Descriptor *) od;
}
if (expect_type==GF_MEDIA_OBJECT_VIDEO) {
if (ffd->video_st<0) return NULL;
od = (GF_ObjectDescriptor *) gf_odf_desc_new(GF_ODF_OD_TAG);
od->objectDescriptorID = 1;
esd = FFD_GetESDescriptor(ffd, GF_FALSE);
/*if session join, setup sync*/
if (ffd->audio_ch) esd->OCRESID = ffd->audio_st+1;
gf_list_add(od->ESDescriptors, esd);
ffd->service_type = 1;
return (GF_Descriptor *) od;
}
return NULL;
}
static GF_Err FFD_CloseService(GF_InputService *plug)
{
FFDemux *ffd = (FFDemux*)plug->priv;
ffd->is_running = 0;
#if FF_API_CLOSE_INPUT_FILE
if (ffd->ctx) av_close_input_file(ffd->ctx);
#else
if (ffd->ctx) avformat_close_input(&ffd->ctx);
#endif
ffd->ctx = NULL;
ffd->audio_ch = ffd->video_ch = NULL;
ffd->audio_run = ffd->video_run = GF_FALSE;
if (ffd->dnload) {
if (ffd->is_running) {
while (!ffd->is_running) gf_sleep(1);
ffd->is_running = 0;
}
gf_service_download_del(ffd->dnload);
ffd->dnload = NULL;
}
if (ffd->buffer) gf_free(ffd->buffer);
ffd->buffer = NULL;
gf_service_disconnect_ack(ffd->service, NULL, GF_OK);
#ifdef FFMPEG_DUMP_REMOTE
if (ffd->outdbg) gf_fclose(ffd->outdbg);
#endif
return GF_OK;
}
static GF_Err FFD_ConnectChannel(GF_InputService *plug, LPNETCHANNEL channel, const char *url, Bool upstream)
{
GF_Err e;
u32 ESID;
FFDemux *ffd = (FFDemux*)plug->priv;
e = GF_STREAM_NOT_FOUND;
if (upstream) {
e = GF_ISOM_INVALID_FILE;
goto exit;
}
if (!strstr(url, "ES_ID=")) {
e = GF_NOT_SUPPORTED;
goto exit;
}
sscanf(url, "ES_ID=%u", &ESID);
if ((s32) ESID == 1 + ffd->audio_st) {
if (ffd->audio_ch) {
e = GF_SERVICE_ERROR;
goto exit;
}
ffd->audio_ch = channel;
e = GF_OK;
}
else if ((s32) ESID == 1 + ffd->video_st) {
if (ffd->video_ch) {
e = GF_SERVICE_ERROR;
goto exit;
}
ffd->video_ch = channel;
e = GF_OK;
}
exit:
gf_service_connect_ack(ffd->service, channel, e);
return GF_OK;
}
static GF_Err FFD_DisconnectChannel(GF_InputService *plug, LPNETCHANNEL channel)
{
GF_Err e;
FFDemux *ffd = (FFDemux*)plug->priv;
e = GF_STREAM_NOT_FOUND;
if (ffd->audio_ch == channel) {
e = GF_OK;
ffd->audio_ch = NULL;
ffd->audio_run = GF_FALSE;
}
else if (ffd->video_ch == channel) {
e = GF_OK;
ffd->video_ch = NULL;
ffd->video_run = GF_FALSE;
}
gf_service_disconnect_ack(ffd->service, channel, e);
return GF_OK;
}
static GF_Err FFD_ServiceCommand(GF_InputService *plug, GF_NetworkCommand *com)
{
FFDemux *ffd = (FFDemux*)plug->priv;
if (com->command_type==GF_NET_SERVICE_HAS_AUDIO) {
if (ffd->audio_st>=0) return GF_OK;
return GF_NOT_SUPPORTED;
}
if (!com->base.on_channel) return GF_NOT_SUPPORTED;
switch (com->command_type) {
/*only BIFS/OD work in pull mode (cf ffmpeg_in.h)*/
case GF_NET_CHAN_SET_PULL:
return GF_NOT_SUPPORTED;
case GF_NET_CHAN_INTERACTIVE:
return ffd->seekable ? GF_OK : GF_NOT_SUPPORTED;
case GF_NET_CHAN_BUFFER:
return GF_OK;
case GF_NET_CHAN_DURATION:
if (ffd->ctx->duration == AV_NOPTS_VALUE)
com->duration.duration = -1;
else
com->duration.duration = (Double) ffd->ctx->duration / AV_TIME_BASE;
return GF_OK;
/*fetch start time*/
case GF_NET_CHAN_PLAY:
if (com->play.speed<0) return GF_NOT_SUPPORTED;
gf_mx_p(ffd->mx);
ffd->seek_time = (com->play.start_range>=0) ? com->play.start_range : 0;
if (ffd->audio_ch==com->base.on_channel) ffd->audio_run = GF_TRUE;
else if (ffd->video_ch==com->base.on_channel) ffd->video_run = GF_TRUE;
/*play on media stream, start thread*/
if ((ffd->audio_ch==com->base.on_channel) || (ffd->video_ch==com->base.on_channel)) {
if (ffd->is_running!=1) {
ffd->is_running = 1;
gf_th_run(ffd->thread, FFDemux_Run, ffd);
}
}
gf_mx_v(ffd->mx);
return GF_OK;
case GF_NET_CHAN_STOP:
if (ffd->audio_ch==com->base.on_channel) ffd->audio_run = GF_FALSE;
else if (ffd->video_ch==com->base.on_channel) ffd->video_run = GF_FALSE;
return GF_OK;
/*note we don't handle PAUSE/RESUME/SET_SPEED, this is automatically handled by the demuxing thread
through buffer occupancy queries*/
default:
return GF_OK;
}
return GF_OK;
}
static Bool FFD_CanHandleURLInService(GF_InputService *plug, const char *url)
{
char szURL[2048], *sep;
FFDemux *ffd;
const char *this_url;
if (!plug || !url)
return GF_FALSE;
ffd = (FFDemux *)plug->priv;
this_url = gf_service_get_url(ffd->service);
if (!this_url)
return GF_FALSE;
strcpy(szURL, this_url);
sep = strrchr(szURL, '#');
if (sep) sep[0] = 0;
if ((url[0] != '#') && strnicmp(szURL, url, sizeof(char)*strlen(szURL))) return GF_FALSE;
sep = strrchr(url, '#');
if (sep && !stricmp(sep, "#video") && (ffd->video_st>=0)) return GF_TRUE;
if (sep && !stricmp(sep, "#audio") && (ffd->audio_st>=0)) return GF_TRUE;
return GF_FALSE;
}
void *New_FFMPEG_Demux()
{
GF_InputService *ffd;
FFDemux *priv;
GF_SAFEALLOC(ffd, GF_InputService);
if (!ffd) return NULL;
GF_SAFEALLOC(priv, FFDemux);
if (!priv) {
gf_free(ffd);
return NULL;
}
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[FFMPEG Demuxer] Registering all ffmpeg plugins...\n") );
/* register all codecs, demux and protocols */
av_register_all();
avformat_network_init();
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[FFMPEG Demuxer] Registering all ffmpeg plugins DONE.\n") );
ffd->RegisterMimeTypes = FFD_RegisterMimeTypes;
ffd->CanHandleURL = FFD_CanHandleURL;
ffd->CloseService = FFD_CloseService;
ffd->ConnectChannel = FFD_ConnectChannel;
ffd->ConnectService = FFD_ConnectService;
ffd->DisconnectChannel = FFD_DisconnectChannel;
ffd->GetServiceDescriptor = FFD_GetServiceDesc;
ffd->ServiceCommand = FFD_ServiceCommand;
ffd->CanHandleURLInService = FFD_CanHandleURLInService;
priv->thread = gf_th_new("FFMPEG Demux");
priv->mx = gf_mx_new("FFMPEG Demux");
if (!priv->thread || !priv->mx) {
if (priv->thread) gf_th_del(priv->thread);
if (priv->mx) gf_mx_del(priv->mx);
gf_free(priv);
return NULL;
}
GF_REGISTER_MODULE_INTERFACE(ffd, GF_NET_CLIENT_INTERFACE, "FFMPEG Demuxer", "gpac distribution");
ffd->priv = priv;
return ffd;
}
void Delete_FFMPEG_Demux(void *ifce)
{
FFDemux *ffd;
GF_InputService *ptr = (GF_InputService *)ifce;
if (!ptr)
return;
ffd = (FFDemux*)ptr->priv;
if (ffd) {
if (ffd->thread)
gf_th_del(ffd->thread);
ffd->thread = NULL;
if (ffd->mx)
gf_mx_del(ffd->mx);
#ifndef USE_PRE_0_7
if (ffd->options) av_dict_free(&ffd->options);
#endif
ffd->mx = NULL;
gf_free(ffd);
ptr->priv = NULL;
}
gf_free(ptr);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_525_2 |
crossvul-cpp_data_bad_3104_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT IIIII FFFFF FFFFF %
% T I F F %
% T I FFF FFF %
% T I F F %
% T IIIII F F %
% %
% %
% Read/Write TIFF Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/draw.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/memory-private.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/resize.h"
#include "magick/resource_.h"
#include "magick/semaphore.h"
#include "magick/splay-tree.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/thread_.h"
#include "magick/token.h"
#include "magick/utility.h"
#if defined(MAGICKCORE_TIFF_DELEGATE)
# if defined(MAGICKCORE_HAVE_TIFFCONF_H)
# include "tiffconf.h"
# endif
# include "tiff.h"
# include "tiffio.h"
# if !defined(COMPRESSION_ADOBE_DEFLATE)
# define COMPRESSION_ADOBE_DEFLATE 8
# endif
# if !defined(PREDICTOR_HORIZONTAL)
# define PREDICTOR_HORIZONTAL 2
# endif
# if !defined(TIFFTAG_COPYRIGHT)
# define TIFFTAG_COPYRIGHT 33432
# endif
# if !defined(TIFFTAG_OPIIMAGEID)
# define TIFFTAG_OPIIMAGEID 32781
# endif
#include "psd-private.h"
/*
Typedef declarations.
*/
typedef enum
{
ReadSingleSampleMethod,
ReadRGBAMethod,
ReadCMYKAMethod,
ReadYCCKMethod,
ReadStripMethod,
ReadTileMethod,
ReadGenericMethod
} TIFFMethodType;
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
typedef struct _ExifInfo
{
unsigned int
tag,
type,
variable_length;
const char
*property;
} ExifInfo;
static const ExifInfo
exif_info[] = {
{ EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" },
{ EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" },
{ EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" },
{ EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" },
{ EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" },
{ EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" },
{ EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" },
{ EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" },
{ EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" },
{ EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" },
{ EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" },
{ EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" },
{ EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" },
{ EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" },
{ EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" },
{ EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" },
{ EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" },
{ EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" },
{ EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" },
{ EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" },
{ EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" },
{ EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" },
{ EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" },
{ EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" },
{ EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" },
{ EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" },
{ EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" },
{ EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" },
{ EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" },
{ EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" },
{ EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" },
{ EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" },
{ EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" },
{ EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" },
{ EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" },
{ EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" },
{ EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" },
{ EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" },
{ EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" },
{ EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" },
{ EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" },
{ EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" },
{ EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" },
{ EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" },
{ EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" },
{ EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" },
{ EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" },
{ EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" },
{ EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" },
{ EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" },
{ EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" },
{ EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" },
{ EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" },
{ EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" },
{ EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" },
{ 0, 0, 0, (char *) NULL }
};
#endif
#endif /* MAGICKCORE_TIFF_DELEGATE */
/*
Global declarations.
*/
static MagickThreadKey
tiff_exception;
static SemaphoreInfo
*tiff_semaphore = (SemaphoreInfo *) NULL;
static TIFFErrorHandler
error_handler,
warning_handler;
static volatile MagickBooleanType
instantiate_key = MagickFalse;
/*
Forward declarations.
*/
#if defined(MAGICKCORE_TIFF_DELEGATE)
static Image *
ReadTIFFImage(const ImageInfo *,ExceptionInfo *);
static MagickBooleanType
WriteGROUP4Image(const ImageInfo *,Image *),
WritePTIFImage(const ImageInfo *,Image *),
WriteTIFFImage(const ImageInfo *,Image *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T I F F %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTIFF() returns MagickTrue if the image format type, identified by the
% magick string, is TIFF.
%
% The format of the IsTIFF method is:
%
% MagickBooleanType IsTIFF(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 IsTIFF(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\115\115\000\052",4) == 0)
return(MagickTrue);
if (memcmp(magick,"\111\111\052\000",4) == 0)
return(MagickTrue);
#if defined(TIFF_VERSION_BIG)
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0)
return(MagickTrue);
if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0)
return(MagickTrue);
#endif
return(MagickFalse);
}
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d G R O U P 4 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadGROUP4Image() reads a raw CCITT Group 4 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 ReadGROUP4Image method is:
%
% Image *ReadGROUP4Image(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 inline size_t WriteLSBLong(FILE *file,const size_t value)
{
unsigned char
buffer[4];
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
buffer[2]=(unsigned char) (value >> 16);
buffer[3]=(unsigned char) (value >> 24);
return(fwrite(buffer,1,4,file));
}
static Image *ReadGROUP4Image(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MaxTextExtent];
FILE
*file;
Image
*image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
size_t
length;
ssize_t
offset,
strip_offset;
/*
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);
}
/*
Write raw CCITT Group 4 wrapped as a TIFF image file.
*/
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file);
length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\000\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->columns);
length=fwrite("\001\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file);
length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\021\001\003\000\001\000\000\000",1,8,file);
strip_offset=10+(12*14)+4+8;
length=WriteLSBLong(file,(size_t) strip_offset);
length=fwrite("\022\001\003\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) image_info->orientation);
length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\026\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file);
offset=(ssize_t) ftell(file)-4;
length=fwrite("\032\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) (strip_offset-8));
length=fwrite("\033\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(size_t) (strip_offset-8));
length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file);
length=fwrite("\000\000\000\000",1,4,file);
length=WriteLSBLong(file,(size_t) (image->x_resolution+0.5));
length=WriteLSBLong(file,1);
status=MagickTrue;
for (length=0; (c=ReadBlobByte(image)) != EOF; length++)
if (fputc(c,file) != c)
status=MagickFalse;
offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);
length=WriteLSBLong(file,(unsigned int) length);
(void) fclose(file);
(void) CloseBlob(image);
image=DestroyImage(image);
/*
Read TIFF image.
*/
read_info=CloneImageInfo((ImageInfo *) NULL);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"%s",filename);
image=ReadTIFFImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
{
(void) CopyMagickString(image->filename,image_info->filename,
MaxTextExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MaxTextExtent);
(void) CopyMagickString(image->magick,"GROUP4",MaxTextExtent);
}
(void) RelinquishUniqueFileResource(filename);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTIFFImage() reads a Tagged 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 ReadTIFFImage method is:
%
% Image *ReadTIFFImage(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 inline unsigned char ClampYCC(double value)
{
value=255.0-value;
if (value < 0.0)
return((unsigned char)0);
if (value > 255.0)
return((unsigned char)255);
return((unsigned char)(value));
}
static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
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,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
a,
b;
a=QuantumScale*GetPixela(q)+0.5;
if (a > 1.0)
a-=1.0;
b=QuantumScale*GetPixelb(q)+0.5;
if (b > 1.0)
b-=1.0;
SetPixela(q,QuantumRange*a);
SetPixelb(q,QuantumRange*b);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
static MagickBooleanType ReadProfile(Image *image,const char *name,
const unsigned char *datum,ssize_t length)
{
MagickBooleanType
status;
StringInfo
*profile;
if (length < 4)
return(MagickFalse);
profile=BlobToStringInfo(datum,(size_t) length);
if (profile == (StringInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=SetImageProfile(image,name,profile);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
return(MagickTrue);
}
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int TIFFCloseBlob(thandle_t image)
{
(void) CloseBlob((Image *) image);
return(0);
}
static void TIFFErrors(const char *module,const char *format,va_list error)
{
char
message[MaxTextExtent];
ExceptionInfo
*exception;
#if defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsnprintf(message,MaxTextExtent,format,error);
#else
(void) vsprintf(message,format,error);
#endif
(void) ConcatenateMagickString(message,".",MaxTextExtent);
exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
if (exception != (ExceptionInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,message,
"`%s'",module);
}
static toff_t TIFFGetBlobSize(thandle_t image)
{
return((toff_t) GetBlobSize((Image *) image));
}
static void TIFFGetProfiles(TIFF *tiff,Image *image,MagickBooleanType ping)
{
uint32
length;
unsigned char
*profile;
length=0;
if (ping == MagickFalse)
{
#if defined(TIFFTAG_ICCPROFILE)
if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"icc",profile,(ssize_t) length);
#endif
#if defined(TIFFTAG_PHOTOSHOP)
if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"8bim",profile,(ssize_t) length);
#endif
#if defined(TIFFTAG_RICHTIFFIPTC)
if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
{
if (TIFFIsByteSwapped(tiff) != 0)
TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length);
(void) ReadProfile(image,"iptc",profile,4L*length);
}
#endif
#if defined(TIFFTAG_XMLPACKET)
if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"xmp",profile,(ssize_t) length);
#endif
if ((TIFFGetField(tiff,34118,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length);
}
if ((TIFFGetField(tiff,37724,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length);
}
static void TIFFGetProperties(TIFF *tiff,Image *image)
{
char
message[MaxTextExtent],
*text;
uint32
count,
length,
type;
unsigned long
*tietz;
if ((TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:artist",text);
if ((TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:copyright",text);
if ((TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:timestamp",text);
if ((TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:document",text);
if ((TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:hostcomputer",text);
if ((TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"comment",text);
if ((TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:make",text);
if ((TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:model",text);
if ((TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) &&
(text != (char *) NULL))
{
if (count >= MaxTextExtent)
count=MaxTextExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:image-id",message);
}
if ((TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"label",text);
if ((TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:software",text);
if ((TIFFGetField(tiff,33423,&count,&text) == 1) &&
(text != (char *) NULL))
{
if (count >= MaxTextExtent)
count=MaxTextExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-33423",message);
}
if ((TIFFGetField(tiff,36867,&count,&text) == 1) &&
(text != (char *) NULL))
{
if (count >= MaxTextExtent)
count=MaxTextExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-36867",message);
}
if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1)
switch (type)
{
case 0x01:
{
(void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE");
break;
}
case 0x02:
{
(void) SetImageProperty(image,"tiff:subfiletype","PAGE");
break;
}
case 0x04:
{
(void) SetImageProperty(image,"tiff:subfiletype","MASK");
break;
}
default:
break;
}
if ((TIFFGetField(tiff,37706,&length,&tietz) == 1) &&
(tietz != (unsigned long *) NULL))
{
(void) FormatLocaleString(message,MaxTextExtent,"%lu",tietz[0]);
(void) SetImageProperty(image,"tiff:tietz_offset",message);
}
}
static void TIFFGetEXIFProperties(TIFF *tiff,Image *image)
{
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
char
value[MaxTextExtent];
register ssize_t
i;
tdir_t
directory;
#if defined(TIFF_VERSION_BIG)
uint64
#else
uint32
#endif
offset;
void
*sans;
/*
Read EXIF properties.
*/
offset=0;
if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1)
return;
directory=TIFFCurrentDirectory(tiff);
if (TIFFReadEXIFDirectory(tiff,offset) != 1)
{
TIFFSetDirectory(tiff,directory);
return;
}
sans=NULL;
for (i=0; exif_info[i].tag != 0; i++)
{
*value='\0';
switch (exif_info[i].type)
{
case TIFF_ASCII:
{
char
*ascii;
ascii=(char *) NULL;
if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans,&sans) == 1) &&
(ascii != (char *) NULL) && (*ascii != '\0'))
(void) CopyMagickString(value,ascii,MaxTextExtent);
break;
}
case TIFF_SHORT:
{
if (exif_info[i].variable_length == 0)
{
uint16
shorty;
shorty=0;
if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%d",shorty);
}
else
{
int
tiff_status;
uint16
*shorty;
uint16
shorty_num;
tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty,
&sans,&sans);
if (tiff_status == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%d",
shorty_num != 0 ? shorty[0] : 0);
}
break;
}
case TIFF_LONG:
{
uint32
longy;
longy=0;
if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%d",longy);
break;
}
#if defined(TIFF_VERSION_BIG)
case TIFF_LONG8:
{
uint64
long8y;
long8y=0;
if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
((MagickOffsetType) long8y));
break;
}
#endif
case TIFF_RATIONAL:
case TIFF_SRATIONAL:
case TIFF_FLOAT:
{
float
floaty;
floaty=0.0;
if (TIFFGetField(tiff,exif_info[i].tag,&floaty,&sans,&sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%g",(double) floaty);
break;
}
case TIFF_DOUBLE:
{
double
doubley;
doubley=0.0;
if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%g",doubley);
break;
}
default:
break;
}
if (*value != '\0')
(void) SetImageProperty(image,exif_info[i].property,value);
}
TIFFSetDirectory(tiff,directory);
#else
(void) tiff;
(void) image;
#endif
}
static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size)
{
*base=(tdata_t *) GetBlobStreamData((Image *) image);
if (*base != (tdata_t *) NULL)
*size=(toff_t) GetBlobSize((Image *) image);
if (*base != (tdata_t *) NULL)
return(1);
return(0);
}
static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size)
{
tsize_t
count;
count=(tsize_t) ReadBlob((Image *) image,(size_t) size,
(unsigned char *) data);
return(count);
}
static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample,
tsample_t sample,ssize_t row,tdata_t scanline)
{
int32
status;
(void) bits_per_sample;
status=TIFFReadScanline(tiff,scanline,(uint32) row,sample);
return(status);
}
static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence)
{
return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence));
}
static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size)
{
(void) image;
(void) base;
(void) size;
}
static void TIFFWarnings(const char *module,const char *format,va_list warning)
{
char
message[MaxTextExtent];
ExceptionInfo
*exception;
#if defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsnprintf(message,MaxTextExtent,format,warning);
#else
(void) vsprintf(message,format,warning);
#endif
(void) ConcatenateMagickString(message,".",MaxTextExtent);
exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
if (exception != (ExceptionInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
message,"`%s'",module);
}
static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size)
{
tsize_t
count;
count=(tsize_t) WriteBlob((Image *) image,(size_t) size,
(unsigned char *) data);
return(count);
}
static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric,
uint16 bits_per_sample,uint16 samples_per_pixel)
{
#define BUFFER_SIZE 2048
MagickOffsetType
position,
offset;
register size_t
i;
TIFFMethodType
method;
#if defined(TIFF_VERSION_BIG)
uint64
#else
uint32
#endif
**value;
unsigned char
buffer[BUFFER_SIZE+32];
unsigned short
length;
/* only support 8 bit for now */
if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) ||
(samples_per_pixel != 4))
return(ReadGenericMethod);
/* Search for Adobe APP14 JPEG Marker */
if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value))
return(ReadRGBAMethod);
position=TellBlob(image);
offset=(MagickOffsetType) (value[0]);
if (SeekBlob(image,offset,SEEK_SET) != offset)
return(ReadRGBAMethod);
method=ReadRGBAMethod;
if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE)
{
for (i=0; i < BUFFER_SIZE; i++)
{
while (i < BUFFER_SIZE)
{
if (buffer[i++] == 255)
break;
}
while (i < BUFFER_SIZE)
{
if (buffer[++i] != 255)
break;
}
if (buffer[i++] == 216) /* JPEG_MARKER_SOI */
continue;
length=(unsigned short) (((unsigned int) (buffer[i] << 8) |
(unsigned int) buffer[i+1]) & 0xffff);
if (i+(size_t) length >= BUFFER_SIZE)
break;
if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */
{
if (length != 14)
break;
/* 0 == CMYK, 1 == YCbCr, 2 = YCCK */
if (buffer[i+13] == 2)
method=ReadYCCKMethod;
break;
}
i+=(size_t) length;
}
}
(void) SeekBlob(image,position,SEEK_SET);
return(method);
}
static void TIFFReadPhotoshopLayers(Image* image,const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
const StringInfo
*layer_info;
Image
*layers;
PSDInfo
info;
register ssize_t
i;
if (GetImageListLength(image) != 1)
return;
if ((image_info->number_scenes == 1) && (image_info->scene == 0))
return;
option=GetImageOption(image_info,"tiff:ignore-layers");
if (option != (const char * ) NULL)
return;
layer_info=GetImageProfile(image,"tiff:37724");
if (layer_info == (const StringInfo *) NULL)
return;
for (i=0; i < (ssize_t) layer_info->length-8; i++)
{
if (LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0)
continue;
i+=4;
if ((LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) ||
(LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) ||
(LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) ||
(LocaleNCompare((const char *) (layer_info->datum+i),
image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0))
break;
}
i+=4;
if (i >= (ssize_t) (layer_info->length-8))
return;
layers=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
(void) DeleteImageProfile(layers,"tiff:37724");
AttachBlob(layers->blob,layer_info->datum,layer_info->length);
SeekBlob(layers,(MagickOffsetType) i,SEEK_SET);
info.version=1;
info.columns=layers->columns;
info.rows=layers->rows;
/* Setting the mode to a value that won't change the colorspace */
info.mode=10;
if (IsGrayImage(image,&image->exception) != MagickFalse)
info.channels=(image->matte != MagickFalse ? 2UL : 1UL);
else
if (image->storage_class == PseudoClass)
info.channels=(image->matte != MagickFalse ? 2UL : 1UL);
else
{
if (image->colorspace != CMYKColorspace)
info.channels=(image->matte != MagickFalse ? 4UL : 3UL);
else
info.channels=(image->matte != MagickFalse ? 5UL : 4UL);
}
(void) ReadPSDLayers(layers,image_info,&info,MagickFalse,exception);
InheritException(exception,&layers->exception);
DeleteImageFromList(&layers);
if (layers != (Image *) NULL)
{
SetImageArtifact(image,"tiff:has-layers","true");
AppendImageToList(&image,layers);
while (layers != (Image *) NULL)
{
SetImageArtifact(layers,"tiff:has-layers","true");
DetachBlob(layers->blob);
layers=GetNextImageInList(layers);
}
}
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static Image *ReadTIFFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
float
*chromaticity,
x_position,
y_position,
x_resolution,
y_resolution;
Image
*image;
int
tiff_status;
MagickBooleanType
status;
MagickSizeType
number_pixels;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
pad;
ssize_t
y;
TIFF
*tiff;
TIFFMethodType
method;
uint16
compress_tag,
bits_per_sample,
endian,
extra_samples,
interlace,
max_sample_value,
min_sample_value,
orientation,
pages,
photometric,
*sample_info,
sample_format,
samples_per_pixel,
units,
value;
uint32
height,
rows_per_strip,
width;
unsigned char
*tiff_pixels;
/*
Open image.
*/
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);
}
(void) SetMagickThreadValue(tiff_exception,exception);
tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (image_info->number_scenes != 0)
{
/*
Generate blank images for subimage specification (e.g. image.tif[4].
We need to check the number of directores because it is possible that
the subimage(s) are stored in the photoshop profile.
*/
if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff))
{
for (i=0; i < (ssize_t) image_info->scene; i++)
{
status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (status == MagickFalse)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
}
}
}
do
{
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
TIFFPrintDirectory(tiff,stdout,MagickFalse);
RestoreMSCWarning
if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||
(TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1))
{
TIFFClose(tiff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (sample_format == SAMPLEFORMAT_IEEEFP)
(void) SetImageProperty(image,"quantum:format","floating-point");
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-black");
break;
}
case PHOTOMETRIC_MINISWHITE:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-white");
break;
}
case PHOTOMETRIC_PALETTE:
{
(void) SetImageProperty(image,"tiff:photometric","palette");
break;
}
case PHOTOMETRIC_RGB:
{
(void) SetImageProperty(image,"tiff:photometric","RGB");
break;
}
case PHOTOMETRIC_CIELAB:
{
(void) SetImageProperty(image,"tiff:photometric","CIELAB");
break;
}
case PHOTOMETRIC_LOGL:
{
(void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)");
break;
}
case PHOTOMETRIC_LOGLUV:
{
(void) SetImageProperty(image,"tiff:photometric","LOGLUV");
break;
}
#if defined(PHOTOMETRIC_MASK)
case PHOTOMETRIC_MASK:
{
(void) SetImageProperty(image,"tiff:photometric","MASK");
break;
}
#endif
case PHOTOMETRIC_SEPARATED:
{
(void) SetImageProperty(image,"tiff:photometric","separated");
break;
}
case PHOTOMETRIC_YCBCR:
{
(void) SetImageProperty(image,"tiff:photometric","YCBCR");
break;
}
default:
{
(void) SetImageProperty(image,"tiff:photometric","unknown");
break;
}
}
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
(unsigned int) width,(unsigned int) height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
interlace);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Bits per sample: %u",bits_per_sample);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Min sample value: %u",min_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Max sample value: %u",max_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
"interpretation: %s",GetImageProperty(image,"tiff:photometric"));
}
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=(size_t) bits_per_sample;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
(double) image->depth);
image->endian=MSBEndian;
if (endian == FILLORDER_LSB2MSB)
image->endian=LSBEndian;
#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)
if (TIFFIsBigEndian(tiff) == 0)
{
(void) SetImageProperty(image,"tiff:endian","lsb");
image->endian=LSBEndian;
}
else
{
(void) SetImageProperty(image,"tiff:endian","msb");
image->endian=MSBEndian;
}
#endif
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
SetImageColorspace(image,GRAYColorspace);
if (photometric == PHOTOMETRIC_SEPARATED)
SetImageColorspace(image,CMYKColorspace);
if (photometric == PHOTOMETRIC_CIELAB)
SetImageColorspace(image,LabColorspace);
TIFFGetProfiles(tiff,image,image_info->ping);
TIFFGetProperties(tiff,image);
option=GetImageOption(image_info,"tiff:exif-properties");
if ((option == (const char *) NULL) ||
(IsMagickTrue(option) != MagickFalse))
TIFFGetEXIFProperties(tiff,image);
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1))
{
image->x_resolution=x_resolution;
image->y_resolution=y_resolution;
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1)
{
if (units == RESUNIT_INCH)
image->units=PixelsPerInchResolution;
if (units == RESUNIT_CENTIMETER)
image->units=PixelsPerCentimeterResolution;
}
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1))
{
image->page.x=(ssize_t) ceil(x_position*image->x_resolution-0.5);
image->page.y=(ssize_t) ceil(y_position*image->y_resolution-0.5);
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1)
image->orientation=(OrientationType) orientation;
if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.white_point.x=chromaticity[0];
image->chromaticity.white_point.y=chromaticity[1];
}
}
if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.red_primary.x=chromaticity[0];
image->chromaticity.red_primary.y=chromaticity[1];
image->chromaticity.green_primary.x=chromaticity[2];
image->chromaticity.green_primary.y=chromaticity[3];
image->chromaticity.blue_primary.x=chromaticity[4];
image->chromaticity.blue_primary.y=chromaticity[5];
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
TIFFClose(tiff);
ThrowReaderException(CoderError,"CompressNotSupported");
}
#endif
switch (compress_tag)
{
case COMPRESSION_NONE: image->compression=NoCompression; break;
case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;
case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;
case COMPRESSION_JPEG:
{
image->compression=JPEGCompression;
#if defined(JPEG_SUPPORT)
{
char
sampling_factor[MaxTextExtent];
int
tiff_status;
uint16
horizontal,
vertical;
tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal,
&vertical);
if (tiff_status == 1)
{
(void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d",
horizontal,vertical);
(void) SetImageProperty(image,"jpeg:sampling-factor",
sampling_factor);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling Factors: %s",sampling_factor);
}
}
#endif
break;
}
case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;
#if defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA: image->compression=LZMACompression; break;
#endif
case COMPRESSION_LZW: image->compression=LZWCompression; break;
case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;
case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
default: image->compression=RLECompression; break;
}
quantum_info=(QuantumInfo *) NULL;
if ((photometric == PHOTOMETRIC_PALETTE) &&
(pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
{
size_t
colors;
colors=(size_t) GetQuantumRange(bits_per_sample)+1;
if (AcquireImageColormap(image,colors) == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1)
image->scene=value;
if (image->storage_class == PseudoClass)
{
int
tiff_status;
size_t
range;
uint16
*blue_colormap,
*green_colormap,
*red_colormap;
/*
Initialize colormap.
*/
tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
&green_colormap,&blue_colormap);
if (tiff_status == 1)
{
if ((red_colormap != (uint16 *) NULL) &&
(green_colormap != (uint16 *) NULL) &&
(blue_colormap != (uint16 *) NULL))
{
range=255; /* might be old style 8-bit colormap */
for (i=0; i < (ssize_t) image->colors; i++)
if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
(blue_colormap[i] >= 256))
{
range=65535;
break;
}
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ClampToQuantum(((double)
QuantumRange*red_colormap[i])/range);
image->colormap[i].green=ClampToQuantum(((double)
QuantumRange*green_colormap[i])/range);
image->colormap[i].blue=ClampToQuantum(((double)
QuantumRange*blue_colormap[i])/range);
}
}
}
}
if (image_info->ping != MagickFalse)
{
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
goto next_tiff_frame;
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate memory for the image and pixel buffer.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (sample_format == SAMPLEFORMAT_UINT)
status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_INT)
status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_IEEEFP)
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
{
TIFFClose(tiff);
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
status=MagickTrue;
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
quantum_info->min_is_white=MagickFalse;
break;
}
case PHOTOMETRIC_MINISWHITE:
{
quantum_info->min_is_white=MagickTrue;
break;
}
default:
break;
}
tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,
&sample_info);
if (tiff_status == 1)
{
(void) SetImageProperty(image,"tiff:alpha","unspecified");
if (extra_samples == 0)
{
if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))
image->matte=MagickTrue;
}
else
for (i=0; i < extra_samples; i++)
{
image->matte=MagickTrue;
if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)
{
SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
(void) SetImageProperty(image,"tiff:alpha","associated");
}
else
if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)
(void) SetImageProperty(image,"tiff:alpha","unassociated");
}
}
method=ReadGenericMethod;
if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)
{
char
value[MaxTextExtent];
method=ReadStripMethod;
(void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int)
rows_per_strip);
(void) SetImageProperty(image,"tiff:rows-per-strip",value);
}
if ((samples_per_pixel >= 3) && (interlace == PLANARCONFIG_CONTIG))
method=ReadRGBAMethod;
if ((samples_per_pixel >= 4) && (interlace == PLANARCONFIG_SEPARATE))
method=ReadCMYKAMethod;
if ((photometric != PHOTOMETRIC_RGB) &&
(photometric != PHOTOMETRIC_CIELAB) &&
(photometric != PHOTOMETRIC_SEPARATED))
method=ReadGenericMethod;
if (image->storage_class == PseudoClass)
method=ReadSingleSampleMethod;
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
method=ReadSingleSampleMethod;
if ((photometric != PHOTOMETRIC_SEPARATED) &&
(interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
method=ReadGenericMethod;
if (image->compression == JPEGCompression)
method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,
samples_per_pixel);
if (compress_tag == COMPRESSION_JBIG)
method=ReadStripMethod;
if (TIFFIsTiled(tiff) != MagickFalse)
method=ReadTileMethod;
quantum_info->endian=LSBEndian;
quantum_type=RGBQuantum;
tiff_pixels=(unsigned char *) AcquireMagickMemory(TIFFScanlineSize(tiff)+
sizeof(uint32));
if (tiff_pixels == (unsigned char *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
switch (method)
{
case ReadSingleSampleMethod:
{
/*
Convert TIFF image to PseudoClass MIFF image.
*/
quantum_type=IndexQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
if (image->matte != MagickFalse)
{
if (image->storage_class != PseudoClass)
{
quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
GrayAlphaQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
}
else
{
quantum_type=IndexAlphaQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
}
}
else
if (image->storage_class != PseudoClass)
{
quantum_type=GrayQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
}
status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log(
bits_per_sample)/log(2))));
if (status == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register PixelPacket
*magick_restrict q;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,tiff_pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadRGBAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
{
quantum_type=RGBAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
}
if (image->colorspace == CMYKColorspace)
{
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
quantum_type=CMYKQuantum;
if (image->matte != MagickFalse)
{
quantum_type=CMYKAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);
}
}
status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
if (status == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register PixelPacket
*magick_restrict q;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,tiff_pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadCMYKAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
for (i=0; i < (ssize_t) samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
int
status;
status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)
tiff_pixels);
if (status == -1)
break;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
if (image->colorspace != CMYKColorspace)
switch (i)
{
case 0: quantum_type=RedQuantum; break;
case 1: quantum_type=GreenQuantum; break;
case 2: quantum_type=BlueQuantum; break;
case 3: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
else
switch (i)
{
case 0: quantum_type=CyanQuantum; break;
case 1: quantum_type=MagentaQuantum; break;
case 2: quantum_type=YellowQuantum; break;
case 3: quantum_type=BlackQuantum; break;
case 4: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,tiff_pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadYCCKMethod:
{
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register IndexPacket
*indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
unsigned char
*p;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
p=tiff_pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+
(1.402*(double) *(p+2))-179.456)));
SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p-
(0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+
135.45984)));
SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+
(1.772*(double) *(p+1))-226.816)));
SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3)));
q++;
p+=4;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadStripMethod:
{
register uint32
*p;
/*
Convert stripped TIFF image to DirectClass MIFF image.
*/
i=0;
p=(uint32 *) NULL;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
if (i == 0)
{
if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) tiff_pixels) == 0)
break;
i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
image->rows-y);
}
i--;
p=((uint32 *) tiff_pixels)+image->columns*i;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
(TIFFGetR(*p))));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
(TIFFGetG(*p))));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
(TIFFGetB(*p))));
if (image->matte != MagickFalse)
SetPixelOpacity(q,ScaleCharToQuantum((unsigned char)
(TIFFGetA(*p))));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadTileMethod:
{
register uint32
*p;
uint32
*tile_pixels,
columns,
rows;
/*
Convert tiled TIFF image to DirectClass MIFF image.
*/
if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||
(TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))
{
TIFFClose(tiff);
ThrowReaderException(CoderError,"ImageIsNotTiled");
}
(void) SetImageStorageClass(image,DirectClass);
number_pixels=(MagickSizeType) columns*rows;
if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows*
sizeof(*tile_pixels));
if (tile_pixels == (uint32 *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (y=0; y < (ssize_t) image->rows; y+=rows)
{
PixelPacket
*tile;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
size_t
columns_remaining,
rows_remaining;
rows_remaining=image->rows-y;
if ((ssize_t) (y+rows) < (ssize_t) image->rows)
rows_remaining=rows;
tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
exception);
if (tile == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x+=columns)
{
size_t
column,
row;
if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
break;
columns_remaining=image->columns-x;
if ((ssize_t) (x+columns) < (ssize_t) image->columns)
columns_remaining=columns;
p=tile_pixels+(rows-rows_remaining)*columns;
q=tile+(image->columns*(rows_remaining-1)+x);
for (row=rows_remaining; row > 0; row--)
{
if (image->matte != MagickFalse)
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)));
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
TIFFGetA(*p)));
q++;
p++;
}
else
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)));
q++;
p++;
}
p+=columns-columns_remaining;
q-=(image->columns+columns_remaining);
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);
break;
}
case ReadGenericMethod:
default:
{
MemoryInfo
*pixel_info;
register uint32
*p;
uint32
*pixels;
/*
Convert TIFF image to DirectClass MIFF image.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);
(void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)
image->rows,(uint32 *) pixels,0);
/*
Convert image to DirectClass pixel packets.
*/
p=pixels+number_pixels-1;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
q+=image->columns-1;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)));
p--;
q--;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
break;
}
}
tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels);
SetQuantumImageType(image,quantum_type);
next_tiff_frame:
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (photometric == PHOTOMETRIC_CIELAB)
DecodeLabImage(image,exception);
if ((photometric == PHOTOMETRIC_LOGL) ||
(photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
{
image->type=GrayscaleType;
if (bits_per_sample == 1)
image->type=BilevelType;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,image->scene-1,
image->scene);
if (status == MagickFalse)
break;
}
} while (status != MagickFalse);
TIFFClose(tiff);
TIFFReadPhotoshopLayers(image,image_info,exception);
if (image_info->number_scenes != 0)
{
if (image_info->scene >= GetImageListLength(image))
{
/* Subimage was not found in the Photoshop layer */
image = DestroyImageList(image);
return((Image *)NULL);
}
}
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterTIFFImage() adds properties for the TIFF 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 RegisterTIFFImage method is:
%
% size_t RegisterTIFFImage(void)
%
*/
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
static TIFFExtendProc
tag_extender = (TIFFExtendProc) NULL;
static void TIFFIgnoreTags(TIFF *tiff)
{
char
*q;
const char
*p,
*tags;
Image
*image;
register ssize_t
i;
size_t
count;
TIFFFieldInfo
*ignore;
if (TIFFGetReadProc(tiff) != TIFFReadBlob)
return;
image=(Image *)TIFFClientdata(tiff);
tags=GetImageArtifact(image,"tiff:ignore-tags");
if (tags == (const char *) NULL)
return;
count=0;
p=tags;
while (*p != '\0')
{
while ((isspace((int) ((unsigned char) *p)) != 0))
p++;
(void) strtol(p,&q,10);
if (p == q)
return;
p=q;
count++;
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
}
if (count == 0)
return;
i=0;
p=tags;
ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore));
/* This also sets field_bit to 0 (FIELD_IGNORE) */
ResetMagickMemory(ignore,0,count*sizeof(*ignore));
while (*p != '\0')
{
while ((isspace((int) ((unsigned char) *p)) != 0))
p++;
ignore[i].field_tag=(ttag_t) strtol(p,&q,10);
p=q;
i++;
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
}
(void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count);
ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore);
}
static void TIFFTagExtender(TIFF *tiff)
{
static const TIFFFieldInfo
TIFFExtensions[] =
{
{ 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
(char *) "PhotoshopLayerData" },
{ 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
(char *) "Microscope" }
};
TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/
sizeof(*TIFFExtensions));
if (tag_extender != (TIFFExtendProc) NULL)
(*tag_extender)(tiff);
TIFFIgnoreTags(tiff);
}
#endif
ModuleExport size_t RegisterTIFFImage(void)
{
#define TIFFDescription "Tagged Image File Format"
char
version[MaxTextExtent];
MagickInfo
*entry;
if (tiff_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&tiff_semaphore);
LockSemaphoreInfo(tiff_semaphore);
if (instantiate_key == MagickFalse)
{
if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
error_handler=TIFFSetErrorHandler(TIFFErrors);
warning_handler=TIFFSetWarningHandler(TIFFWarnings);
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
if (tag_extender == (TIFFExtendProc) NULL)
tag_extender=TIFFSetTagExtender(TIFFTagExtender);
#endif
instantiate_key=MagickTrue;
}
UnlockSemaphoreInfo(tiff_semaphore);
*version='\0';
#if defined(TIFF_VERSION)
(void) FormatLocaleString(version,MaxTextExtent,"%d",TIFF_VERSION);
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
{
const char
*p;
register ssize_t
i;
p=TIFFGetVersion();
for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\n'); i++)
version[i]=(*p++);
version[i]='\0';
}
#endif
entry=SetMagickInfo("GROUP4");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadGROUP4Image;
entry->encoder=(EncodeImageHandler *) WriteGROUP4Image;
#endif
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->adjoin=MagickFalse;
entry->format_type=ImplicitFormatType;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Raw CCITT Group4");
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PTIF");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WritePTIFImage;
#endif
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Pyramid encoded TIFF");
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TIF");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->stealth=MagickTrue;
entry->description=ConstantString(TIFFDescription);
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TIFF");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->magick=(IsImageFormatHandler *) IsTIFF;
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString(TIFFDescription);
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TIFF64");
#if defined(TIFF_VERSION_BIG)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->adjoin=MagickFalse;
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Tagged Image File Format (64-bit)");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterTIFFImage() removes format registrations made by the TIFF module
% from the list of supported formats.
%
% The format of the UnregisterTIFFImage method is:
%
% UnregisterTIFFImage(void)
%
*/
ModuleExport void UnregisterTIFFImage(void)
{
(void) UnregisterMagickInfo("TIFF64");
(void) UnregisterMagickInfo("TIFF");
(void) UnregisterMagickInfo("TIF");
(void) UnregisterMagickInfo("PTIF");
if (tiff_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&tiff_semaphore);
LockSemaphoreInfo(tiff_semaphore);
if (instantiate_key != MagickFalse)
{
if (DeleteMagickThreadKey(tiff_exception) == MagickFalse)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
if (tag_extender == (TIFFExtendProc) NULL)
(void) TIFFSetTagExtender(tag_extender);
#endif
(void) TIFFSetWarningHandler(warning_handler);
(void) TIFFSetErrorHandler(error_handler);
instantiate_key=MagickFalse;
}
UnlockSemaphoreInfo(tiff_semaphore);
DestroySemaphoreInfo(&tiff_semaphore);
}
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e G R O U P 4 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format.
%
% The format of the WriteGROUP4Image method is:
%
% MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
Image *image)
{
char
filename[MaxTextExtent];
FILE
*file;
Image
*huffman_image;
ImageInfo
*write_info;
int
unique_file;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count;
TIFF
*tiff;
toff_t
*byte_count,
strip_size;
unsigned char
*buffer;
/*
Write image as CCITT Group4 TIFF image to a temporary file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
huffman_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (huffman_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
huffman_image->endian=MSBEndian;
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
ThrowFileException(&image->exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
return(MagickFalse);
}
(void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s",
filename);
(void) SetImageType(huffman_image,BilevelType);
write_info=CloneImageInfo((ImageInfo *) NULL);
SetImageInfoFile(write_info,file);
(void) SetImageDepth(image,1);
(void) SetImageType(image,BilevelType);
write_info->compression=Group4Compression;
write_info->type=BilevelType;
(void) SetImageOption(write_info,"quantum:polarity","min-is-white");
status=WriteTIFFImage(write_info,huffman_image);
(void) fflush(file);
write_info=DestroyImageInfo(write_info);
if (status == MagickFalse)
{
InheritException(&image->exception,&huffman_image->exception);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
return(MagickFalse);
}
tiff=TIFFOpen(filename,"rb");
if (tiff == (TIFF *) NULL)
{
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile",
image_info->filename);
return(MagickFalse);
}
/*
Allocate raw strip buffer.
*/
if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1)
{
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
return(MagickFalse);
}
strip_size=byte_count[0];
for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
if (byte_count[i] > strip_size)
strip_size=byte_count[i];
buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
{
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image_info->filename);
}
/*
Compress runlength encoded to 2D Huffman pixels.
*/
for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
{
count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size);
if (WriteBlob(image,(size_t) count,buffer) != count)
status=MagickFalse;
}
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
(void) CloseBlob(image);
return(status);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P T I F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file
% format.
%
% The format of the WritePTIFImage method is:
%
% MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
Image *image)
{
ExceptionInfo
*exception;
Image
*images,
*next,
*pyramid_image;
ImageInfo
*write_info;
MagickBooleanType
status;
PointInfo
resolution;
size_t
columns,
rows;
/*
Create pyramid-encoded TIFF image.
*/
exception=(&image->exception);
images=NewImageList();
for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
{
Image
*clone_image;
clone_image=CloneImage(next,0,0,MagickFalse,exception);
if (clone_image == (Image *) NULL)
break;
clone_image->previous=NewImageList();
clone_image->next=NewImageList();
(void) SetImageProperty(clone_image,"tiff:subfiletype","none");
AppendImageToList(&images,clone_image);
columns=next->columns;
rows=next->rows;
resolution.x=next->x_resolution;
resolution.y=next->y_resolution;
while ((columns > 64) && (rows > 64))
{
columns/=2;
rows/=2;
resolution.x/=2.0;
resolution.y/=2.0;
pyramid_image=ResizeImage(next,columns,rows,image->filter,image->blur,
exception);
if (pyramid_image == (Image *) NULL)
break;
pyramid_image->x_resolution=resolution.x;
pyramid_image->y_resolution=resolution.y;
(void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE");
AppendImageToList(&images,pyramid_image);
}
}
/*
Write pyramid-encoded TIFF image.
*/
write_info=CloneImageInfo(image_info);
write_info->adjoin=MagickTrue;
status=WriteTIFFImage(write_info,GetFirstImageInList(images));
images=DestroyImageList(images);
write_info=DestroyImageInfo(write_info);
return(status);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% W r i t e T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteTIFFImage() writes an image in the Tagged image file format.
%
% The format of the WriteTIFFImage method is:
%
% MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
*/
typedef struct _TIFFInfo
{
RectangleInfo
tile_geometry;
unsigned char
*scanline,
*scanlines,
*pixels;
} TIFFInfo;
static void DestroyTIFFInfo(TIFFInfo *tiff_info)
{
assert(tiff_info != (TIFFInfo *) NULL);
if (tiff_info->scanlines != (unsigned char *) NULL)
tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory(
tiff_info->scanlines);
if (tiff_info->pixels != (unsigned char *) NULL)
tiff_info->pixels=(unsigned char *) RelinquishMagickMemory(
tiff_info->pixels);
}
static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
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,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
a,
b;
a=QuantumScale*GetPixela(q)-0.5;
if (a < 0.0)
a+=1.0;
b=QuantumScale*GetPixelb(q)-0.5;
if (b < 0.0)
b+=1.0;
SetPixela(q,QuantumRange*a);
SetPixelb(q,QuantumRange*b);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,TIFF *tiff,
TIFFInfo *tiff_info)
{
const char
*option;
MagickStatusType
flags;
uint32
tile_columns,
tile_rows;
assert(tiff_info != (TIFFInfo *) NULL);
(void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info));
option=GetImageOption(image_info,"tiff:tile-geometry");
if (option == (const char *) NULL)
{
uint32
rows_per_strip;
option=GetImageOption(image_info,"tiff:rows-per-strip");
if (option != (const char *) NULL)
rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
else
if (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&rows_per_strip) == 0)
rows_per_strip=0; /* use default */
rows_per_strip=TIFFDefaultStripSize(tiff,rows_per_strip);
(void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
return(MagickTrue);
}
flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry);
if ((flags & HeightValue) == 0)
tiff_info->tile_geometry.height=tiff_info->tile_geometry.width;
tile_columns=(uint32) tiff_info->tile_geometry.width;
tile_rows=(uint32) tiff_info->tile_geometry.height;
TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows);
(void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns);
(void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows);
tiff_info->tile_geometry.width=tile_columns;
tiff_info->tile_geometry.height=tile_rows;
tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t)
tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines));
tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t)
tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines));
if ((tiff_info->scanlines == (unsigned char *) NULL) ||
(tiff_info->pixels == (unsigned char *) NULL))
{
DestroyTIFFInfo(tiff_info);
return(MagickFalse);
}
return(MagickTrue);
}
static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row,
tsample_t sample,Image *image)
{
int32
status;
register ssize_t
i;
register unsigned char
*p,
*q;
size_t
number_tiles,
tile_width;
ssize_t
bytes_per_pixel,
j,
k,
l;
if (TIFFIsTiled(tiff) == 0)
return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample));
/*
Fill scanlines to tile height.
*/
i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff);
(void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline,
(size_t) TIFFScanlineSize(tiff));
if (((size_t) (row % tiff_info->tile_geometry.height) !=
(tiff_info->tile_geometry.height-1)) &&
(row != (ssize_t) (image->rows-1)))
return(0);
/*
Write tile to TIFF image.
*/
status=0;
bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (tiff_info->tile_geometry.height*
tiff_info->tile_geometry.width);
number_tiles=(image->columns+tiff_info->tile_geometry.width)/
tiff_info->tile_geometry.width;
for (i=0; i < (ssize_t) number_tiles; i++)
{
tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i*
tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width;
for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++)
for (k=0; k < (ssize_t) tile_width; k++)
{
if (bytes_per_pixel == 0)
{
p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
tiff_info->tile_geometry.width+k)/8);
q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8);
*q++=(*p++);
continue;
}
p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
tiff_info->tile_geometry.width+k)*bytes_per_pixel);
q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel);
for (l=0; l < bytes_per_pixel; l++)
*q++=(*p++);
}
if ((i*tiff_info->tile_geometry.width) != image->columns)
status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i*
tiff_info->tile_geometry.width),(uint32) ((row/
tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0,
sample);
if (status < 0)
break;
}
return(status);
}
static void TIFFSetProfiles(TIFF *tiff,Image *image)
{
const char
*name;
const StringInfo
*profile;
if (image->profiles == (void *) NULL)
return;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (GetStringInfoLength(profile) == 0)
{
name=GetNextImageProfile(image);
continue;
}
#if defined(TIFFTAG_XMLPACKET)
if (LocaleCompare(name,"xmp") == 0)
(void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength(
profile),GetStringInfoDatum(profile));
#endif
#if defined(TIFFTAG_ICCPROFILE)
if (LocaleCompare(name,"icc") == 0)
(void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength(
profile),GetStringInfoDatum(profile));
#endif
if (LocaleCompare(name,"iptc") == 0)
{
size_t
length;
StringInfo
*iptc_profile;
iptc_profile=CloneStringInfo(profile);
length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) &
0x03);
SetStringInfoLength(iptc_profile,length);
if (TIFFIsByteSwapped(tiff))
TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile),
(unsigned long) (length/4));
(void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32)
GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile));
iptc_profile=DestroyStringInfo(iptc_profile);
}
#if defined(TIFFTAG_PHOTOSHOP)
if (LocaleCompare(name,"8bim") == 0)
(void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32)
GetStringInfoLength(profile),GetStringInfoDatum(profile));
#endif
if (LocaleCompare(name,"tiff:37724") == 0)
(void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile),
GetStringInfoDatum(profile));
if (LocaleCompare(name,"tiff:34118") == 0)
(void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile),
GetStringInfoDatum(profile));
name=GetNextImageProfile(image);
}
}
static void TIFFSetProperties(TIFF *tiff,const ImageInfo *image_info,
Image *image)
{
const char
*value;
value=GetImageArtifact(image,"tiff:document");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value);
value=GetImageArtifact(image,"tiff:hostcomputer");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
value=GetImageArtifact(image,"tiff:artist");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_ARTIST,value);
value=GetImageArtifact(image,"tiff:timestamp");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_DATETIME,value);
value=GetImageArtifact(image,"tiff:make");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_MAKE,value);
value=GetImageArtifact(image,"tiff:model");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
value=GetImageArtifact(image,"tiff:software");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
value=GetImageArtifact(image,"tiff:copyright");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value);
value=GetImageArtifact(image,"kodak-33423");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,33423,value);
value=GetImageArtifact(image,"kodak-36867");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,36867,value);
value=GetImageProperty(image,"label");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
value=GetImageArtifact(image,"tiff:subfiletype");
if (value != (const char *) NULL)
{
if (LocaleCompare(value,"REDUCEDIMAGE") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
else
if (LocaleCompare(value,"PAGE") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
else
if (LocaleCompare(value,"MASK") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK);
}
else
{
uint16
page,
pages;
page=(uint16) image->scene;
pages=(uint16) GetImageListLength(image);
if ((image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
}
static void TIFFSetEXIFProperties(TIFF *tiff,Image *image)
{
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
const char
*value;
register ssize_t
i;
uint32
offset;
/*
Write EXIF properties.
*/
offset=0;
(void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset);
for (i=0; exif_info[i].tag != 0; i++)
{
value=GetImageProperty(image,exif_info[i].property);
if (value == (const char *) NULL)
continue;
switch (exif_info[i].type)
{
case TIFF_ASCII:
{
(void) TIFFSetField(tiff,exif_info[i].tag,value);
break;
}
case TIFF_SHORT:
{
uint16
field;
field=(uint16) StringToLong(value);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
case TIFF_LONG:
{
uint16
field;
field=(uint16) StringToLong(value);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
case TIFF_RATIONAL:
case TIFF_SRATIONAL:
{
float
field;
field=StringToDouble(value,(char **) NULL);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
default:
break;
}
}
/* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */
#else
(void) tiff;
(void) image;
#endif
}
static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
Image *image)
{
const char
*mode,
*option;
CompressionType
compression;
EndianType
endian_type;
MagickBooleanType
debug,
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
ssize_t
y;
TIFF
*tiff;
TIFFInfo
tiff_info;
uint16
bits_per_sample,
compress_tag,
endian,
photometric;
unsigned char
*pixels;
/*
Open TIFF file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) SetMagickThreadValue(tiff_exception,&image->exception);
endian_type=UndefinedEndian;
option=GetImageOption(image_info,"tiff:endian");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian_type=MSBEndian;
if (LocaleNCompare(option,"lsb",3) == 0)
endian_type=LSBEndian;;
}
switch (endian_type)
{
case LSBEndian: mode="wl"; break;
case MSBEndian: mode="wb"; break;
default: mode="w"; break;
}
#if defined(TIFF_VERSION_BIG)
if (LocaleCompare(image_info->magick,"TIFF64") == 0)
switch (endian_type)
{
case LSBEndian: mode="wl8"; break;
case MSBEndian: mode="wb8"; break;
default: mode="w8"; break;
}
#endif
tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
return(MagickFalse);
scene=0;
debug=IsEventLogging();
(void) debug;
do
{
/*
Initialize TIFF fields.
*/
if ((image_info->type != UndefinedType) &&
(image_info->type != OptimizeType))
(void) SetImageType(image,image_info->type);
compression=UndefinedCompression;
if (image->compression != JPEGCompression)
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
(void) SetImageType(image,BilevelType);
(void) SetImageDepth(image,1);
break;
}
case JPEGCompression:
{
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
break;
}
default:
break;
}
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
(quantum_info->format == UndefinedQuantumFormat) &&
(IsHighDynamicRangeImage(image,&image->exception) != MagickFalse))
{
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
(GetPreviousImageInList(image) != (Image *) NULL))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
if ((image->columns != (uint32) image->columns) ||
(image->rows != (uint32) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
(void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
(void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
switch (compression)
{
case FaxCompression:
{
compress_tag=COMPRESSION_CCITTFAX3;
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
case Group4Compression:
{
compress_tag=COMPRESSION_CCITTFAX4;
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
#if defined(COMPRESSION_JBIG)
case JBIG1Compression:
{
compress_tag=COMPRESSION_JBIG;
break;
}
#endif
case JPEGCompression:
{
compress_tag=COMPRESSION_JPEG;
break;
}
#if defined(COMPRESSION_LZMA)
case LZMACompression:
{
compress_tag=COMPRESSION_LZMA;
break;
}
#endif
case LZWCompression:
{
compress_tag=COMPRESSION_LZW;
break;
}
case RLECompression:
{
compress_tag=COMPRESSION_PACKBITS;
break;
}
case ZipCompression:
{
compress_tag=COMPRESSION_ADOBE_DEFLATE;
break;
}
case NoCompression:
default:
{
compress_tag=COMPRESSION_NONE;
break;
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
}
#else
switch (compress_tag)
{
#if defined(CCITT_SUPPORT)
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
#endif
#if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
case COMPRESSION_JPEG:
#endif
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
#endif
#if defined(LZW_SUPPORT)
case COMPRESSION_LZW:
#endif
#if defined(PACKBITS_SUPPORT)
case COMPRESSION_PACKBITS:
#endif
#if defined(ZIP_SUPPORT)
case COMPRESSION_ADOBE_DEFLATE:
#endif
case COMPRESSION_NONE:
break;
default:
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
break;
}
}
#endif
if (image->colorspace == CMYKColorspace)
{
photometric=PHOTOMETRIC_SEPARATED;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
(void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
}
else
{
/*
Full color TIFF raster.
*/
if (image->colorspace == LabColorspace)
{
photometric=PHOTOMETRIC_CIELAB;
EncodeLabImage(image,&image->exception);
}
else
if (image->colorspace == YCbCrColorspace)
{
photometric=PHOTOMETRIC_YCBCR;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
}
else
photometric=PHOTOMETRIC_RGB;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
if ((image_info->type != TrueColorType) &&
(image_info->type != TrueColorMatteType))
{
if ((image_info->type != PaletteType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
photometric=(uint16) (quantum_info->min_is_white !=
MagickFalse ? PHOTOMETRIC_MINISWHITE :
PHOTOMETRIC_MINISBLACK);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
if ((image->depth == 1) && (image->matte == MagickFalse))
SetImageMonochrome(image,&image->exception);
}
else
if (image->storage_class == PseudoClass)
{
size_t
depth;
/*
Colormapped TIFF raster.
*/
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
photometric=PHOTOMETRIC_PALETTE;
depth=1;
while ((GetQuantumRange(depth)+1) < image->colors)
depth<<=1;
status=SetQuantumDepth(image,quantum_info,depth);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
if ((compress_tag == COMPRESSION_CCITTFAX3) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
else
if ((compress_tag == COMPRESSION_CCITTFAX4) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
option=GetImageOption(image_info,"tiff:fill-order");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian=FILLORDER_MSB2LSB;
if (LocaleNCompare(option,"lsb",3) == 0)
endian=FILLORDER_LSB2MSB;
}
(void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
(void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
(void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
if (image->matte != MagickFalse)
{
uint16
extra_samples,
sample_info[1],
samples_per_pixel;
/*
TIFF has a matte channel.
*/
extra_samples=1;
sample_info[0]=EXTRASAMPLE_UNASSALPHA;
option=GetImageOption(image_info,"tiff:alpha");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"associated") == 0)
sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
else
if (LocaleCompare(option,"unspecified") == 0)
sample_info[0]=EXTRASAMPLE_UNSPECIFIED;
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
&samples_per_pixel);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
(void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
&sample_info);
if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
}
(void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
switch (quantum_info->format)
{
case FloatingPointQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
(void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
(void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
break;
}
case SignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
break;
}
case UnsignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
break;
}
default:
break;
}
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
if (photometric == PHOTOMETRIC_RGB)
if ((image_info->interlace == PlaneInterlace) ||
(image_info->interlace == PartitionInterlace))
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
switch (compress_tag)
{
case COMPRESSION_JPEG:
{
#if defined(JPEG_SUPPORT)
if (image_info->quality != UndefinedCompressionQuality)
(void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
{
const char
*value;
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
if (image->colorspace == YCbCrColorspace)
{
const char
*sampling_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
sampling_factor=(const char *) NULL;
value=GetImageProperty(image,"jpeg:sampling-factor");
if (value != (char *) NULL)
{
sampling_factor=value;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input sampling-factors=%s",sampling_factor);
}
if (image_info->sampling_factor != (char *) NULL)
sampling_factor=image_info->sampling_factor;
if (sampling_factor != (const char *) NULL)
{
flags=ParseGeometry(sampling_factor,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
geometry_info.rho,(uint16) geometry_info.sigma);
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (bits_per_sample == 12)
(void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
#endif
break;
}
case COMPRESSION_ADOBE_DEFLATE:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
(void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
case COMPRESSION_CCITTFAX3:
{
/*
Byte-aligned EOL.
*/
(void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
break;
}
case COMPRESSION_CCITTFAX4:
break;
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
{
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
(void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
#endif
case COMPRESSION_LZW:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
break;
}
default:
break;
}
if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))
{
unsigned short
units;
/*
Set image resolution.
*/
units=RESUNIT_NONE;
if (image->units == PixelsPerInchResolution)
units=RESUNIT_INCH;
if (image->units == PixelsPerCentimeterResolution)
units=RESUNIT_CENTIMETER;
(void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
(void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution);
(void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution);
if ((image->page.x < 0) || (image->page.y < 0))
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"TIFF: negative image positions unsupported","%s",
image->filename);
if ((image->page.x > 0) && (image->x_resolution > 0.0))
{
/*
Set horizontal image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
image->x_resolution);
}
if ((image->page.y > 0) && (image->y_resolution > 0.0))
{
/*
Set vertical image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
image->y_resolution);
}
}
if (image->chromaticity.white_point.x != 0.0)
{
float
chromaticity[6];
/*
Set image chromaticity.
*/
chromaticity[0]=(float) image->chromaticity.red_primary.x;
chromaticity[1]=(float) image->chromaticity.red_primary.y;
chromaticity[2]=(float) image->chromaticity.green_primary.x;
chromaticity[3]=(float) image->chromaticity.green_primary.y;
chromaticity[4]=(float) image->chromaticity.blue_primary.x;
chromaticity[5]=(float) image->chromaticity.blue_primary.y;
(void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
chromaticity[0]=(float) image->chromaticity.white_point.x;
chromaticity[1]=(float) image->chromaticity.white_point.y;
(void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
}
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1))
{
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
if (image->scene != 0)
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
GetImageListLength(image));
}
if (image->orientation != UndefinedOrientation)
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
(void) TIFFSetProfiles(tiff,image);
{
uint16
page,
pages;
page=(uint16) scene;
pages=(uint16) GetImageListLength(image);
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
(void) TIFFSetProperties(tiff,image_info,image);
DisableMSCWarning(4127)
if (0)
RestoreMSCWarning
(void) TIFFSetEXIFProperties(tiff,image);
/*
Write image scanlines.
*/
if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->endian=LSBEndian;
pixels=GetQuantumPixels(quantum_info);
tiff_info.scanline=GetQuantumPixels(quantum_info);
switch (photometric)
{
case PHOTOMETRIC_CIELAB:
case PHOTOMETRIC_YCBCR:
case PHOTOMETRIC_RGB:
{
/*
RGB TIFF image.
*/
switch (image_info->interlace)
{
case NoInterlace:
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
case PartitionInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,100,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,200,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,300,400);
if (status == MagickFalse)
break;
}
if (image->matte != MagickFalse)
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,400,400);
if (status == MagickFalse)
break;
}
break;
}
}
break;
}
case PHOTOMETRIC_SEPARATED:
{
/*
CMYK TIFF image.
*/
quantum_type=CMYKQuantum;
if (image->matte != MagickFalse)
quantum_type=CMYKAQuantum;
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PHOTOMETRIC_PALETTE:
{
uint16
*blue,
*green,
*red;
/*
Colormapped TIFF image.
*/
red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
(blue == (uint16 *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize TIFF colormap.
*/
(void) ResetMagickMemory(red,0,65536*sizeof(*red));
(void) ResetMagickMemory(green,0,65536*sizeof(*green));
(void) ResetMagickMemory(blue,0,65536*sizeof(*blue));
for (i=0; i < (ssize_t) image->colors; i++)
{
red[i]=ScaleQuantumToShort(image->colormap[i].red);
green[i]=ScaleQuantumToShort(image->colormap[i].green);
blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
}
(void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
red=(uint16 *) RelinquishMagickMemory(red);
green=(uint16 *) RelinquishMagickMemory(green);
blue=(uint16 *) RelinquishMagickMemory(blue);
}
default:
{
/*
Convert PseudoClass packets to contiguous grayscale scanlines.
*/
quantum_type=IndexQuantum;
if (image->matte != MagickFalse)
{
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayAlphaQuantum;
else
quantum_type=IndexAlphaQuantum;
}
else
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (image->colorspace == LabColorspace)
DecodeLabImage(image,&image->exception);
DestroyTIFFInfo(&tiff_info);
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
RestoreMSCWarning
TIFFPrintDirectory(tiff,stdout,MagickFalse);
(void) TIFFWriteDirectory(tiff);
image=SyncNextImageInList(image);
if (image == (Image *) NULL)
break;
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
TIFFClose(tiff);
return(MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3104_1 |
crossvul-cpp_data_bad_252_2 | /**
* @file
* Conversion to/from base64 encoding
*
* @authors
* Copyright (C) 1993,1995 Carl Harris
* Copyright (C) 1997 Eric S. Raymond
* Copyright (C) 1999 Brendan Cully <brendan@kublai.com>
*
* @copyright
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @page base64 Conversion to/from base64 encoding
*
* Convert between binary data and base64 text, according to RFC2045.
*
* @note RFC3548 obsoletes RFC2045.
* @note RFC4648 obsoletes RFC3548.
*/
#include "config.h"
#include "base64.h"
#define BAD -1
/**
* B64Chars - Characters of the Base64 encoding
*/
static const char B64Chars[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', '+', '/',
};
// clang-format off
/**
* Index64 - Lookup table for Base64 encoding characters
*
* @note This is very similar to the table in imap/utf7.c
*
* Encoding chars:
* * utf7 A-Za-z0-9+,
* * mime A-Za-z0-9+/
*/
const int Index64[128] = {
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
-1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
};
// clang-format on
/**
* mutt_b64_encode - Convert raw bytes to null-terminated base64 string
* @param out Output buffer for the base64 encoded string
* @param cin Input buffer for the raw bytes
* @param len Length of the input buffer
* @param olen Length of the output buffer
* @retval num Length of the string written to the output buffer
*
* This function performs base64 encoding. The resulting string is guaranteed
* to be null-terminated. The number of characters up to the terminating
* null-byte is returned (equivalent to calling strlen() on the output buffer
* after this function returns).
*/
size_t mutt_b64_encode(char *out, const char *cin, size_t len, size_t olen)
{
unsigned char *begin = (unsigned char *) out;
const unsigned char *in = (const unsigned char *) cin;
while ((len >= 3) && (olen > 10))
{
*out++ = B64Chars[in[0] >> 2];
*out++ = B64Chars[((in[0] << 4) & 0x30) | (in[1] >> 4)];
*out++ = B64Chars[((in[1] << 2) & 0x3c) | (in[2] >> 6)];
*out++ = B64Chars[in[2] & 0x3f];
olen -= 4;
len -= 3;
in += 3;
}
/* clean up remainder */
if ((len > 0) && (olen > 4))
{
unsigned char fragment;
*out++ = B64Chars[in[0] >> 2];
fragment = (in[0] << 4) & 0x30;
if (len > 1)
fragment |= in[1] >> 4;
*out++ = B64Chars[fragment];
*out++ = (len < 2) ? '=' : B64Chars[(in[1] << 2) & 0x3c];
*out++ = '=';
}
*out = '\0';
return (out - (char *) begin);
}
/**
* mutt_b64_decode - Convert null-terminated base64 string to raw bytes
* @param out Output buffer for the raw bytes
* @param in Input buffer for the null-terminated base64-encoded string
* @retval num Success, bytes written
* @retval -1 Error
*
* This function performs base64 decoding. The resulting buffer is NOT
* null-terminated. If the input buffer contains invalid base64 characters,
* this function returns -1.
*/
int mutt_b64_decode(char *out, const char *in)
{
int len = 0;
unsigned char digit4;
do
{
const unsigned char digit1 = in[0];
if ((digit1 > 127) || (base64val(digit1) == BAD))
return -1;
const unsigned char digit2 = in[1];
if ((digit2 > 127) || (base64val(digit2) == BAD))
return -1;
const unsigned char digit3 = in[2];
if ((digit3 > 127) || ((digit3 != '=') && (base64val(digit3) == BAD)))
return -1;
digit4 = in[3];
if ((digit4 > 127) || ((digit4 != '=') && (base64val(digit4) == BAD)))
return -1;
in += 4;
/* digits are already sanity-checked */
*out++ = (base64val(digit1) << 2) | (base64val(digit2) >> 4);
len++;
if (digit3 != '=')
{
*out++ = ((base64val(digit2) << 4) & 0xf0) | (base64val(digit3) >> 2);
len++;
if (digit4 != '=')
{
*out++ = ((base64val(digit3) << 6) & 0xc0) | base64val(digit4);
len++;
}
}
} while (*in && digit4 != '=');
return len;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_252_2 |
crossvul-cpp_data_bad_83_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/mm.h>
#include <linux/sched/user.h>
#include <linux/sched/debug.h>
#include <linux/sched/task.h>
#include <linux/sched/task_stack.h>
#include <linux/sched/cputime.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>
#include <linux/cn_proc.h>
#include <linux/compiler.h>
#include <linux/posix-timers.h>
#define CREATE_TRACE_POINTS
#include <trace/events/signal.h>
#include <asm/param.h>
#include <linux/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;
pr_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 long 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;
smp_mb(); /* advised by wake_up_bit() */
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 long 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)) {
signal_set_stop_flags(sig, 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 this kthread.
*/
void flush_signals(struct task_struct *t)
{
unsigned long flags;
spin_lock_irqsave(&t->sighand->siglock, flags);
clear_tsk_thread_flag(t, TIF_SIGPENDING);
flush_sigqueue(&t->pending);
flush_sigqueue(&t->signal->shared_pending);
spin_unlock_irqrestore(&t->sighand->siglock, flags);
}
#ifdef CONFIG_POSIX_TIMERS
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);
}
#endif
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;
}
static void collect_signal(int sig, struct sigpending *list, siginfo_t *info,
bool *resched_timer)
{
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);
*resched_timer =
(first->flags & SIGQUEUE_PREALLOC) &&
(info->si_code == SI_TIMER) &&
(info->si_sys_private);
__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, bool *resched_timer)
{
int sig = next_signal(pending, mask);
if (sig)
collect_signal(sig, pending, info, resched_timer);
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)
{
bool resched_timer = false;
int signr;
/* We only dequeue private signals from ourselves, we don't let
* signalfd steal them
*/
signr = __dequeue_signal(&tsk->pending, mask, info, &resched_timer);
if (!signr) {
signr = __dequeue_signal(&tsk->signal->shared_pending,
mask, info, &resched_timer);
#ifdef CONFIG_POSIX_TIMERS
/*
* 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 != 0) {
hrtimer_forward(tmr, tmr->base->get_time(),
tsk->signal->it_real_incr);
hrtimer_restart(tmr);
}
}
#endif
}
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;
}
#ifdef CONFIG_POSIX_TIMERS
if (resched_timer) {
/*
* 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);
posixtimer_rearm(info);
spin_lock(&tsk->sighand->siglock);
}
#endif
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.
*/
static int flush_sigqueue_mask(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;
}
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 bool prepare_signal(int sig, struct task_struct *p, bool force)
{
struct signal_struct *signal = p->signal;
struct task_struct *t;
sigset_t flush;
if (signal->flags & (SIGNAL_GROUP_EXIT | SIGNAL_GROUP_COREDUMP)) {
if (!(signal->flags & SIGNAL_GROUP_EXIT))
return sig == SIGKILL;
/*
* 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.
*/
siginitset(&flush, sigmask(SIGCONT));
flush_sigqueue_mask(&flush, &signal->shared_pending);
for_each_thread(p, t)
flush_sigqueue_mask(&flush, &t->pending);
} else if (sig == SIGCONT) {
unsigned int why;
/*
* Remove all stop signals from all queues, wake all threads.
*/
siginitset(&flush, SIG_KERNEL_STOP_MASK);
flush_sigqueue_mask(&flush, &signal->shared_pending);
for_each_thread(p, t) {
flush_sigqueue_mask(&flush, &t->pending);
task_clear_jobctl_pending(t, JOBCTL_STOP_PENDING);
if (likely(!(t->ptrace & PT_SEIZED)))
wake_up_state(t, __TASK_STOPPED);
else
ptrace_trap_notify(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_set_stop_flags(signal, 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();
pr_info("potentially unexpected fatal signal %d.\n", signr);
#if defined(__i386__) && !defined(__arch_um__)
pr_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;
pr_cont("%02x ", insn);
}
}
pr_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 (;;) {
/*
* Disable interrupts early to avoid deadlocks.
* See rcu_read_unlock() comment header for details.
*/
local_irq_save(*flags);
rcu_read_lock();
sighand = rcu_dereference(tsk->sighand);
if (unlikely(sighand == NULL)) {
rcu_read_unlock();
local_irq_restore(*flags);
break;
}
/*
* This sighand can be already freed and even reused, but
* we rely on SLAB_TYPESAFE_BY_RCU and sighand_ctor() which
* initializes ->siglock: this slab can't go away, it has
* the same object type, ->siglock can't be reinitialized.
*
* We need to ensure that tsk->sighand is still the same
* after we take the lock, we can race with de_thread() or
* __exit_signal(). In the latter case the next iteration
* must see ->sighand == NULL.
*/
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;
for (;;) {
rcu_read_lock();
p = pid_task(pid, PIDTYPE_PID);
if (p)
error = group_send_sig_info(sig, info, p);
rcu_read_unlock();
if (likely(!p || error != -ESRCH))
return error;
/*
* 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.
*/
}
}
static 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 = ¤t->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;
u64 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 = nsec_to_clock_t(utime + tsk->signal->utime);
info.si_stime = nsec_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;
u64 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 = nsec_to_clock_t(utime);
info.si_stime = nsec_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(¤t->sighand->siglock)
__acquires(¤t->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(¤t->sighand->siglock);
arch_ptrace_stop(exit_code, info);
spin_lock_irq(¤t->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(¤t->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(¤t->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(¤t->sighand->siglock);
ptrace_do_notify(SIGTRAP, exit_code, CLD_TRAPPED);
spin_unlock_irq(¤t->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(¤t->sighand->siglock)
{
struct signal_struct *sig = current->signal;
if (!(current->jobctl & JOBCTL_STOP_PENDING)) {
unsigned long 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++;
t = current;
while_each_thread(current, 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(¤t->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)
{
/*
* 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(¤t->blocked, signr)) {
specific_send_sig_info(signr, info, current);
signr = 0;
}
return signr;
}
int get_signal(struct ksignal *ksig)
{
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, ¤t->blocked, &ksig->info);
if (!signr)
break; /* will return 0 */
if (unlikely(current->ptrace) && signr != SIGKILL) {
signr = ptrace_signal(signr, &ksig->info);
if (!signr)
continue;
}
ka = &sighand->action[signr-1];
/* Trace actually delivered signals. */
trace_signal_deliver(signr, &ksig->info, ka);
if (ka->sa.sa_handler == SIG_IGN) /* Do nothing. */
continue;
if (ka->sa.sa_handler != SIG_DFL) {
/* Run the handler. */
ksig->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(ksig->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(ksig->info.si_signo);
proc_coredump_connector(current);
/*
* 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(&ksig->info);
}
/*
* Death signals, no core dump.
*/
do_group_exit(ksig->info.si_signo);
/* NOTREACHED */
}
spin_unlock_irq(&sighand->siglock);
ksig->sig = signr;
return ksig->sig > 0;
}
/**
* signal_delivered -
* @ksig: kernel signal struct
* @stepping: nonzero if debugger single-step or block-step in use
*
* This function should be called when a signal has successfully been
* delivered. It updates the blocked signals accordingly (@ksig->ka.sa.sa_mask
* is always blocked, and the signal itself is blocked unless %SA_NODEFER
* is set in @ksig->ka.sa.sa_flags. Tracing is notified.
*/
static void signal_delivered(struct ksignal *ksig, 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, ¤t->blocked, &ksig->ka.sa.sa_mask);
if (!(ksig->ka.sa.sa_flags & SA_NODEFER))
sigaddset(&blocked, ksig->sig);
set_current_blocked(&blocked);
tracehook_signal_handler(stepping);
}
void signal_setup_done(int failed, struct ksignal *ksig, int stepping)
{
if (failed)
force_sigsegv(ksig->sig, current);
else
signal_delivered(ksig, 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.
*/
cgroup_threadgroup_change_begin(tsk);
if (thread_group_empty(tsk) || signal_group_exit(tsk->signal)) {
tsk->flags |= PF_EXITING;
cgroup_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;
cgroup_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);
/*
* System call entry points.
*/
/**
* sys_restart_syscall - restart a system call
*/
SYSCALL_DEFINE0(restart_syscall)
{
struct restart_block *restart = ¤t->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, ¤t->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;
/*
* In case the signal mask hasn't changed, there is nothing we need
* to do. The current->blocked shouldn't be modified by other task.
*/
if (sigequalsets(&tsk->blocked, newset))
return;
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(¤t->sighand->siglock);
sigorsets(set, ¤t->pending.signal,
¤t->signal->shared_pending.signal);
spin_unlock_irq(¤t->sighand->siglock);
/* Outside the lock because only this thread touches it. */
sigandsets(set, ¤t->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, const 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_signo == SIGBUS &&
(from->si_code == BUS_MCEERR_AR || from->si_code == BUS_MCEERR_AO))
err |= __put_user(from->si_addr_lsb, &to->si_addr_lsb);
#endif
#ifdef SEGV_BNDERR
if (from->si_signo == SIGSEGV && from->si_code == SEGV_BNDERR) {
err |= __put_user(from->si_lower, &to->si_lower);
err |= __put_user(from->si_upper, &to->si_upper);
}
#endif
#ifdef SEGV_PKUERR
if (from->si_signo == SIGSEGV && from->si_code == SEGV_PKUERR)
err |= __put_user(from->si_pkey, &to->si_pkey);
#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
*/
static int do_sigtimedwait(const sigset_t *which, siginfo_t *info,
const struct timespec *ts)
{
ktime_t *to = NULL, timeout = KTIME_MAX;
struct task_struct *tsk = current;
sigset_t mask = *which;
int sig, ret = 0;
if (ts) {
if (!timespec_valid(ts))
return -EINVAL;
timeout = timespec_to_ktime(*ts);
to = &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);
__set_current_state(TASK_INTERRUPTIBLE);
ret = freezable_schedule_hrtimeout_range(to, tsk->timer_slack_ns,
HRTIMER_MODE_REL);
spin_lock_irq(&tsk->sighand->siglock);
__set_task_blocked(tsk, &tsk->real_blocked);
sigemptyset(&tsk->real_blocked);
sig = dequeue_signal(tsk, &mask, info);
}
spin_unlock_irq(&tsk->sighand->siglock);
if (sig)
return sig;
return ret ? -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;
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE4(rt_sigtimedwait, compat_sigset_t __user *, uthese,
struct compat_siginfo __user *, uinfo,
struct compat_timespec __user *, uts, compat_size_t, sigsetsize)
{
compat_sigset_t s32;
sigset_t s;
struct timespec t;
siginfo_t info;
long ret;
if (sigsetsize != sizeof(sigset_t))
return -EINVAL;
if (copy_from_user(&s32, uthese, sizeof(compat_sigset_t)))
return -EFAULT;
sigset_from_compat(&s, &s32);
if (uts) {
if (compat_get_timespec(&t, uts))
return -EFAULT;
}
ret = do_sigtimedwait(&s, &info, uts ? &t : NULL);
if (ret > 0 && uinfo) {
if (copy_siginfo_to_user32(uinfo, &info))
ret = -EFAULT;
}
return ret;
}
#endif
/**
* 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))
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))
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
/*
* For kthreads only, must not be used if cloned with CLONE_SIGHAND
*/
void kernel_sigaction(int sig, __sighandler_t action)
{
spin_lock_irq(¤t->sighand->siglock);
current->sighand->action[sig - 1].sa.sa_handler = action;
if (action == SIG_IGN) {
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, sig);
flush_sigqueue_mask(&mask, ¤t->signal->shared_pending);
flush_sigqueue_mask(&mask, ¤t->pending);
recalc_sigpending();
}
spin_unlock_irq(¤t->sighand->siglock);
}
EXPORT_SYMBOL(kernel_sigaction);
void __weak sigaction_compat_abi(struct k_sigaction *act,
struct k_sigaction *oact)
{
}
int do_sigaction(int sig, struct k_sigaction *act, struct k_sigaction *oact)
{
struct task_struct *p = current, *t;
struct k_sigaction *k;
sigset_t mask;
if (!valid_signal(sig) || sig < 1 || (act && sig_kernel_only(sig)))
return -EINVAL;
k = &p->sighand->action[sig-1];
spin_lock_irq(&p->sighand->siglock);
if (oact)
*oact = *k;
sigaction_compat_abi(act, oact);
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(p, sig), sig)) {
sigemptyset(&mask);
sigaddset(&mask, sig);
flush_sigqueue_mask(&mask, &p->signal->shared_pending);
for_each_thread(p, t)
flush_sigqueue_mask(&mask, &t->pending);
}
}
spin_unlock_irq(&p->sighand->siglock);
return 0;
}
static int
do_sigaltstack (const stack_t *ss, stack_t *oss, unsigned long sp)
{
struct task_struct *t = current;
if (oss) {
memset(oss, 0, sizeof(stack_t));
oss->ss_sp = (void __user *) t->sas_ss_sp;
oss->ss_size = t->sas_ss_size;
oss->ss_flags = sas_ss_flags(sp) |
(current->sas_ss_flags & SS_FLAG_BITS);
}
if (ss) {
void __user *ss_sp = ss->ss_sp;
size_t ss_size = ss->ss_size;
unsigned ss_flags = ss->ss_flags;
int ss_mode;
if (unlikely(on_sig_stack(sp)))
return -EPERM;
ss_mode = ss_flags & ~SS_FLAG_BITS;
if (unlikely(ss_mode != SS_DISABLE && ss_mode != SS_ONSTACK &&
ss_mode != 0))
return -EINVAL;
if (ss_mode == SS_DISABLE) {
ss_size = 0;
ss_sp = NULL;
} else {
if (unlikely(ss_size < MINSIGSTKSZ))
return -ENOMEM;
}
t->sas_ss_sp = (unsigned long) ss_sp;
t->sas_ss_size = ss_size;
t->sas_ss_flags = ss_flags;
}
return 0;
}
SYSCALL_DEFINE2(sigaltstack,const stack_t __user *,uss, stack_t __user *,uoss)
{
stack_t new, old;
int err;
if (uss && copy_from_user(&new, uss, sizeof(stack_t)))
return -EFAULT;
err = do_sigaltstack(uss ? &new : NULL, uoss ? &old : NULL,
current_user_stack_pointer());
if (!err && uoss && copy_to_user(uoss, &old, sizeof(stack_t)))
err = -EFAULT;
return err;
}
int restore_altstack(const stack_t __user *uss)
{
stack_t new;
if (copy_from_user(&new, uss, sizeof(stack_t)))
return -EFAULT;
(void)do_sigaltstack(&new, NULL, current_user_stack_pointer());
/* squash all but EFAULT for now */
return 0;
}
int __save_altstack(stack_t __user *uss, unsigned long sp)
{
struct task_struct *t = current;
int err = __put_user((void __user *)t->sas_ss_sp, &uss->ss_sp) |
__put_user(t->sas_ss_flags, &uss->ss_flags) |
__put_user(t->sas_ss_size, &uss->ss_size);
if (err)
return err;
if (t->sas_ss_flags & SS_AUTODISARM)
sas_ss_reset(t);
return 0;
}
#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;
if (uss_ptr) {
compat_stack_t uss32;
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;
}
ret = do_sigaltstack(uss_ptr ? &uss : NULL, &uoss,
compat_user_stack_pointer());
if (ret >= 0 && uoss_ptr) {
compat_stack_t old;
memset(&old, 0, sizeof(old));
old.ss_sp = ptr_to_compat(uoss.ss_sp);
old.ss_flags = uoss.ss_flags;
old.ss_size = uoss.ss_size;
if (copy_to_user(uoss_ptr, &old, sizeof(compat_stack_t)))
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)
{
int err;
struct task_struct *t = current;
err = __put_user(ptr_to_compat((void __user *)t->sas_ss_sp),
&uss->ss_sp) |
__put_user(t->sas_ss_flags, &uss->ss_flags) |
__put_user(t->sas_ss_size, &uss->ss_size);
if (err)
return err;
if (t->sas_ss_flags & SS_AUTODISARM)
sas_ss_reset(t);
return 0;
}
#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));
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE1(sigpending, compat_old_sigset_t __user *, set32)
{
sigset_t set;
int err = do_sigpending(&set, sizeof(old_sigset_t));
if (err == 0)
if (copy_to_user(set32, &set, sizeof(old_sigset_t)))
err = -EFAULT;
return err;
}
#endif
#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 CONFIG_SGETMASK_SYSCALL
/*
* 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 /* CONFIG_SGETMASK_SYSCALL */
#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)) {
__set_current_state(TASK_INTERRUPTIBLE);
schedule();
}
return -ERESTARTNOHAND;
}
#endif
static int sigsuspend(sigset_t *set)
{
current->saved_sigmask = current->blocked;
set_current_blocked(set);
while (!signal_pending(current)) {
__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
__weak const char *arch_vma_name(struct vm_area_struct *vma)
{
return NULL;
}
void __init signals_init(void)
{
/* If this check fails, the __ARCH_SI_PREAMBLE_SIZE value is wrong! */
BUILD_BUG_ON(__ARCH_SI_PREAMBLE_SIZE
!= offsetof(struct siginfo, _sifields._pad));
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-119/c/bad_83_0 |
crossvul-cpp_data_bad_5182_1 | /*
+--------------------------------------------------------------------+
| PECL :: http |
+--------------------------------------------------------------------+
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the conditions mentioned |
| in the accompanying LICENSE file are met. |
+--------------------------------------------------------------------+
| Copyright (c) 2004-2014, Michael Wallner <mike@php.net> |
+--------------------------------------------------------------------+
*/
#include "php_http_api.h"
#if PHP_HTTP_HAVE_IDN2
# include <idn2.h>
#elif PHP_HTTP_HAVE_IDN
# include <idna.h>
#endif
#ifdef PHP_HTTP_HAVE_WCHAR
# include <wchar.h>
# include <wctype.h>
#endif
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#include "php_http_utf8.h"
static inline char *localhostname(void)
{
char hostname[1024] = {0};
#ifdef PHP_WIN32
if (SUCCESS == gethostname(hostname, lenof(hostname))) {
return estrdup(hostname);
}
#elif defined(HAVE_GETHOSTNAME)
if (SUCCESS == gethostname(hostname, lenof(hostname))) {
# if defined(HAVE_GETDOMAINNAME)
size_t hlen = strlen(hostname);
if (hlen <= lenof(hostname) - lenof("(none)")) {
hostname[hlen++] = '.';
if (SUCCESS == getdomainname(&hostname[hlen], lenof(hostname) - hlen)) {
if (!strcmp(&hostname[hlen], "(none)")) {
hostname[hlen - 1] = '\0';
}
return estrdup(hostname);
}
}
# endif
if (strcmp(hostname, "(none)")) {
return estrdup(hostname);
}
}
#endif
return estrndup("localhost", lenof("localhost"));
}
#define url(buf) ((php_http_url_t *) (buf).data)
static php_http_url_t *php_http_url_from_env(TSRMLS_D)
{
zval *https, *zhost, *zport;
long port;
php_http_buffer_t buf;
php_http_buffer_init_ex(&buf, MAX(PHP_HTTP_BUFFER_DEFAULT_SIZE, sizeof(php_http_url_t)<<2), PHP_HTTP_BUFFER_INIT_PREALLOC);
php_http_buffer_account(&buf, sizeof(php_http_url_t));
memset(buf.data, 0, buf.used);
/* scheme */
url(buf)->scheme = &buf.data[buf.used];
https = php_http_env_get_server_var(ZEND_STRL("HTTPS"), 1 TSRMLS_CC);
if (https && !strcasecmp(Z_STRVAL_P(https), "ON")) {
php_http_buffer_append(&buf, "https", sizeof("https"));
} else {
php_http_buffer_append(&buf, "http", sizeof("http"));
}
/* host */
url(buf)->host = &buf.data[buf.used];
if ((((zhost = php_http_env_get_server_var(ZEND_STRL("HTTP_HOST"), 1 TSRMLS_CC)) ||
(zhost = php_http_env_get_server_var(ZEND_STRL("SERVER_NAME"), 1 TSRMLS_CC)) ||
(zhost = php_http_env_get_server_var(ZEND_STRL("SERVER_ADDR"), 1 TSRMLS_CC)))) && Z_STRLEN_P(zhost)) {
size_t stop_at = strspn(Z_STRVAL_P(zhost), "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-.");
php_http_buffer_append(&buf, Z_STRVAL_P(zhost), stop_at);
php_http_buffer_append(&buf, "", 1);
} else {
char *host_str = localhostname();
php_http_buffer_append(&buf, host_str, strlen(host_str) + 1);
efree(host_str);
}
/* port */
zport = php_http_env_get_server_var(ZEND_STRL("SERVER_PORT"), 1 TSRMLS_CC);
if (zport && IS_LONG == is_numeric_string(Z_STRVAL_P(zport), Z_STRLEN_P(zport), &port, NULL, 0)) {
url(buf)->port = port;
}
/* path */
if (SG(request_info).request_uri && SG(request_info).request_uri[0]) {
const char *q = strchr(SG(request_info).request_uri, '?');
url(buf)->path = &buf.data[buf.used];
if (q) {
php_http_buffer_append(&buf, SG(request_info).request_uri, q - SG(request_info).request_uri);
php_http_buffer_append(&buf, "", 1);
} else {
php_http_buffer_append(&buf, SG(request_info).request_uri, strlen(SG(request_info).request_uri) + 1);
}
}
/* query */
if (SG(request_info).query_string && SG(request_info).query_string[0]) {
url(buf)->query = &buf.data[buf.used];
php_http_buffer_append(&buf, SG(request_info).query_string, strlen(SG(request_info).query_string) + 1);
}
return url(buf);
}
#define url_isset(u,n) \
((u)&&(u)->n)
#define url_append(buf, append) do { \
char *_ptr = (buf)->data; \
php_http_url_t *_url = (php_http_url_t *) _ptr, _mem = *_url; \
append; \
/* relocate */ \
if (_ptr != (buf)->data) { \
ptrdiff_t diff = (buf)->data - _ptr; \
_url = (php_http_url_t *) (buf)->data; \
if (_mem.scheme) _url->scheme += diff; \
if (_mem.user) _url->user += diff; \
if (_mem.pass) _url->pass += diff; \
if (_mem.host) _url->host += diff; \
if (_mem.path) _url->path += diff; \
if (_mem.query) _url->query += diff; \
if (_mem.fragment) _url->fragment += diff; \
} \
} while (0)
#define url_copy(n) do { \
if (url_isset(new_url, n)) { \
url(buf)->n = &buf.data[buf.used]; \
url_append(&buf, php_http_buffer_append(&buf, new_url->n, strlen(new_url->n) + 1)); \
} else if (url_isset(old_url, n)) { \
url(buf)->n = &buf.data[buf.used]; \
url_append(&buf, php_http_buffer_append(&buf, old_url->n, strlen(old_url->n) + 1)); \
} \
} while (0)
php_http_url_t *php_http_url_mod(const php_http_url_t *old_url, const php_http_url_t *new_url, unsigned flags TSRMLS_DC)
{
php_http_url_t *tmp_url = NULL;
php_http_buffer_t buf;
php_http_buffer_init_ex(&buf, MAX(PHP_HTTP_BUFFER_DEFAULT_SIZE, sizeof(php_http_url_t)<<2), PHP_HTTP_BUFFER_INIT_PREALLOC);
php_http_buffer_account(&buf, sizeof(php_http_url_t));
memset(buf.data, 0, buf.used);
/* set from env if requested */
if (flags & PHP_HTTP_URL_FROM_ENV) {
php_http_url_t *env_url = php_http_url_from_env(TSRMLS_C);
old_url = tmp_url = php_http_url_mod(env_url, old_url, flags ^ PHP_HTTP_URL_FROM_ENV TSRMLS_CC);
php_http_url_free(&env_url);
}
url_copy(scheme);
if (!(flags & PHP_HTTP_URL_STRIP_USER)) {
url_copy(user);
}
if (!(flags & PHP_HTTP_URL_STRIP_PASS)) {
url_copy(pass);
}
url_copy(host);
if (!(flags & PHP_HTTP_URL_STRIP_PORT)) {
url(buf)->port = url_isset(new_url, port) ? new_url->port : ((old_url) ? old_url->port : 0);
}
if (!(flags & PHP_HTTP_URL_STRIP_PATH)) {
if ((flags & PHP_HTTP_URL_JOIN_PATH) && url_isset(old_url, path) && url_isset(new_url, path) && *new_url->path != '/') {
size_t old_path_len = strlen(old_url->path), new_path_len = strlen(new_url->path);
char *path = ecalloc(1, old_path_len + new_path_len + 1 + 1);
strcat(path, old_url->path);
if (path[old_path_len - 1] != '/') {
php_dirname(path, old_path_len);
strcat(path, "/");
}
strcat(path, new_url->path);
url(buf)->path = &buf.data[buf.used];
if (path[0] != '/') {
url_append(&buf, php_http_buffer_append(&buf, "/", 1));
}
url_append(&buf, php_http_buffer_append(&buf, path, strlen(path) + 1));
efree(path);
} else {
const char *path = NULL;
if (url_isset(new_url, path)) {
path = new_url->path;
} else if (url_isset(old_url, path)) {
path = old_url->path;
}
if (path) {
url(buf)->path = &buf.data[buf.used];
url_append(&buf, php_http_buffer_append(&buf, path, strlen(path) + 1));
}
}
}
if (!(flags & PHP_HTTP_URL_STRIP_QUERY)) {
if ((flags & PHP_HTTP_URL_JOIN_QUERY) && url_isset(new_url, query) && url_isset(old_url, query)) {
zval qarr, qstr;
INIT_PZVAL(&qstr);
INIT_PZVAL(&qarr);
array_init(&qarr);
ZVAL_STRING(&qstr, old_url->query, 0);
php_http_querystring_update(&qarr, &qstr, NULL TSRMLS_CC);
ZVAL_STRING(&qstr, new_url->query, 0);
php_http_querystring_update(&qarr, &qstr, NULL TSRMLS_CC);
ZVAL_NULL(&qstr);
php_http_querystring_update(&qarr, NULL, &qstr TSRMLS_CC);
url(buf)->query = &buf.data[buf.used];
url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL(qstr), Z_STRLEN(qstr) + 1));
zval_dtor(&qstr);
zval_dtor(&qarr);
} else {
url_copy(query);
}
}
if (!(flags & PHP_HTTP_URL_STRIP_FRAGMENT)) {
url_copy(fragment);
}
/* done with copy & combine & strip */
if (flags & PHP_HTTP_URL_FROM_ENV) {
/* free old_url we tainted above */
php_http_url_free(&tmp_url);
}
/* replace directory references if path is not a single slash */
if ((flags & PHP_HTTP_URL_SANITIZE_PATH)
&& url(buf)->path[0] && url(buf)->path[1]) {
char *ptr, *end = url(buf)->path + strlen(url(buf)->path) + 1;
for (ptr = strchr(url(buf)->path, '/'); ptr; ptr = strchr(ptr, '/')) {
switch (ptr[1]) {
case '/':
memmove(&ptr[1], &ptr[2], end - &ptr[2]);
break;
case '.':
switch (ptr[2]) {
case '\0':
ptr[1] = '\0';
break;
case '/':
memmove(&ptr[1], &ptr[3], end - &ptr[3]);
break;
case '.':
if (ptr[3] == '/') {
char *pos = &ptr[4];
while (ptr != url(buf)->path) {
if (*--ptr == '/') {
break;
}
}
memmove(&ptr[1], pos, end - pos);
break;
} else if (!ptr[3]) {
/* .. at the end */
ptr[1] = '\0';
}
/* no break */
default:
/* something else */
++ptr;
break;
}
break;
default:
++ptr;
break;
}
}
}
/* unset default ports */
if (url(buf)->port) {
if ( ((url(buf)->port == 80) && url(buf)->scheme && !strcmp(url(buf)->scheme, "http"))
|| ((url(buf)->port ==443) && url(buf)->scheme && !strcmp(url(buf)->scheme, "https"))
) {
url(buf)->port = 0;
}
}
return url(buf);
}
char *php_http_url_to_string(const php_http_url_t *url, char **url_str, size_t *url_len, zend_bool persistent)
{
php_http_buffer_t buf;
php_http_buffer_init_ex(&buf, PHP_HTTP_BUFFER_DEFAULT_SIZE, persistent ?
PHP_HTTP_BUFFER_INIT_PERSISTENT : 0);
if (url->scheme && *url->scheme) {
php_http_buffer_appendl(&buf, url->scheme);
php_http_buffer_appends(&buf, "://");
} else if ((url->user && *url->user) || (url->host && *url->host)) {
php_http_buffer_appends(&buf, "//");
}
if (url->user && *url->user) {
php_http_buffer_appendl(&buf, url->user);
if (url->pass && *url->pass) {
php_http_buffer_appends(&buf, ":");
php_http_buffer_appendl(&buf, url->pass);
}
php_http_buffer_appends(&buf, "@");
}
if (url->host && *url->host) {
php_http_buffer_appendl(&buf, url->host);
if (url->port) {
php_http_buffer_appendf(&buf, ":%hu", url->port);
}
}
if (url->path && *url->path) {
if (*url->path != '/') {
php_http_buffer_appends(&buf, "/");
}
php_http_buffer_appendl(&buf, url->path);
} else if (buf.used) {
php_http_buffer_appends(&buf, "/");
}
if (url->query && *url->query) {
php_http_buffer_appends(&buf, "?");
php_http_buffer_appendl(&buf, url->query);
}
if (url->fragment && *url->fragment) {
php_http_buffer_appends(&buf, "#");
php_http_buffer_appendl(&buf, url->fragment);
}
php_http_buffer_shrink(&buf);
php_http_buffer_fix(&buf);
if (url_len) {
*url_len = buf.used;
}
if (url_str) {
*url_str = buf.data;
}
return buf.data;
}
char *php_http_url_authority_to_string(const php_http_url_t *url, char **url_str, size_t *url_len)
{
php_http_buffer_t buf;
php_http_buffer_init(&buf);
if (url->user && *url->user) {
php_http_buffer_appendl(&buf, url->user);
if (url->pass && *url->pass) {
php_http_buffer_appends(&buf, ":");
php_http_buffer_appendl(&buf, url->pass);
}
php_http_buffer_appends(&buf, "@");
}
if (url->host && *url->host) {
php_http_buffer_appendl(&buf, url->host);
if (url->port) {
php_http_buffer_appendf(&buf, ":%hu", url->port);
}
}
php_http_buffer_shrink(&buf);
php_http_buffer_fix(&buf);
if (url_len) {
*url_len = buf.used;
}
if (url_str) {
*url_str = buf.data;
}
return buf.data;
}
php_http_url_t *php_http_url_from_zval(zval *value, unsigned flags TSRMLS_DC)
{
zval *zcpy;
php_http_url_t *purl;
switch (Z_TYPE_P(value)) {
case IS_ARRAY:
case IS_OBJECT:
purl = php_http_url_from_struct(HASH_OF(value));
break;
default:
zcpy = php_http_ztyp(IS_STRING, value);
purl = php_http_url_parse(Z_STRVAL_P(zcpy), Z_STRLEN_P(zcpy), flags TSRMLS_CC);
zval_ptr_dtor(&zcpy);
}
return purl;
}
php_http_url_t *php_http_url_from_struct(HashTable *ht)
{
zval **e;
php_http_buffer_t buf;
php_http_buffer_init_ex(&buf, MAX(PHP_HTTP_BUFFER_DEFAULT_SIZE, sizeof(php_http_url_t)<<2), PHP_HTTP_BUFFER_INIT_PREALLOC);
php_http_buffer_account(&buf, sizeof(php_http_url_t));
memset(buf.data, 0, buf.used);
if (SUCCESS == zend_hash_find(ht, "scheme", sizeof("scheme"), (void *) &e)) {
zval *cpy = php_http_ztyp(IS_STRING, *e);
url(buf)->scheme = &buf.data[buf.used];
url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL_P(cpy), Z_STRLEN_P(cpy) + 1));
zval_ptr_dtor(&cpy);
}
if (SUCCESS == zend_hash_find(ht, "user", sizeof("user"), (void *) &e)) {
zval *cpy = php_http_ztyp(IS_STRING, *e);
url(buf)->user = &buf.data[buf.used];
url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL_P(cpy), Z_STRLEN_P(cpy) + 1));
zval_ptr_dtor(&cpy);
}
if (SUCCESS == zend_hash_find(ht, "pass", sizeof("pass"), (void *) &e)) {
zval *cpy = php_http_ztyp(IS_STRING, *e);
url(buf)->pass = &buf.data[buf.used];
url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL_P(cpy), Z_STRLEN_P(cpy) + 1));
zval_ptr_dtor(&cpy);
}
if (SUCCESS == zend_hash_find(ht, "host", sizeof("host"), (void *) &e)) {
zval *cpy = php_http_ztyp(IS_STRING, *e);
url(buf)->host = &buf.data[buf.used];
url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL_P(cpy), Z_STRLEN_P(cpy) + 1));
zval_ptr_dtor(&cpy);
}
if (SUCCESS == zend_hash_find(ht, "port", sizeof("port"), (void *) &e)) {
zval *cpy = php_http_ztyp(IS_LONG, *e);
url(buf)->port = (unsigned short) Z_LVAL_P(cpy);
zval_ptr_dtor(&cpy);
}
if (SUCCESS == zend_hash_find(ht, "path", sizeof("path"), (void *) &e)) {
zval *cpy = php_http_ztyp(IS_STRING, *e);
url(buf)->path = &buf.data[buf.used];
url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL_P(cpy), Z_STRLEN_P(cpy) + 1));
zval_ptr_dtor(&cpy);
}
if (SUCCESS == zend_hash_find(ht, "query", sizeof("query"), (void *) &e)) {
zval *cpy = php_http_ztyp(IS_STRING, *e);
url(buf)->query = &buf.data[buf.used];
url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL_P(cpy), Z_STRLEN_P(cpy) + 1));
zval_ptr_dtor(&cpy);
}
if (SUCCESS == zend_hash_find(ht, "fragment", sizeof("fragment"), (void *) &e)) {
zval *cpy = php_http_ztyp(IS_STRING, *e);
url(buf)->fragment = &buf.data[buf.used];
url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL_P(cpy), Z_STRLEN_P(cpy) + 1));
zval_ptr_dtor(&cpy);
}
return url(buf);
}
HashTable *php_http_url_to_struct(const php_http_url_t *url, zval *strct TSRMLS_DC)
{
zval arr;
if (strct) {
switch (Z_TYPE_P(strct)) {
default:
zval_dtor(strct);
array_init(strct);
/* no break */
case IS_ARRAY:
case IS_OBJECT:
INIT_PZVAL_ARRAY((&arr), HASH_OF(strct));
break;
}
} else {
INIT_PZVAL(&arr);
array_init(&arr);
}
if (url) {
if (url->scheme) {
add_assoc_string(&arr, "scheme", url->scheme, 1);
}
if (url->user) {
add_assoc_string(&arr, "user", url->user, 1);
}
if (url->pass) {
add_assoc_string(&arr, "pass", url->pass, 1);
}
if (url->host) {
add_assoc_string(&arr, "host", url->host, 1);
}
if (url->port) {
add_assoc_long(&arr, "port", (long) url->port);
}
if (url->path) {
add_assoc_string(&arr, "path", url->path, 1);
}
if (url->query) {
add_assoc_string(&arr, "query", url->query, 1);
}
if (url->fragment) {
add_assoc_string(&arr, "fragment", url->fragment, 1);
}
}
return Z_ARRVAL(arr);
}
ZEND_RESULT_CODE php_http_url_encode_hash(HashTable *hash, const char *pre_encoded_str, size_t pre_encoded_len, char **encoded_str, size_t *encoded_len TSRMLS_DC)
{
const char *arg_sep_str = "&";
size_t arg_sep_len = 1;
php_http_buffer_t *qstr = php_http_buffer_new();
php_http_url_argsep(&arg_sep_str, &arg_sep_len TSRMLS_CC);
if (SUCCESS != php_http_url_encode_hash_ex(hash, qstr, arg_sep_str, arg_sep_len, "=", 1, pre_encoded_str, pre_encoded_len TSRMLS_CC)) {
php_http_buffer_free(&qstr);
return FAILURE;
}
php_http_buffer_data(qstr, encoded_str, encoded_len);
php_http_buffer_free(&qstr);
return SUCCESS;
}
ZEND_RESULT_CODE php_http_url_encode_hash_ex(HashTable *hash, php_http_buffer_t *qstr, const char *arg_sep_str, size_t arg_sep_len, const char *val_sep_str, size_t val_sep_len, const char *pre_encoded_str, size_t pre_encoded_len TSRMLS_DC)
{
if (pre_encoded_len && pre_encoded_str) {
php_http_buffer_append(qstr, pre_encoded_str, pre_encoded_len);
}
if (!php_http_params_to_string(qstr, hash, arg_sep_str, arg_sep_len, "", 0, val_sep_str, val_sep_len, PHP_HTTP_PARAMS_QUERY TSRMLS_CC)) {
return FAILURE;
}
return SUCCESS;
}
struct parse_state {
php_http_url_t url;
#ifdef ZTS
void ***ts;
#endif
const char *ptr;
const char *end;
size_t maxlen;
off_t offset;
unsigned flags;
char buffer[1]; /* last member */
};
void php_http_url_free(php_http_url_t **url)
{
if (*url) {
efree(*url);
*url = NULL;
}
}
php_http_url_t *php_http_url_copy(const php_http_url_t *url, zend_bool persistent)
{
php_http_url_t *cpy;
const char *end = NULL, *url_ptr = (const char *) url;
char *cpy_ptr;
end = MAX(url->scheme, end);
end = MAX(url->pass, end);
end = MAX(url->user, end);
end = MAX(url->host, end);
end = MAX(url->path, end);
end = MAX(url->query, end);
end = MAX(url->fragment, end);
if (end) {
end += strlen(end) + 1;
cpy_ptr = pecalloc(1, end - url_ptr, persistent);
cpy = (php_http_url_t *) cpy_ptr;
memcpy(cpy_ptr + sizeof(*cpy), url_ptr + sizeof(*url), end - url_ptr - sizeof(*url));
cpy->scheme = url->scheme ? cpy_ptr + (url->scheme - url_ptr) : NULL;
cpy->pass = url->pass ? cpy_ptr + (url->pass - url_ptr) : NULL;
cpy->user = url->user ? cpy_ptr + (url->user - url_ptr) : NULL;
cpy->host = url->host ? cpy_ptr + (url->host - url_ptr) : NULL;
cpy->path = url->path ? cpy_ptr + (url->path - url_ptr) : NULL;
cpy->query = url->query ? cpy_ptr + (url->query - url_ptr) : NULL;
cpy->fragment = url->fragment ? cpy_ptr + (url->fragment - url_ptr) : NULL;
} else {
cpy = ecalloc(1, sizeof(*url));
}
cpy->port = url->port;
return cpy;
}
static size_t parse_mb_utf8(unsigned *wc, const char *ptr, const char *end)
{
unsigned wchar;
size_t consumed = utf8towc(&wchar, (const unsigned char *) ptr, end - ptr);
if (!consumed || consumed == (size_t) -1) {
return 0;
}
if (wc) {
*wc = wchar;
}
return consumed;
}
#ifdef PHP_HTTP_HAVE_WCHAR
static size_t parse_mb_loc(unsigned *wc, const char *ptr, const char *end)
{
wchar_t wchar;
size_t consumed = 0;
#if defined(HAVE_MBRTOWC)
mbstate_t ps;
memset(&ps, 0, sizeof(ps));
consumed = mbrtowc(&wchar, ptr, end - ptr, &ps);
#elif defined(HAVE_MBTOWC)
consumed = mbtowc(&wchar, ptr, end - ptr);
#endif
if (!consumed || consumed == (size_t) -1) {
return 0;
}
if (wc) {
*wc = wchar;
}
return consumed;
}
#endif
typedef enum parse_mb_what {
PARSE_SCHEME,
PARSE_USERINFO,
PARSE_HOSTINFO,
PARSE_PATH,
PARSE_QUERY,
PARSE_FRAGMENT
} parse_mb_what_t;
static const char * const parse_what[] = {
"scheme",
"userinfo",
"hostinfo",
"path",
"query",
"fragment"
};
static const char parse_xdigits[] = "0123456789ABCDEF";
static size_t parse_mb(struct parse_state *state, parse_mb_what_t what, const char *ptr, const char *end, const char *begin, zend_bool silent)
{
unsigned wchar;
size_t consumed = 0;
if (state->flags & PHP_HTTP_URL_PARSE_MBUTF8) {
consumed = parse_mb_utf8(&wchar, ptr, end);
}
#ifdef PHP_HTTP_HAVE_WCHAR
else if (state->flags & PHP_HTTP_URL_PARSE_MBLOC) {
consumed = parse_mb_loc(&wchar, ptr, end);
}
#endif
while (consumed) {
if (!(state->flags & PHP_HTTP_URL_PARSE_TOPCT) || what == PARSE_HOSTINFO || what == PARSE_SCHEME) {
if (what == PARSE_HOSTINFO && (state->flags & PHP_HTTP_URL_PARSE_TOIDN)) {
/* idna */
} else if (state->flags & PHP_HTTP_URL_PARSE_MBUTF8) {
if (!isualnum(wchar)) {
break;
}
#ifdef PHP_HTTP_HAVE_WCHAR
} else if (state->flags & PHP_HTTP_URL_PARSE_MBLOC) {
if (!iswalnum(wchar)) {
break;
}
#endif
}
PHP_HTTP_DUFF(consumed, state->buffer[state->offset++] = *ptr++);
} else {
int i = 0;
PHP_HTTP_DUFF(consumed,
state->buffer[state->offset++] = '%';
state->buffer[state->offset++] = parse_xdigits[((unsigned char) ptr[i]) >> 4];
state->buffer[state->offset++] = parse_xdigits[((unsigned char) ptr[i]) & 0xf];
++i;
);
}
return consumed;
}
if (!silent) {
TSRMLS_FETCH_FROM_CTX(state->ts);
if (consumed) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Failed to parse %s; unexpected multibyte sequence 0x%x at pos %u in '%s'",
parse_what[what], wchar, (unsigned) (ptr - begin), begin);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Failed to parse %s; unexpected byte 0x%02x at pos %u in '%s'",
parse_what[what], (unsigned char) *ptr, (unsigned) (ptr - begin), begin);
}
}
return 0;
}
static ZEND_RESULT_CODE parse_userinfo(struct parse_state *state, const char *ptr)
{
size_t mb;
const char *password = NULL, *end = state->ptr, *tmp = ptr;
TSRMLS_FETCH_FROM_CTX(state->ts);
state->url.user = &state->buffer[state->offset];
do {
switch (*ptr) {
case ':':
if (password) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Failed to parse password; duplicate ':' at pos %u in '%s'",
(unsigned) (ptr - tmp), tmp);
return FAILURE;
}
password = ptr + 1;
state->buffer[state->offset++] = 0;
state->url.pass = &state->buffer[state->offset];
break;
case '%':
if (ptr[1] != '%' && (end - ptr <= 2 || !isxdigit(*(ptr+1)) || !isxdigit(*(ptr+2)))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Failed to parse userinfo; invalid percent encoding at pos %u in '%s'",
(unsigned) (ptr - tmp), tmp);
return FAILURE;
}
state->buffer[state->offset++] = *ptr++;
state->buffer[state->offset++] = *ptr++;
state->buffer[state->offset++] = *ptr;
break;
case '!': case '$': case '&': case '\'': case '(': case ')': case '*':
case '+': case ',': case ';': case '=': /* sub-delims */
case '-': case '.': case '_': case '~': /* unreserved */
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
case 'V': case 'W': case 'X': case 'Y': case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y': case 'z':
case '0': case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9':
/* allowed */
state->buffer[state->offset++] = *ptr;
break;
default:
if (!(mb = parse_mb(state, PARSE_USERINFO, ptr, end, tmp, 0))) {
return FAILURE;
}
ptr += mb - 1;
}
} while(++ptr != end);
state->buffer[state->offset++] = 0;
return SUCCESS;
}
#if defined(PHP_WIN32) || defined(HAVE_UIDNA_IDNTOASCII)
typedef size_t (*parse_mb_func)(unsigned *wc, const char *ptr, const char *end);
static ZEND_RESULT_CODE to_utf16(parse_mb_func fn, const char *u8, uint16_t **u16, size_t *len TSRMLS_DC)
{
size_t offset = 0, u8_len = strlen(u8);
*u16 = ecalloc(4 * sizeof(uint16_t), u8_len + 1);
*len = 0;
while (offset < u8_len) {
unsigned wc;
uint16_t buf[2], *ptr = buf;
size_t consumed = fn(&wc, &u8[offset], &u8[u8_len]);
if (!consumed) {
efree(*u16);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse UTF-8 at pos %zu of '%s'", offset, u8);
return FAILURE;
} else {
offset += consumed;
}
switch (wctoutf16(buf, wc)) {
case 2:
(*u16)[(*len)++] = *ptr++;
/* no break */
case 1:
(*u16)[(*len)++] = *ptr++;
break;
case 0:
default:
efree(*u16);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to convert UTF-32 'U+%X' to UTF-16", wc);
return FAILURE;
}
}
return SUCCESS;
}
#endif
#ifndef MAXHOSTNAMELEN
# define MAXHOSTNAMELEN 256
#endif
#if PHP_HTTP_HAVE_IDN2
static ZEND_RESULT_CODE parse_idn2(struct parse_state *state, size_t prev_len)
{
char *idn = NULL;
int rv = -1;
TSRMLS_FETCH_FROM_CTX(state->ts);
if (state->flags & PHP_HTTP_URL_PARSE_MBUTF8) {
rv = idn2_lookup_u8((const unsigned char *) state->url.host, (unsigned char **) &idn, IDN2_NFC_INPUT);
}
# ifdef PHP_HTTP_HAVE_WCHAR
else if (state->flags & PHP_HTTP_URL_PARSE_MBLOC) {
rv = idn2_lookup_ul(state->url.host, &idn, 0);
}
# endif
if (rv != IDN2_OK) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN; %s", idn2_strerror(rv));
return FAILURE;
} else {
size_t idnlen = strlen(idn);
memcpy(state->url.host, idn, idnlen + 1);
free(idn);
state->offset += idnlen - prev_len;
return SUCCESS;
}
}
#elif PHP_HTTP_HAVE_IDN
static ZEND_RESULT_CODE parse_idn(struct parse_state *state, size_t prev_len)
{
char *idn = NULL;
int rv = -1;
TSRMLS_FETCH_FROM_CTX(state->ts);
if (state->flags & PHP_HTTP_URL_PARSE_MBUTF8) {
rv = idna_to_ascii_8z(state->url.host, &idn, IDNA_ALLOW_UNASSIGNED|IDNA_USE_STD3_ASCII_RULES);
}
# ifdef PHP_HTTP_HAVE_WCHAR
else if (state->flags & PHP_HTTP_URL_PARSE_MBLOC) {
rv = idna_to_ascii_lz(state->url.host, &idn, IDNA_ALLOW_UNASSIGNED|IDNA_USE_STD3_ASCII_RULES);
}
# endif
if (rv != IDNA_SUCCESS) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN; %s", idna_strerror(rv));
return FAILURE;
} else {
size_t idnlen = strlen(idn);
memcpy(state->url.host, idn, idnlen + 1);
free(idn);
state->offset += idnlen - prev_len;
return SUCCESS;
}
}
#endif
#ifdef HAVE_UIDNA_IDNTOASCII
# if HAVE_UNICODE_UIDNA_H
# include <unicode/uidna.h>
# else
typedef uint16_t UChar;
typedef enum { U_ZERO_ERROR = 0 } UErrorCode;
int32_t uidna_IDNToASCII(const UChar *src, int32_t srcLength, UChar *dest, int32_t destCapacity, int32_t options, void *parseError, UErrorCode *status);
# endif
static ZEND_RESULT_CODE parse_uidn(struct parse_state *state)
{
char *host_ptr;
uint16_t *uhost_str, ahost_str[MAXHOSTNAMELEN], *ahost_ptr;
size_t uhost_len, ahost_len;
UErrorCode error = U_ZERO_ERROR;
TSRMLS_FETCH_FROM_CTX(state->ts);
if (state->flags & PHP_HTTP_URL_PARSE_MBUTF8) {
if (SUCCESS != to_utf16(parse_mb_utf8, state->url.host, &uhost_str, &uhost_len TSRMLS_CC)) {
return FAILURE;
}
#ifdef PHP_HTTP_HAVE_WCHAR
} else if (state->flags & PHP_HTTP_URL_PARSE_MBLOC) {
if (SUCCESS != to_utf16(parse_mb_loc, state->url.host, &uhost_str, &uhost_len TSRMLS_CC)) {
return FAILURE;
}
#endif
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN; codepage not specified");
return FAILURE;
}
ahost_len = uidna_IDNToASCII(uhost_str, uhost_len, ahost_str, MAXHOSTNAMELEN, 3, NULL, &error);
efree(uhost_str);
if (error != U_ZERO_ERROR) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN; ICU error %d", error);
return FAILURE;
}
host_ptr = state->url.host;
ahost_ptr = ahost_str;
PHP_HTTP_DUFF(ahost_len, *host_ptr++ = *ahost_ptr++);
*host_ptr = '\0';
state->offset += host_ptr - state->url.host;
return SUCCESS;
}
#endif
#if 0 && defined(PHP_WIN32)
static ZEND_RESULT_CODE parse_widn(struct parse_state *state)
{
char *host_ptr;
uint16_t *uhost_str, ahost_str[MAXHOSTNAMELEN], *ahost_ptr;
size_t uhost_len;
TSRMLS_FETCH_FROM_CTX(state->ts);
if (state->flags & PHP_HTTP_URL_PARSE_MBUTF8) {
if (SUCCESS != to_utf16(parse_mb_utf8, state->url.host, &uhost_str, &uhost_len)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN");
return FAILURE;
}
#ifdef PHP_HTTP_HAVE_WCHAR
} else if (state->flags & PHP_HTTP_URL_PARSE_MBLOC) {
if (SUCCESS != to_utf16(parse_mb_loc, state->url.host, &uhost_str, &uhost_len)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN");
return FAILURE;
}
#endif
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN");
return FAILURE;
}
if (!IdnToAscii(IDN_ALLOW_UNASSIGNED|IDN_USE_STD3_ASCII_RULES, uhost_str, uhost_len, ahost_str, MAXHOSTNAMELEN)) {
efree(uhost_str);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN");
return FAILURE;
}
efree(uhost_str);
host_ptr = state->url.host;
ahost_ptr = ahost_str;
PHP_HTTP_DUFF(wcslen(ahost_str), *host_ptr++ = *ahost_ptr++);
efree(ahost_str);
*host_ptr = '\0';
state->offset += host_ptr - state->url.host;
return SUCCESS;
}
#endif
#ifdef HAVE_INET_PTON
static const char *parse_ip6(struct parse_state *state, const char *ptr)
{
const char *error = NULL, *end = state->ptr, *tmp = memchr(ptr, ']', end - ptr);
TSRMLS_FETCH_FROM_CTX(state->ts);
if (tmp) {
size_t addrlen = tmp - ptr + 1;
char buf[16], *addr = estrndup(ptr + 1, addrlen - 2);
int rv = inet_pton(AF_INET6, addr, buf);
if (rv == 1) {
state->buffer[state->offset] = '[';
state->url.host = &state->buffer[state->offset];
inet_ntop(AF_INET6, buf, state->url.host + 1, state->maxlen - state->offset);
state->offset += strlen(state->url.host);
state->buffer[state->offset++] = ']';
state->buffer[state->offset++] = 0;
ptr = tmp + 1;
} else if (rv == -1) {
error = strerror(errno);
} else {
error = "unexpected '['";
}
efree(addr);
} else {
error = "expected ']'";
}
if (error) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse hostinfo; %s", error);
return NULL;
}
return ptr;
}
#endif
static ZEND_RESULT_CODE parse_hostinfo(struct parse_state *state, const char *ptr)
{
size_t mb, len;
const char *end = state->ptr, *tmp = ptr, *port = NULL, *label = NULL;
TSRMLS_FETCH_FROM_CTX(state->ts);
#ifdef HAVE_INET_PTON
if (*ptr == '[' && !(ptr = parse_ip6(state, ptr))) {
return FAILURE;
}
#endif
if (ptr != end) do {
switch (*ptr) {
case ':':
if (port) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Failed to parse port; unexpected ':' at pos %u in '%s'",
(unsigned) (ptr - tmp), tmp);
return FAILURE;
}
port = ptr + 1;
break;
case '%':
if (ptr[1] != '%' && (end - ptr <= 2 || !isxdigit(*(ptr+1)) || !isxdigit(*(ptr+2)))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Failed to parse hostinfo; invalid percent encoding at pos %u in '%s'",
(unsigned) (ptr - tmp), tmp);
return FAILURE;
}
state->buffer[state->offset++] = *ptr++;
state->buffer[state->offset++] = *ptr++;
state->buffer[state->offset++] = *ptr;
break;
case '!': case '$': case '&': case '\'': case '(': case ')': case '*':
case '+': case ',': case ';': case '=': /* sub-delims */
case '-': case '.': case '_': case '~': /* unreserved */
if (port || !label) {
/* sort of a compromise, just ensure we don't end up
* with a dot at the beginning or two consecutive dots
*/
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Failed to parse %s; unexpected '%c' at pos %u in '%s'",
port ? "port" : "host",
(unsigned char) *ptr, (unsigned) (ptr - tmp), tmp);
return FAILURE;
}
state->buffer[state->offset++] = *ptr;
label = NULL;
break;
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
case 'V': case 'W': case 'X': case 'Y': case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y': case 'z':
if (port) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Failed to parse port; unexpected char '%c' at pos %u in '%s'",
(unsigned char) *ptr, (unsigned) (ptr - tmp), tmp);
return FAILURE;
}
/* no break */
case '0': case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9':
/* allowed */
if (port) {
state->url.port *= 10;
state->url.port += *ptr - '0';
} else {
label = ptr;
state->buffer[state->offset++] = *ptr;
}
break;
default:
if (ptr == end) {
break;
} else if (port) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Failed to parse port; unexpected byte 0x%02x at pos %u in '%s'",
(unsigned char) *ptr, (unsigned) (ptr - tmp), tmp);
return FAILURE;
} else if (!(mb = parse_mb(state, PARSE_HOSTINFO, ptr, end, tmp, 0))) {
return FAILURE;
}
label = ptr;
ptr += mb - 1;
}
} while (++ptr != end);
if (!state->url.host) {
len = (port ? port - tmp - 1 : end - tmp);
state->url.host = &state->buffer[state->offset - len];
state->buffer[state->offset++] = 0;
}
if (state->flags & PHP_HTTP_URL_PARSE_TOIDN) {
#if PHP_HTTP_HAVE_IDN2
return parse_idn2(state, len);
#elif PHP_HTTP_HAVE_IDN
return parse_idn(state, len);
#endif
#ifdef HAVE_UIDNA_IDNTOASCII
return parse_uidn(state);
#endif
#if 0 && defined(PHP_WIN32)
return parse_widn(state);
#endif
}
return SUCCESS;
}
static const char *parse_authority(struct parse_state *state)
{
const char *tmp = state->ptr, *host = NULL;
do {
switch (*state->ptr) {
case '@':
/* userinfo delimiter */
if (host) {
TSRMLS_FETCH_FROM_CTX(state->ts);
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Failed to parse userinfo; unexpected '@'");
return NULL;
}
host = state->ptr + 1;
if (tmp != state->ptr && SUCCESS != parse_userinfo(state, tmp)) {
return NULL;
}
tmp = state->ptr + 1;
break;
case '/':
case '?':
case '#':
case '\0':
EOD:
/* host delimiter */
if (tmp != state->ptr && SUCCESS != parse_hostinfo(state, tmp)) {
return NULL;
}
return state->ptr;
}
} while (++state->ptr <= state->end);
--state->ptr;
goto EOD;
}
static const char *parse_path(struct parse_state *state)
{
size_t mb;
const char *tmp;
TSRMLS_FETCH_FROM_CTX(state->ts);
/* is there actually a path to parse? */
if (!*state->ptr) {
return state->ptr;
}
tmp = state->ptr;
state->url.path = &state->buffer[state->offset];
do {
switch (*state->ptr) {
case '#':
case '?':
goto done;
case '%':
if (state->ptr[1] != '%' && (state->end - state->ptr <= 2 || !isxdigit(*(state->ptr+1)) || !isxdigit(*(state->ptr+2)))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Failed to parse path; invalid percent encoding at pos %u in '%s'",
(unsigned) (state->ptr - tmp), tmp);
return NULL;
}
state->buffer[state->offset++] = *state->ptr++;
state->buffer[state->offset++] = *state->ptr++;
state->buffer[state->offset++] = *state->ptr;
break;
case '/': /* yeah, well */
case '!': case '$': case '&': case '\'': case '(': case ')': case '*':
case '+': case ',': case ';': case '=': /* sub-delims */
case '-': case '.': case '_': case '~': /* unreserved */
case ':': case '@': /* pchar */
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
case 'V': case 'W': case 'X': case 'Y': case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y': case 'z':
case '0': case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9':
/* allowed */
state->buffer[state->offset++] = *state->ptr;
break;
default:
if (!(mb = parse_mb(state, PARSE_PATH, state->ptr, state->end, tmp, 0))) {
return NULL;
}
state->ptr += mb - 1;
}
} while (++state->ptr < state->end);
done:
/* did we have any path component ? */
if (tmp != state->ptr) {
state->buffer[state->offset++] = 0;
} else {
state->url.path = NULL;
}
return state->ptr;
}
static const char *parse_query(struct parse_state *state)
{
size_t mb;
const char *tmp = state->ptr + !!*state->ptr;
TSRMLS_FETCH_FROM_CTX(state->ts);
/* is there actually a query to parse? */
if (*state->ptr != '?') {
return state->ptr;
}
/* skip initial '?' */
tmp = ++state->ptr;
state->url.query = &state->buffer[state->offset];
while (state->ptr < state->end) {
switch (*state->ptr) {
case '#':
goto done;
case '%':
if (state->ptr[1] != '%' && (state->end - state->ptr <= 2 || !isxdigit(*(state->ptr+1)) || !isxdigit(*(state->ptr+2)))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Failed to parse query; invalid percent encoding at pos %u in '%s'",
(unsigned) (state->ptr - tmp), tmp);
return NULL;
}
state->buffer[state->offset++] = *state->ptr++;
state->buffer[state->offset++] = *state->ptr++;
state->buffer[state->offset++] = *state->ptr;
break;
/* RFC1738 unsafe */
case '{': case '}':
case '<': case '>':
case '[': case ']':
case '|': case '\\': case '^': case '`': case '"': case ' ':
if (state->flags & PHP_HTTP_URL_PARSE_TOPCT) {
state->buffer[state->offset++] = '%';
state->buffer[state->offset++] = parse_xdigits[((unsigned char) *state->ptr) >> 4];
state->buffer[state->offset++] = parse_xdigits[((unsigned char) *state->ptr) & 0xf];
break;
}
/* no break */
case '?': case '/': /* yeah, well */
case '!': case '$': case '&': case '\'': case '(': case ')': case '*':
case '+': case ',': case ';': case '=': /* sub-delims */
case '-': case '.': case '_': case '~': /* unreserved */
case ':': case '@': /* pchar */
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
case 'V': case 'W': case 'X': case 'Y': case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y': case 'z':
case '0': case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9':
/* allowed */
state->buffer[state->offset++] = *state->ptr;
break;
default:
if (!(mb = parse_mb(state, PARSE_QUERY, state->ptr, state->end, tmp, 0))) {
return NULL;
}
state->ptr += mb - 1;
}
++state->ptr;
}
done:
state->buffer[state->offset++] = 0;
return state->ptr;
}
static const char *parse_fragment(struct parse_state *state)
{
size_t mb;
const char *tmp;
TSRMLS_FETCH_FROM_CTX(state->ts);
/* is there actually a fragment to parse? */
if (*state->ptr != '#') {
return state->ptr;
}
/* skip initial '#' */
tmp = ++state->ptr;
state->url.fragment = &state->buffer[state->offset];
do {
switch (*state->ptr) {
case '%':
if (state->ptr[1] != '%' && (state->end - state->ptr <= 2 || !isxdigit(*(state->ptr+1)) || !isxdigit(*(state->ptr+2)))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Failed to parse fragment; invalid percent encoding at pos %u in '%s'",
(unsigned) (state->ptr - tmp), tmp);
return NULL;
}
state->buffer[state->offset++] = *state->ptr++;
state->buffer[state->offset++] = *state->ptr++;
state->buffer[state->offset++] = *state->ptr;
break;
/* RFC1738 unsafe */
case '{': case '}':
case '<': case '>':
case '[': case ']':
case '|': case '\\': case '^': case '`': case '"': case ' ':
if (state->flags & PHP_HTTP_URL_PARSE_TOPCT) {
state->buffer[state->offset++] = '%';
state->buffer[state->offset++] = parse_xdigits[((unsigned char) *state->ptr) >> 4];
state->buffer[state->offset++] = parse_xdigits[((unsigned char) *state->ptr) & 0xf];
break;
}
/* no break */
case '?': case '/':
case '!': case '$': case '&': case '\'': case '(': case ')': case '*':
case '+': case ',': case ';': case '=': /* sub-delims */
case '-': case '.': case '_': case '~': /* unreserved */
case ':': case '@': /* pchar */
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
case 'V': case 'W': case 'X': case 'Y': case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y': case 'z':
case '0': case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9':
/* allowed */
state->buffer[state->offset++] = *state->ptr;
break;
default:
if (!(mb = parse_mb(state, PARSE_FRAGMENT, state->ptr, state->end, tmp, 0))) {
return NULL;
}
state->ptr += mb - 1;
}
} while (++state->ptr < state->end);
state->buffer[state->offset++] = 0;
return state->ptr;
}
static const char *parse_hier(struct parse_state *state)
{
if (*state->ptr == '/') {
if (state->end - state->ptr > 1) {
if (*(state->ptr + 1) == '/') {
state->ptr += 2;
if (!(state->ptr = parse_authority(state))) {
return NULL;
}
}
}
}
return parse_path(state);
}
static const char *parse_scheme(struct parse_state *state)
{
size_t mb;
const char *tmp = state->ptr;
do {
switch (*state->ptr) {
case ':':
/* scheme delimiter */
state->url.scheme = &state->buffer[0];
state->buffer[state->offset++] = 0;
return ++state->ptr;
case '0': case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9':
case '+': case '-': case '.':
if (state->ptr == tmp) {
return tmp;
}
/* no break */
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
case 'V': case 'W': case 'X': case 'Y': case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y': case 'z':
/* scheme part */
state->buffer[state->offset++] = *state->ptr;
break;
default:
if (!(mb = parse_mb(state, PARSE_SCHEME, state->ptr, state->end, tmp, 1))) {
/* soft fail; parse path next */
return tmp;
}
state->ptr += mb - 1;
}
} while (++state->ptr != state->end);
return state->ptr = tmp;
}
php_http_url_t *php_http_url_parse(const char *str, size_t len, unsigned flags TSRMLS_DC)
{
size_t maxlen = 3 * len;
struct parse_state *state = ecalloc(1, sizeof(*state) + maxlen);
state->end = str + len;
state->ptr = str;
state->flags = flags;
state->maxlen = maxlen;
TSRMLS_SET_CTX(state->ts);
if (!parse_scheme(state)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL scheme: '%s'", state->ptr);
efree(state);
return NULL;
}
if (!parse_hier(state)) {
efree(state);
return NULL;
}
if (!parse_query(state)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL query: '%s'", state->ptr);
efree(state);
return NULL;
}
if (!parse_fragment(state)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL fragment: '%s'", state->ptr);
efree(state);
return NULL;
}
return (php_http_url_t *) state;
}
php_http_url_t *php_http_url_parse_authority(const char *str, size_t len, unsigned flags TSRMLS_DC)
{
size_t maxlen = 3 * len;
struct parse_state *state = ecalloc(1, sizeof(*state) + maxlen);
state->end = str + len;
state->ptr = str;
state->flags = flags;
state->maxlen = maxlen;
TSRMLS_SET_CTX(state->ts);
if (!(state->ptr = parse_authority(state))) {
efree(state);
return NULL;
}
if (state->ptr != state->end) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Failed to parse URL authority, unexpected character at pos %u in '%s'",
(unsigned) (state->ptr - str), str);
efree(state);
return NULL;
}
return (php_http_url_t *) state;
}
ZEND_BEGIN_ARG_INFO_EX(ai_HttpUrl___construct, 0, 0, 0)
ZEND_ARG_INFO(0, old_url)
ZEND_ARG_INFO(0, new_url)
ZEND_ARG_INFO(0, flags)
ZEND_END_ARG_INFO();
PHP_METHOD(HttpUrl, __construct)
{
zval *new_url = NULL, *old_url = NULL;
long flags = PHP_HTTP_URL_FROM_ENV;
zend_error_handling zeh;
php_http_expect(SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z!z!l", &old_url, &new_url, &flags), invalid_arg, return);
zend_replace_error_handling(EH_THROW, php_http_exception_bad_url_class_entry, &zeh TSRMLS_CC);
{
php_http_url_t *res_purl, *new_purl = NULL, *old_purl = NULL;
if (new_url) {
new_purl = php_http_url_from_zval(new_url, flags TSRMLS_CC);
if (!new_purl) {
zend_restore_error_handling(&zeh TSRMLS_CC);
return;
}
}
if (old_url) {
old_purl = php_http_url_from_zval(old_url, flags TSRMLS_CC);
if (!old_purl) {
if (new_purl) {
php_http_url_free(&new_purl);
}
zend_restore_error_handling(&zeh TSRMLS_CC);
return;
}
}
res_purl = php_http_url_mod(old_purl, new_purl, flags TSRMLS_CC);
php_http_url_to_struct(res_purl, getThis() TSRMLS_CC);
php_http_url_free(&res_purl);
if (old_purl) {
php_http_url_free(&old_purl);
}
if (new_purl) {
php_http_url_free(&new_purl);
}
}
zend_restore_error_handling(&zeh TSRMLS_CC);
}
ZEND_BEGIN_ARG_INFO_EX(ai_HttpUrl_mod, 0, 0, 1)
ZEND_ARG_INFO(0, more_url_parts)
ZEND_ARG_INFO(0, flags)
ZEND_END_ARG_INFO();
PHP_METHOD(HttpUrl, mod)
{
zval *new_url = NULL;
long flags = PHP_HTTP_URL_JOIN_PATH | PHP_HTTP_URL_JOIN_QUERY | PHP_HTTP_URL_SANITIZE_PATH;
zend_error_handling zeh;
php_http_expect(SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z!|l", &new_url, &flags), invalid_arg, return);
zend_replace_error_handling(EH_THROW, php_http_exception_bad_url_class_entry, &zeh TSRMLS_CC);
{
php_http_url_t *new_purl = NULL, *old_purl = NULL;
if (new_url) {
new_purl = php_http_url_from_zval(new_url, flags TSRMLS_CC);
if (!new_purl) {
zend_restore_error_handling(&zeh TSRMLS_CC);
return;
}
}
if ((old_purl = php_http_url_from_struct(HASH_OF(getThis())))) {
php_http_url_t *res_purl;
ZVAL_OBJVAL(return_value, zend_objects_clone_obj(getThis() TSRMLS_CC), 0);
res_purl = php_http_url_mod(old_purl, new_purl, flags TSRMLS_CC);
php_http_url_to_struct(res_purl, return_value TSRMLS_CC);
php_http_url_free(&res_purl);
php_http_url_free(&old_purl);
}
if (new_purl) {
php_http_url_free(&new_purl);
}
}
zend_restore_error_handling(&zeh TSRMLS_CC);
}
ZEND_BEGIN_ARG_INFO_EX(ai_HttpUrl_toString, 0, 0, 0)
ZEND_END_ARG_INFO();
PHP_METHOD(HttpUrl, toString)
{
if (SUCCESS == zend_parse_parameters_none()) {
php_http_url_t *purl;
if ((purl = php_http_url_from_struct(HASH_OF(getThis())))) {
char *str;
size_t len;
php_http_url_to_string(purl, &str, &len, 0);
php_http_url_free(&purl);
RETURN_STRINGL(str, len, 0);
}
}
RETURN_EMPTY_STRING();
}
ZEND_BEGIN_ARG_INFO_EX(ai_HttpUrl_toArray, 0, 0, 0)
ZEND_END_ARG_INFO();
PHP_METHOD(HttpUrl, toArray)
{
php_http_url_t *purl;
if (SUCCESS != zend_parse_parameters_none()) {
return;
}
/* strip any non-URL properties */
purl = php_http_url_from_struct(HASH_OF(getThis()));
php_http_url_to_struct(purl, return_value TSRMLS_CC);
php_http_url_free(&purl);
}
static zend_function_entry php_http_url_methods[] = {
PHP_ME(HttpUrl, __construct, ai_HttpUrl___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
PHP_ME(HttpUrl, mod, ai_HttpUrl_mod, ZEND_ACC_PUBLIC)
PHP_ME(HttpUrl, toString, ai_HttpUrl_toString, ZEND_ACC_PUBLIC)
ZEND_MALIAS(HttpUrl, __toString, toString, ai_HttpUrl_toString, ZEND_ACC_PUBLIC)
PHP_ME(HttpUrl, toArray, ai_HttpUrl_toArray, ZEND_ACC_PUBLIC)
EMPTY_FUNCTION_ENTRY
};
zend_class_entry *php_http_url_class_entry;
PHP_MINIT_FUNCTION(http_url)
{
zend_class_entry ce = {0};
INIT_NS_CLASS_ENTRY(ce, "http", "Url", php_http_url_methods);
php_http_url_class_entry = zend_register_internal_class(&ce TSRMLS_CC);
zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("scheme"), ZEND_ACC_PUBLIC TSRMLS_CC);
zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("user"), ZEND_ACC_PUBLIC TSRMLS_CC);
zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("pass"), ZEND_ACC_PUBLIC TSRMLS_CC);
zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("host"), ZEND_ACC_PUBLIC TSRMLS_CC);
zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("port"), ZEND_ACC_PUBLIC TSRMLS_CC);
zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("path"), ZEND_ACC_PUBLIC TSRMLS_CC);
zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("query"), ZEND_ACC_PUBLIC TSRMLS_CC);
zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("fragment"), ZEND_ACC_PUBLIC TSRMLS_CC);
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("REPLACE"), PHP_HTTP_URL_REPLACE TSRMLS_CC);
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("JOIN_PATH"), PHP_HTTP_URL_JOIN_PATH TSRMLS_CC);
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("JOIN_QUERY"), PHP_HTTP_URL_JOIN_QUERY TSRMLS_CC);
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_USER"), PHP_HTTP_URL_STRIP_USER TSRMLS_CC);
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_PASS"), PHP_HTTP_URL_STRIP_PASS TSRMLS_CC);
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_AUTH"), PHP_HTTP_URL_STRIP_AUTH TSRMLS_CC);
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_PORT"), PHP_HTTP_URL_STRIP_PORT TSRMLS_CC);
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_PATH"), PHP_HTTP_URL_STRIP_PATH TSRMLS_CC);
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_QUERY"), PHP_HTTP_URL_STRIP_QUERY TSRMLS_CC);
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_FRAGMENT"), PHP_HTTP_URL_STRIP_FRAGMENT TSRMLS_CC);
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_ALL"), PHP_HTTP_URL_STRIP_ALL TSRMLS_CC);
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("FROM_ENV"), PHP_HTTP_URL_FROM_ENV TSRMLS_CC);
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("SANITIZE_PATH"), PHP_HTTP_URL_SANITIZE_PATH TSRMLS_CC);
#ifdef PHP_HTTP_HAVE_WCHAR
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("PARSE_MBLOC"), PHP_HTTP_URL_PARSE_MBLOC TSRMLS_CC);
#endif
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("PARSE_MBUTF8"), PHP_HTTP_URL_PARSE_MBUTF8 TSRMLS_CC);
#if defined(PHP_HTTP_HAVE_IDN2) || defined(PHP_HTTP_HAVE_IDN) || defined(HAVE_UIDNA_IDNTOASCII)
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("PARSE_TOIDN"), PHP_HTTP_URL_PARSE_TOIDN TSRMLS_CC);
#endif
zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("PARSE_TOPCT"), PHP_HTTP_URL_PARSE_TOPCT TSRMLS_CC);
return SUCCESS;
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5182_1 |
crossvul-cpp_data_bad_5476_1 | /* $Id$ */
/*
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
/*
* TIFF Library.
*
* Predictor Tag Support (used by multiple codecs).
*/
#include "tiffiop.h"
#include "tif_predict.h"
#define PredictorState(tif) ((TIFFPredictorState*) (tif)->tif_data)
static void horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc);
static void horAcc16(TIFF* tif, uint8* cp0, tmsize_t cc);
static void horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc);
static void swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc);
static void swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc);
static void horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc);
static void horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc);
static void horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc);
static void swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc);
static void swabHorDiff32(TIFF* tif, uint8* cp0, tmsize_t cc);
static void fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc);
static void fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc);
static int PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s);
static int PredictorDecodeTile(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s);
static int PredictorEncodeRow(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s);
static int PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s);
static int
PredictorSetup(TIFF* tif)
{
static const char module[] = "PredictorSetup";
TIFFPredictorState* sp = PredictorState(tif);
TIFFDirectory* td = &tif->tif_dir;
switch (sp->predictor) /* no differencing */
{
case PREDICTOR_NONE:
return 1;
case PREDICTOR_HORIZONTAL:
if (td->td_bitspersample != 8
&& td->td_bitspersample != 16
&& td->td_bitspersample != 32) {
TIFFErrorExt(tif->tif_clientdata, module,
"Horizontal differencing \"Predictor\" not supported with %d-bit samples",
td->td_bitspersample);
return 0;
}
break;
case PREDICTOR_FLOATINGPOINT:
if (td->td_sampleformat != SAMPLEFORMAT_IEEEFP) {
TIFFErrorExt(tif->tif_clientdata, module,
"Floating point \"Predictor\" not supported with %d data format",
td->td_sampleformat);
return 0;
}
if (td->td_bitspersample != 16
&& td->td_bitspersample != 24
&& td->td_bitspersample != 32
&& td->td_bitspersample != 64) { /* Should 64 be allowed? */
TIFFErrorExt(tif->tif_clientdata, module,
"Floating point \"Predictor\" not supported with %d-bit samples",
td->td_bitspersample);
return 0;
}
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"\"Predictor\" value %d not supported",
sp->predictor);
return 0;
}
sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
/*
* Calculate the scanline/tile-width size in bytes.
*/
if (isTiled(tif))
sp->rowsize = TIFFTileRowSize(tif);
else
sp->rowsize = TIFFScanlineSize(tif);
if (sp->rowsize == 0)
return 0;
return 1;
}
static int
PredictorSetupDecode(TIFF* tif)
{
TIFFPredictorState* sp = PredictorState(tif);
TIFFDirectory* td = &tif->tif_dir;
if (!(*sp->setupdecode)(tif) || !PredictorSetup(tif))
return 0;
if (sp->predictor == 2) {
switch (td->td_bitspersample) {
case 8: sp->decodepfunc = horAcc8; break;
case 16: sp->decodepfunc = horAcc16; break;
case 32: sp->decodepfunc = horAcc32; break;
}
/*
* Override default decoding method with one that does the
* predictor stuff.
*/
if( tif->tif_decoderow != PredictorDecodeRow )
{
sp->decoderow = tif->tif_decoderow;
tif->tif_decoderow = PredictorDecodeRow;
sp->decodestrip = tif->tif_decodestrip;
tif->tif_decodestrip = PredictorDecodeTile;
sp->decodetile = tif->tif_decodetile;
tif->tif_decodetile = PredictorDecodeTile;
}
/*
* If the data is horizontally differenced 16-bit data that
* requires byte-swapping, then it must be byte swapped before
* the accumulation step. We do this with a special-purpose
* routine and override the normal post decoding logic that
* the library setup when the directory was read.
*/
if (tif->tif_flags & TIFF_SWAB) {
if (sp->decodepfunc == horAcc16) {
sp->decodepfunc = swabHorAcc16;
tif->tif_postdecode = _TIFFNoPostDecode;
} else if (sp->decodepfunc == horAcc32) {
sp->decodepfunc = swabHorAcc32;
tif->tif_postdecode = _TIFFNoPostDecode;
}
}
}
else if (sp->predictor == 3) {
sp->decodepfunc = fpAcc;
/*
* Override default decoding method with one that does the
* predictor stuff.
*/
if( tif->tif_decoderow != PredictorDecodeRow )
{
sp->decoderow = tif->tif_decoderow;
tif->tif_decoderow = PredictorDecodeRow;
sp->decodestrip = tif->tif_decodestrip;
tif->tif_decodestrip = PredictorDecodeTile;
sp->decodetile = tif->tif_decodetile;
tif->tif_decodetile = PredictorDecodeTile;
}
/*
* The data should not be swapped outside of the floating
* point predictor, the accumulation routine should return
* byres in the native order.
*/
if (tif->tif_flags & TIFF_SWAB) {
tif->tif_postdecode = _TIFFNoPostDecode;
}
/*
* Allocate buffer to keep the decoded bytes before
* rearranging in the right order
*/
}
return 1;
}
static int
PredictorSetupEncode(TIFF* tif)
{
TIFFPredictorState* sp = PredictorState(tif);
TIFFDirectory* td = &tif->tif_dir;
if (!(*sp->setupencode)(tif) || !PredictorSetup(tif))
return 0;
if (sp->predictor == 2) {
switch (td->td_bitspersample) {
case 8: sp->encodepfunc = horDiff8; break;
case 16: sp->encodepfunc = horDiff16; break;
case 32: sp->encodepfunc = horDiff32; break;
}
/*
* Override default encoding method with one that does the
* predictor stuff.
*/
if( tif->tif_encoderow != PredictorEncodeRow )
{
sp->encoderow = tif->tif_encoderow;
tif->tif_encoderow = PredictorEncodeRow;
sp->encodestrip = tif->tif_encodestrip;
tif->tif_encodestrip = PredictorEncodeTile;
sp->encodetile = tif->tif_encodetile;
tif->tif_encodetile = PredictorEncodeTile;
}
/*
* If the data is horizontally differenced 16-bit data that
* requires byte-swapping, then it must be byte swapped after
* the differentiation step. We do this with a special-purpose
* routine and override the normal post decoding logic that
* the library setup when the directory was read.
*/
if (tif->tif_flags & TIFF_SWAB) {
if (sp->encodepfunc == horDiff16) {
sp->encodepfunc = swabHorDiff16;
tif->tif_postdecode = _TIFFNoPostDecode;
} else if (sp->encodepfunc == horDiff32) {
sp->encodepfunc = swabHorDiff32;
tif->tif_postdecode = _TIFFNoPostDecode;
}
}
}
else if (sp->predictor == 3) {
sp->encodepfunc = fpDiff;
/*
* Override default encoding method with one that does the
* predictor stuff.
*/
if( tif->tif_encoderow != PredictorEncodeRow )
{
sp->encoderow = tif->tif_encoderow;
tif->tif_encoderow = PredictorEncodeRow;
sp->encodestrip = tif->tif_encodestrip;
tif->tif_encodestrip = PredictorEncodeTile;
sp->encodetile = tif->tif_encodetile;
tif->tif_encodetile = PredictorEncodeTile;
}
}
return 1;
}
#define REPEAT4(n, op) \
switch (n) { \
default: { tmsize_t i; for (i = n-4; i > 0; i--) { op; } } \
case 4: op; \
case 3: op; \
case 2: op; \
case 1: op; \
case 0: ; \
}
/* Remarks related to C standard compliance in all below functions : */
/* - to avoid any undefined behaviour, we only operate on unsigned types */
/* since the behaviour of "overflows" is defined (wrap over) */
/* - when storing into the byte stream, we explicitly mask with 0xff so */
/* as to make icc -check=conversions happy (not necessary by the standard) */
static void
horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
unsigned char* cp = (unsigned char*) cp0;
assert((cc%stride)==0);
if (cc > stride) {
/*
* Pipeline the most common cases.
*/
if (stride == 3) {
unsigned int cr = cp[0];
unsigned int cg = cp[1];
unsigned int cb = cp[2];
cc -= 3;
cp += 3;
while (cc>0) {
cp[0] = (unsigned char) ((cr += cp[0]) & 0xff);
cp[1] = (unsigned char) ((cg += cp[1]) & 0xff);
cp[2] = (unsigned char) ((cb += cp[2]) & 0xff);
cc -= 3;
cp += 3;
}
} else if (stride == 4) {
unsigned int cr = cp[0];
unsigned int cg = cp[1];
unsigned int cb = cp[2];
unsigned int ca = cp[3];
cc -= 4;
cp += 4;
while (cc>0) {
cp[0] = (unsigned char) ((cr += cp[0]) & 0xff);
cp[1] = (unsigned char) ((cg += cp[1]) & 0xff);
cp[2] = (unsigned char) ((cb += cp[2]) & 0xff);
cp[3] = (unsigned char) ((ca += cp[3]) & 0xff);
cc -= 4;
cp += 4;
}
} else {
cc -= stride;
do {
REPEAT4(stride, cp[stride] =
(unsigned char) ((cp[stride] + *cp) & 0xff); cp++)
cc -= stride;
} while (cc>0);
}
}
}
static void
swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
TIFFSwabArrayOfShort(wp, wc);
horAcc16(tif, cp0, cc);
}
static void
horAcc16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
assert((cc%(2*stride))==0);
if (wc > stride) {
wc -= stride;
do {
REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] + (unsigned int)wp[0]) & 0xffff); wp++)
wc -= stride;
} while (wc > 0);
}
}
static void
swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
TIFFSwabArrayOfLong(wp, wc);
horAcc32(tif, cp0, cc);
}
static void
horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
assert((cc%(4*stride))==0);
if (wc > stride) {
wc -= stride;
do {
REPEAT4(stride, wp[stride] += wp[0]; wp++)
wc -= stride;
} while (wc > 0);
}
}
/*
* Floating point predictor accumulation routine.
*/
static void
fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32 bps = tif->tif_dir.td_bitspersample / 8;
tmsize_t wc = cc / bps;
tmsize_t count = cc;
uint8 *cp = (uint8 *) cp0;
uint8 *tmp = (uint8 *)_TIFFmalloc(cc);
assert((cc%(bps*stride))==0);
if (!tmp)
return;
while (count > stride) {
REPEAT4(stride, cp[stride] =
(unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++)
count -= stride;
}
_TIFFmemcpy(tmp, cp0, cc);
cp = (uint8 *) cp0;
for (count = 0; count < wc; count++) {
uint32 byte;
for (byte = 0; byte < bps; byte++) {
#if WORDS_BIGENDIAN
cp[bps * count + byte] = tmp[byte * wc + count];
#else
cp[bps * count + byte] =
tmp[(bps - byte - 1) * wc + count];
#endif
}
}
_TIFFfree(tmp);
}
/*
* Decode a scanline and apply the predictor routine.
*/
static int
PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->decoderow != NULL);
assert(sp->decodepfunc != NULL);
if ((*sp->decoderow)(tif, op0, occ0, s)) {
(*sp->decodepfunc)(tif, op0, occ0);
return 1;
} else
return 0;
}
/*
* Decode a tile/strip and apply the predictor routine.
* Note that horizontal differencing must be done on a
* row-by-row basis. The width of a "row" has already
* been calculated at pre-decode time according to the
* strip/tile dimensions.
*/
static int
PredictorDecodeTile(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->decodetile != NULL);
if ((*sp->decodetile)(tif, op0, occ0, s)) {
tmsize_t rowsize = sp->rowsize;
assert(rowsize > 0);
assert((occ0%rowsize)==0);
assert(sp->decodepfunc != NULL);
while (occ0 > 0) {
(*sp->decodepfunc)(tif, op0, rowsize);
occ0 -= rowsize;
op0 += rowsize;
}
return 1;
} else
return 0;
}
static void
horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
unsigned char* cp = (unsigned char*) cp0;
assert((cc%stride)==0);
if (cc > stride) {
cc -= stride;
/*
* Pipeline the most common cases.
*/
if (stride == 3) {
unsigned int r1, g1, b1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
do {
r1 = cp[3]; cp[3] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[4]; cp[4] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[5]; cp[5] = (unsigned char)((b1-b2)&0xff); b2 = b1;
cp += 3;
} while ((cc -= 3) > 0);
} else if (stride == 4) {
unsigned int r1, g1, b1, a1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
unsigned int a2 = cp[3];
do {
r1 = cp[4]; cp[4] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[5]; cp[5] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[6]; cp[6] = (unsigned char)((b1-b2)&0xff); b2 = b1;
a1 = cp[7]; cp[7] = (unsigned char)((a1-a2)&0xff); a2 = a1;
cp += 4;
} while ((cc -= 4) > 0);
} else {
cp += cc - 1;
do {
REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
} while ((cc -= stride) > 0);
}
}
}
static void
horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
uint16 *wp = (uint16*) cp0;
tmsize_t wc = cc/2;
assert((cc%(2*stride))==0);
if (wc > stride) {
wc -= stride;
wp += wc - 1;
do {
REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] - (unsigned int)wp[0]) & 0xffff); wp--)
wc -= stride;
} while (wc > 0);
}
}
static void
swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
horDiff16(tif, cp0, cc);
TIFFSwabArrayOfShort(wp, wc);
}
static void
horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
uint32 *wp = (uint32*) cp0;
tmsize_t wc = cc/4;
assert((cc%(4*stride))==0);
if (wc > stride) {
wc -= stride;
wp += wc - 1;
do {
REPEAT4(stride, wp[stride] -= wp[0]; wp--)
wc -= stride;
} while (wc > 0);
}
}
static void
swabHorDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
horDiff32(tif, cp0, cc);
TIFFSwabArrayOfLong(wp, wc);
}
/*
* Floating point predictor differencing routine.
*/
static void
fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32 bps = tif->tif_dir.td_bitspersample / 8;
tmsize_t wc = cc / bps;
tmsize_t count;
uint8 *cp = (uint8 *) cp0;
uint8 *tmp = (uint8 *)_TIFFmalloc(cc);
assert((cc%(bps*stride))==0);
if (!tmp)
return;
_TIFFmemcpy(tmp, cp0, cc);
for (count = 0; count < wc; count++) {
uint32 byte;
for (byte = 0; byte < bps; byte++) {
#if WORDS_BIGENDIAN
cp[byte * wc + count] = tmp[bps * count + byte];
#else
cp[(bps - byte - 1) * wc + count] =
tmp[bps * count + byte];
#endif
}
}
_TIFFfree(tmp);
cp = (uint8 *) cp0;
cp += cc - stride - 1;
for (count = cc; count > stride; count -= stride)
REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
}
static int
PredictorEncodeRow(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encoderow != NULL);
/* XXX horizontal differencing alters user's data XXX */
(*sp->encodepfunc)(tif, bp, cc);
return (*sp->encoderow)(tif, bp, cc, s);
}
static int
PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s)
{
static const char module[] = "PredictorEncodeTile";
TIFFPredictorState *sp = PredictorState(tif);
uint8 *working_copy;
tmsize_t cc = cc0, rowsize;
unsigned char* bp;
int result_code;
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encodetile != NULL);
/*
* Do predictor manipulation in a working buffer to avoid altering
* the callers buffer. http://trac.osgeo.org/gdal/ticket/1965
*/
working_copy = (uint8*) _TIFFmalloc(cc0);
if( working_copy == NULL )
{
TIFFErrorExt(tif->tif_clientdata, module,
"Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.",
cc0 );
return 0;
}
memcpy( working_copy, bp0, cc0 );
bp = working_copy;
rowsize = sp->rowsize;
assert(rowsize > 0);
assert((cc0%rowsize)==0);
while (cc > 0) {
(*sp->encodepfunc)(tif, bp, rowsize);
cc -= rowsize;
bp += rowsize;
}
result_code = (*sp->encodetile)(tif, working_copy, cc0, s);
_TIFFfree( working_copy );
return result_code;
}
#define FIELD_PREDICTOR (FIELD_CODEC+0) /* XXX */
static const TIFFField predictFields[] = {
{ TIFFTAG_PREDICTOR, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UINT16, FIELD_PREDICTOR, FALSE, FALSE, "Predictor", NULL },
};
static int
PredictorVSetField(TIFF* tif, uint32 tag, va_list ap)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->vsetparent != NULL);
switch (tag) {
case TIFFTAG_PREDICTOR:
sp->predictor = (uint16) va_arg(ap, uint16_vap);
TIFFSetFieldBit(tif, FIELD_PREDICTOR);
break;
default:
return (*sp->vsetparent)(tif, tag, ap);
}
tif->tif_flags |= TIFF_DIRTYDIRECT;
return 1;
}
static int
PredictorVGetField(TIFF* tif, uint32 tag, va_list ap)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->vgetparent != NULL);
switch (tag) {
case TIFFTAG_PREDICTOR:
*va_arg(ap, uint16*) = (uint16)sp->predictor;
break;
default:
return (*sp->vgetparent)(tif, tag, ap);
}
return 1;
}
static void
PredictorPrintDir(TIFF* tif, FILE* fd, long flags)
{
TIFFPredictorState* sp = PredictorState(tif);
(void) flags;
if (TIFFFieldSet(tif,FIELD_PREDICTOR)) {
fprintf(fd, " Predictor: ");
switch (sp->predictor) {
case 1: fprintf(fd, "none "); break;
case 2: fprintf(fd, "horizontal differencing "); break;
case 3: fprintf(fd, "floating point predictor "); break;
}
fprintf(fd, "%u (0x%x)\n", sp->predictor, sp->predictor);
}
if (sp->printdir)
(*sp->printdir)(tif, fd, flags);
}
int
TIFFPredictorInit(TIFF* tif)
{
TIFFPredictorState* sp = PredictorState(tif);
assert(sp != 0);
/*
* Merge codec-specific tag information.
*/
if (!_TIFFMergeFields(tif, predictFields,
TIFFArrayCount(predictFields))) {
TIFFErrorExt(tif->tif_clientdata, "TIFFPredictorInit",
"Merging Predictor codec-specific tags failed");
return 0;
}
/*
* Override parent get/set field methods.
*/
sp->vgetparent = tif->tif_tagmethods.vgetfield;
tif->tif_tagmethods.vgetfield =
PredictorVGetField;/* hook for predictor tag */
sp->vsetparent = tif->tif_tagmethods.vsetfield;
tif->tif_tagmethods.vsetfield =
PredictorVSetField;/* hook for predictor tag */
sp->printdir = tif->tif_tagmethods.printdir;
tif->tif_tagmethods.printdir =
PredictorPrintDir; /* hook for predictor tag */
sp->setupdecode = tif->tif_setupdecode;
tif->tif_setupdecode = PredictorSetupDecode;
sp->setupencode = tif->tif_setupencode;
tif->tif_setupencode = PredictorSetupEncode;
sp->predictor = 1; /* default value */
sp->encodepfunc = NULL; /* no predictor routine */
sp->decodepfunc = NULL; /* no predictor routine */
return 1;
}
int
TIFFPredictorCleanup(TIFF* tif)
{
TIFFPredictorState* sp = PredictorState(tif);
assert(sp != 0);
tif->tif_tagmethods.vgetfield = sp->vgetparent;
tif->tif_tagmethods.vsetfield = sp->vsetparent;
tif->tif_tagmethods.printdir = sp->printdir;
tif->tif_setupdecode = sp->setupdecode;
tif->tif_setupencode = sp->setupencode;
return 1;
}
/* vim: set ts=8 sts=8 sw=8 noet: */
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5476_1 |
crossvul-cpp_data_bad_4735_0 | /*
* NetLabel CIPSO/IPv4 Support
*
* This file defines the CIPSO/IPv4 functions for the NetLabel system. The
* NetLabel system manages static and dynamic label mappings for network
* protocols such as CIPSO and RIPSO.
*
* Author: Paul Moore <paul.moore@hp.com>
*
*/
/*
* (c) Copyright Hewlett-Packard Development Company, L.P., 2006
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* 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/types.h>
#include <linux/socket.h>
#include <linux/string.h>
#include <linux/skbuff.h>
#include <linux/audit.h>
#include <net/sock.h>
#include <net/netlink.h>
#include <net/genetlink.h>
#include <net/netlabel.h>
#include <net/cipso_ipv4.h>
#include "netlabel_user.h"
#include "netlabel_cipso_v4.h"
/* Argument struct for cipso_v4_doi_walk() */
struct netlbl_cipsov4_doiwalk_arg {
struct netlink_callback *nl_cb;
struct sk_buff *skb;
u32 seq;
};
/* NetLabel Generic NETLINK CIPSOv4 family */
static struct genl_family netlbl_cipsov4_gnl_family = {
.id = GENL_ID_GENERATE,
.hdrsize = 0,
.name = NETLBL_NLTYPE_CIPSOV4_NAME,
.version = NETLBL_PROTO_VERSION,
.maxattr = NLBL_CIPSOV4_A_MAX,
};
/* NetLabel Netlink attribute policy */
static struct nla_policy netlbl_cipsov4_genl_policy[NLBL_CIPSOV4_A_MAX + 1] = {
[NLBL_CIPSOV4_A_DOI] = { .type = NLA_U32 },
[NLBL_CIPSOV4_A_MTYPE] = { .type = NLA_U32 },
[NLBL_CIPSOV4_A_TAG] = { .type = NLA_U8 },
[NLBL_CIPSOV4_A_TAGLST] = { .type = NLA_NESTED },
[NLBL_CIPSOV4_A_MLSLVLLOC] = { .type = NLA_U32 },
[NLBL_CIPSOV4_A_MLSLVLREM] = { .type = NLA_U32 },
[NLBL_CIPSOV4_A_MLSLVL] = { .type = NLA_NESTED },
[NLBL_CIPSOV4_A_MLSLVLLST] = { .type = NLA_NESTED },
[NLBL_CIPSOV4_A_MLSCATLOC] = { .type = NLA_U32 },
[NLBL_CIPSOV4_A_MLSCATREM] = { .type = NLA_U32 },
[NLBL_CIPSOV4_A_MLSCAT] = { .type = NLA_NESTED },
[NLBL_CIPSOV4_A_MLSCATLST] = { .type = NLA_NESTED },
};
/*
* Helper Functions
*/
/**
* netlbl_cipsov4_doi_free - Frees a CIPSO V4 DOI definition
* @entry: the entry's RCU field
*
* Description:
* This function is designed to be used as a callback to the call_rcu()
* function so that the memory allocated to the DOI definition can be released
* safely.
*
*/
static void netlbl_cipsov4_doi_free(struct rcu_head *entry)
{
struct cipso_v4_doi *ptr;
ptr = container_of(entry, struct cipso_v4_doi, rcu);
switch (ptr->type) {
case CIPSO_V4_MAP_STD:
kfree(ptr->map.std->lvl.cipso);
kfree(ptr->map.std->lvl.local);
kfree(ptr->map.std->cat.cipso);
kfree(ptr->map.std->cat.local);
break;
}
kfree(ptr);
}
/**
* netlbl_cipsov4_add_common - Parse the common sections of a ADD message
* @info: the Generic NETLINK info block
* @doi_def: the CIPSO V4 DOI definition
*
* Description:
* Parse the common sections of a ADD message and fill in the related values
* in @doi_def. Returns zero on success, negative values on failure.
*
*/
static int netlbl_cipsov4_add_common(struct genl_info *info,
struct cipso_v4_doi *doi_def)
{
struct nlattr *nla;
int nla_rem;
u32 iter = 0;
doi_def->doi = nla_get_u32(info->attrs[NLBL_CIPSOV4_A_DOI]);
if (nla_validate_nested(info->attrs[NLBL_CIPSOV4_A_TAGLST],
NLBL_CIPSOV4_A_MAX,
netlbl_cipsov4_genl_policy) != 0)
return -EINVAL;
nla_for_each_nested(nla, info->attrs[NLBL_CIPSOV4_A_TAGLST], nla_rem)
if (nla->nla_type == NLBL_CIPSOV4_A_TAG) {
if (iter > CIPSO_V4_TAG_MAXCNT)
return -EINVAL;
doi_def->tags[iter++] = nla_get_u8(nla);
}
if (iter < CIPSO_V4_TAG_MAXCNT)
doi_def->tags[iter] = CIPSO_V4_TAG_INVALID;
return 0;
}
/*
* NetLabel Command Handlers
*/
/**
* netlbl_cipsov4_add_std - Adds a CIPSO V4 DOI definition
* @info: the Generic NETLINK info block
*
* Description:
* Create a new CIPSO_V4_MAP_STD DOI definition based on the given ADD message
* and add it to the CIPSO V4 engine. Return zero on success and non-zero on
* error.
*
*/
static int netlbl_cipsov4_add_std(struct genl_info *info)
{
int ret_val = -EINVAL;
struct cipso_v4_doi *doi_def = NULL;
struct nlattr *nla_a;
struct nlattr *nla_b;
int nla_a_rem;
int nla_b_rem;
u32 iter;
if (!info->attrs[NLBL_CIPSOV4_A_TAGLST] ||
!info->attrs[NLBL_CIPSOV4_A_MLSLVLLST])
return -EINVAL;
if (nla_validate_nested(info->attrs[NLBL_CIPSOV4_A_MLSLVLLST],
NLBL_CIPSOV4_A_MAX,
netlbl_cipsov4_genl_policy) != 0)
return -EINVAL;
doi_def = kmalloc(sizeof(*doi_def), GFP_KERNEL);
if (doi_def == NULL)
return -ENOMEM;
doi_def->map.std = kzalloc(sizeof(*doi_def->map.std), GFP_KERNEL);
if (doi_def->map.std == NULL) {
ret_val = -ENOMEM;
goto add_std_failure;
}
doi_def->type = CIPSO_V4_MAP_STD;
ret_val = netlbl_cipsov4_add_common(info, doi_def);
if (ret_val != 0)
goto add_std_failure;
ret_val = -EINVAL;
nla_for_each_nested(nla_a,
info->attrs[NLBL_CIPSOV4_A_MLSLVLLST],
nla_a_rem)
if (nla_a->nla_type == NLBL_CIPSOV4_A_MLSLVL) {
if (nla_validate_nested(nla_a,
NLBL_CIPSOV4_A_MAX,
netlbl_cipsov4_genl_policy) != 0)
goto add_std_failure;
nla_for_each_nested(nla_b, nla_a, nla_b_rem)
switch (nla_b->nla_type) {
case NLBL_CIPSOV4_A_MLSLVLLOC:
if (nla_get_u32(nla_b) >
CIPSO_V4_MAX_LOC_LVLS)
goto add_std_failure;
if (nla_get_u32(nla_b) >=
doi_def->map.std->lvl.local_size)
doi_def->map.std->lvl.local_size =
nla_get_u32(nla_b) + 1;
break;
case NLBL_CIPSOV4_A_MLSLVLREM:
if (nla_get_u32(nla_b) >
CIPSO_V4_MAX_REM_LVLS)
goto add_std_failure;
if (nla_get_u32(nla_b) >=
doi_def->map.std->lvl.cipso_size)
doi_def->map.std->lvl.cipso_size =
nla_get_u32(nla_b) + 1;
break;
}
}
doi_def->map.std->lvl.local = kcalloc(doi_def->map.std->lvl.local_size,
sizeof(u32),
GFP_KERNEL);
if (doi_def->map.std->lvl.local == NULL) {
ret_val = -ENOMEM;
goto add_std_failure;
}
doi_def->map.std->lvl.cipso = kcalloc(doi_def->map.std->lvl.cipso_size,
sizeof(u32),
GFP_KERNEL);
if (doi_def->map.std->lvl.cipso == NULL) {
ret_val = -ENOMEM;
goto add_std_failure;
}
for (iter = 0; iter < doi_def->map.std->lvl.local_size; iter++)
doi_def->map.std->lvl.local[iter] = CIPSO_V4_INV_LVL;
for (iter = 0; iter < doi_def->map.std->lvl.cipso_size; iter++)
doi_def->map.std->lvl.cipso[iter] = CIPSO_V4_INV_LVL;
nla_for_each_nested(nla_a,
info->attrs[NLBL_CIPSOV4_A_MLSLVLLST],
nla_a_rem)
if (nla_a->nla_type == NLBL_CIPSOV4_A_MLSLVL) {
struct nlattr *lvl_loc;
struct nlattr *lvl_rem;
lvl_loc = nla_find_nested(nla_a,
NLBL_CIPSOV4_A_MLSLVLLOC);
lvl_rem = nla_find_nested(nla_a,
NLBL_CIPSOV4_A_MLSLVLREM);
if (lvl_loc == NULL || lvl_rem == NULL)
goto add_std_failure;
doi_def->map.std->lvl.local[nla_get_u32(lvl_loc)] =
nla_get_u32(lvl_rem);
doi_def->map.std->lvl.cipso[nla_get_u32(lvl_rem)] =
nla_get_u32(lvl_loc);
}
if (info->attrs[NLBL_CIPSOV4_A_MLSCATLST]) {
if (nla_validate_nested(info->attrs[NLBL_CIPSOV4_A_MLSCATLST],
NLBL_CIPSOV4_A_MAX,
netlbl_cipsov4_genl_policy) != 0)
goto add_std_failure;
nla_for_each_nested(nla_a,
info->attrs[NLBL_CIPSOV4_A_MLSCATLST],
nla_a_rem)
if (nla_a->nla_type == NLBL_CIPSOV4_A_MLSCAT) {
if (nla_validate_nested(nla_a,
NLBL_CIPSOV4_A_MAX,
netlbl_cipsov4_genl_policy) != 0)
goto add_std_failure;
nla_for_each_nested(nla_b, nla_a, nla_b_rem)
switch (nla_b->nla_type) {
case NLBL_CIPSOV4_A_MLSCATLOC:
if (nla_get_u32(nla_b) >
CIPSO_V4_MAX_LOC_CATS)
goto add_std_failure;
if (nla_get_u32(nla_b) >=
doi_def->map.std->cat.local_size)
doi_def->map.std->cat.local_size =
nla_get_u32(nla_b) + 1;
break;
case NLBL_CIPSOV4_A_MLSCATREM:
if (nla_get_u32(nla_b) >
CIPSO_V4_MAX_REM_CATS)
goto add_std_failure;
if (nla_get_u32(nla_b) >=
doi_def->map.std->cat.cipso_size)
doi_def->map.std->cat.cipso_size =
nla_get_u32(nla_b) + 1;
break;
}
}
doi_def->map.std->cat.local = kcalloc(
doi_def->map.std->cat.local_size,
sizeof(u32),
GFP_KERNEL);
if (doi_def->map.std->cat.local == NULL) {
ret_val = -ENOMEM;
goto add_std_failure;
}
doi_def->map.std->cat.cipso = kcalloc(
doi_def->map.std->cat.cipso_size,
sizeof(u32),
GFP_KERNEL);
if (doi_def->map.std->cat.cipso == NULL) {
ret_val = -ENOMEM;
goto add_std_failure;
}
for (iter = 0; iter < doi_def->map.std->cat.local_size; iter++)
doi_def->map.std->cat.local[iter] = CIPSO_V4_INV_CAT;
for (iter = 0; iter < doi_def->map.std->cat.cipso_size; iter++)
doi_def->map.std->cat.cipso[iter] = CIPSO_V4_INV_CAT;
nla_for_each_nested(nla_a,
info->attrs[NLBL_CIPSOV4_A_MLSCATLST],
nla_a_rem)
if (nla_a->nla_type == NLBL_CIPSOV4_A_MLSCAT) {
struct nlattr *cat_loc;
struct nlattr *cat_rem;
cat_loc = nla_find_nested(nla_a,
NLBL_CIPSOV4_A_MLSCATLOC);
cat_rem = nla_find_nested(nla_a,
NLBL_CIPSOV4_A_MLSCATREM);
if (cat_loc == NULL || cat_rem == NULL)
goto add_std_failure;
doi_def->map.std->cat.local[
nla_get_u32(cat_loc)] =
nla_get_u32(cat_rem);
doi_def->map.std->cat.cipso[
nla_get_u32(cat_rem)] =
nla_get_u32(cat_loc);
}
}
ret_val = cipso_v4_doi_add(doi_def);
if (ret_val != 0)
goto add_std_failure;
return 0;
add_std_failure:
if (doi_def)
netlbl_cipsov4_doi_free(&doi_def->rcu);
return ret_val;
}
/**
* netlbl_cipsov4_add_pass - Adds a CIPSO V4 DOI definition
* @info: the Generic NETLINK info block
*
* Description:
* Create a new CIPSO_V4_MAP_PASS DOI definition based on the given ADD message
* and add it to the CIPSO V4 engine. Return zero on success and non-zero on
* error.
*
*/
static int netlbl_cipsov4_add_pass(struct genl_info *info)
{
int ret_val;
struct cipso_v4_doi *doi_def = NULL;
if (!info->attrs[NLBL_CIPSOV4_A_TAGLST])
return -EINVAL;
doi_def = kmalloc(sizeof(*doi_def), GFP_KERNEL);
if (doi_def == NULL)
return -ENOMEM;
doi_def->type = CIPSO_V4_MAP_PASS;
ret_val = netlbl_cipsov4_add_common(info, doi_def);
if (ret_val != 0)
goto add_pass_failure;
ret_val = cipso_v4_doi_add(doi_def);
if (ret_val != 0)
goto add_pass_failure;
return 0;
add_pass_failure:
netlbl_cipsov4_doi_free(&doi_def->rcu);
return ret_val;
}
/**
* netlbl_cipsov4_add - Handle an ADD message
* @skb: the NETLINK buffer
* @info: the Generic NETLINK info block
*
* Description:
* Create a new DOI definition based on the given ADD message and add it to the
* CIPSO V4 engine. Returns zero on success, negative values on failure.
*
*/
static int netlbl_cipsov4_add(struct sk_buff *skb, struct genl_info *info)
{
int ret_val = -EINVAL;
u32 type;
u32 doi;
const char *type_str = "(unknown)";
struct audit_buffer *audit_buf;
struct netlbl_audit audit_info;
if (!info->attrs[NLBL_CIPSOV4_A_DOI] ||
!info->attrs[NLBL_CIPSOV4_A_MTYPE])
return -EINVAL;
doi = nla_get_u32(info->attrs[NLBL_CIPSOV4_A_DOI]);
netlbl_netlink_auditinfo(skb, &audit_info);
type = nla_get_u32(info->attrs[NLBL_CIPSOV4_A_MTYPE]);
switch (type) {
case CIPSO_V4_MAP_STD:
type_str = "std";
ret_val = netlbl_cipsov4_add_std(info);
break;
case CIPSO_V4_MAP_PASS:
type_str = "pass";
ret_val = netlbl_cipsov4_add_pass(info);
break;
}
audit_buf = netlbl_audit_start_common(AUDIT_MAC_CIPSOV4_ADD,
&audit_info);
if (audit_buf != NULL) {
audit_log_format(audit_buf,
" cipso_doi=%u cipso_type=%s res=%u",
doi,
type_str,
ret_val == 0 ? 1 : 0);
audit_log_end(audit_buf);
}
return ret_val;
}
/**
* netlbl_cipsov4_list - Handle a LIST message
* @skb: the NETLINK buffer
* @info: the Generic NETLINK info block
*
* Description:
* Process a user generated LIST message and respond accordingly. While the
* response message generated by the kernel is straightforward, determining
* before hand the size of the buffer to allocate is not (we have to generate
* the message to know the size). In order to keep this function sane what we
* do is allocate a buffer of NLMSG_GOODSIZE and try to fit the response in
* that size, if we fail then we restart with a larger buffer and try again.
* We continue in this manner until we hit a limit of failed attempts then we
* give up and just send an error message. Returns zero on success and
* negative values on error.
*
*/
static int netlbl_cipsov4_list(struct sk_buff *skb, struct genl_info *info)
{
int ret_val;
struct sk_buff *ans_skb = NULL;
u32 nlsze_mult = 1;
void *data;
u32 doi;
struct nlattr *nla_a;
struct nlattr *nla_b;
struct cipso_v4_doi *doi_def;
u32 iter;
if (!info->attrs[NLBL_CIPSOV4_A_DOI]) {
ret_val = -EINVAL;
goto list_failure;
}
list_start:
ans_skb = nlmsg_new(NLMSG_DEFAULT_SIZE * nlsze_mult, GFP_KERNEL);
if (ans_skb == NULL) {
ret_val = -ENOMEM;
goto list_failure;
}
data = genlmsg_put_reply(ans_skb, info, &netlbl_cipsov4_gnl_family,
0, NLBL_CIPSOV4_C_LIST);
if (data == NULL) {
ret_val = -ENOMEM;
goto list_failure;
}
doi = nla_get_u32(info->attrs[NLBL_CIPSOV4_A_DOI]);
rcu_read_lock();
doi_def = cipso_v4_doi_getdef(doi);
if (doi_def == NULL) {
ret_val = -EINVAL;
goto list_failure;
}
ret_val = nla_put_u32(ans_skb, NLBL_CIPSOV4_A_MTYPE, doi_def->type);
if (ret_val != 0)
goto list_failure_lock;
nla_a = nla_nest_start(ans_skb, NLBL_CIPSOV4_A_TAGLST);
if (nla_a == NULL) {
ret_val = -ENOMEM;
goto list_failure_lock;
}
for (iter = 0;
iter < CIPSO_V4_TAG_MAXCNT &&
doi_def->tags[iter] != CIPSO_V4_TAG_INVALID;
iter++) {
ret_val = nla_put_u8(ans_skb,
NLBL_CIPSOV4_A_TAG,
doi_def->tags[iter]);
if (ret_val != 0)
goto list_failure_lock;
}
nla_nest_end(ans_skb, nla_a);
switch (doi_def->type) {
case CIPSO_V4_MAP_STD:
nla_a = nla_nest_start(ans_skb, NLBL_CIPSOV4_A_MLSLVLLST);
if (nla_a == NULL) {
ret_val = -ENOMEM;
goto list_failure_lock;
}
for (iter = 0;
iter < doi_def->map.std->lvl.local_size;
iter++) {
if (doi_def->map.std->lvl.local[iter] ==
CIPSO_V4_INV_LVL)
continue;
nla_b = nla_nest_start(ans_skb, NLBL_CIPSOV4_A_MLSLVL);
if (nla_b == NULL) {
ret_val = -ENOMEM;
goto list_retry;
}
ret_val = nla_put_u32(ans_skb,
NLBL_CIPSOV4_A_MLSLVLLOC,
iter);
if (ret_val != 0)
goto list_retry;
ret_val = nla_put_u32(ans_skb,
NLBL_CIPSOV4_A_MLSLVLREM,
doi_def->map.std->lvl.local[iter]);
if (ret_val != 0)
goto list_retry;
nla_nest_end(ans_skb, nla_b);
}
nla_nest_end(ans_skb, nla_a);
nla_a = nla_nest_start(ans_skb, NLBL_CIPSOV4_A_MLSCATLST);
if (nla_a == NULL) {
ret_val = -ENOMEM;
goto list_retry;
}
for (iter = 0;
iter < doi_def->map.std->cat.local_size;
iter++) {
if (doi_def->map.std->cat.local[iter] ==
CIPSO_V4_INV_CAT)
continue;
nla_b = nla_nest_start(ans_skb, NLBL_CIPSOV4_A_MLSCAT);
if (nla_b == NULL) {
ret_val = -ENOMEM;
goto list_retry;
}
ret_val = nla_put_u32(ans_skb,
NLBL_CIPSOV4_A_MLSCATLOC,
iter);
if (ret_val != 0)
goto list_retry;
ret_val = nla_put_u32(ans_skb,
NLBL_CIPSOV4_A_MLSCATREM,
doi_def->map.std->cat.local[iter]);
if (ret_val != 0)
goto list_retry;
nla_nest_end(ans_skb, nla_b);
}
nla_nest_end(ans_skb, nla_a);
break;
}
rcu_read_unlock();
genlmsg_end(ans_skb, data);
ret_val = genlmsg_reply(ans_skb, info);
if (ret_val != 0)
goto list_failure;
return 0;
list_retry:
/* XXX - this limit is a guesstimate */
if (nlsze_mult < 4) {
rcu_read_unlock();
kfree_skb(ans_skb);
nlsze_mult++;
goto list_start;
}
list_failure_lock:
rcu_read_unlock();
list_failure:
kfree_skb(ans_skb);
return ret_val;
}
/**
* netlbl_cipsov4_listall_cb - cipso_v4_doi_walk() callback for LISTALL
* @doi_def: the CIPSOv4 DOI definition
* @arg: the netlbl_cipsov4_doiwalk_arg structure
*
* Description:
* This function is designed to be used as a callback to the
* cipso_v4_doi_walk() function for use in generating a response for a LISTALL
* message. Returns the size of the message on success, negative values on
* failure.
*
*/
static int netlbl_cipsov4_listall_cb(struct cipso_v4_doi *doi_def, void *arg)
{
int ret_val = -ENOMEM;
struct netlbl_cipsov4_doiwalk_arg *cb_arg = arg;
void *data;
data = genlmsg_put(cb_arg->skb, NETLINK_CB(cb_arg->nl_cb->skb).pid,
cb_arg->seq, &netlbl_cipsov4_gnl_family,
NLM_F_MULTI, NLBL_CIPSOV4_C_LISTALL);
if (data == NULL)
goto listall_cb_failure;
ret_val = nla_put_u32(cb_arg->skb, NLBL_CIPSOV4_A_DOI, doi_def->doi);
if (ret_val != 0)
goto listall_cb_failure;
ret_val = nla_put_u32(cb_arg->skb,
NLBL_CIPSOV4_A_MTYPE,
doi_def->type);
if (ret_val != 0)
goto listall_cb_failure;
return genlmsg_end(cb_arg->skb, data);
listall_cb_failure:
genlmsg_cancel(cb_arg->skb, data);
return ret_val;
}
/**
* netlbl_cipsov4_listall - Handle a LISTALL message
* @skb: the NETLINK buffer
* @cb: the NETLINK callback
*
* Description:
* Process a user generated LISTALL message and respond accordingly. Returns
* zero on success and negative values on error.
*
*/
static int netlbl_cipsov4_listall(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct netlbl_cipsov4_doiwalk_arg cb_arg;
int doi_skip = cb->args[0];
cb_arg.nl_cb = cb;
cb_arg.skb = skb;
cb_arg.seq = cb->nlh->nlmsg_seq;
cipso_v4_doi_walk(&doi_skip, netlbl_cipsov4_listall_cb, &cb_arg);
cb->args[0] = doi_skip;
return skb->len;
}
/**
* netlbl_cipsov4_remove - Handle a REMOVE message
* @skb: the NETLINK buffer
* @info: the Generic NETLINK info block
*
* Description:
* Process a user generated REMOVE message and respond accordingly. Returns
* zero on success, negative values on failure.
*
*/
static int netlbl_cipsov4_remove(struct sk_buff *skb, struct genl_info *info)
{
int ret_val = -EINVAL;
u32 doi = 0;
struct audit_buffer *audit_buf;
struct netlbl_audit audit_info;
if (!info->attrs[NLBL_CIPSOV4_A_DOI])
return -EINVAL;
doi = nla_get_u32(info->attrs[NLBL_CIPSOV4_A_DOI]);
netlbl_netlink_auditinfo(skb, &audit_info);
ret_val = cipso_v4_doi_remove(doi,
&audit_info,
netlbl_cipsov4_doi_free);
audit_buf = netlbl_audit_start_common(AUDIT_MAC_CIPSOV4_DEL,
&audit_info);
if (audit_buf != NULL) {
audit_log_format(audit_buf,
" cipso_doi=%u res=%u",
doi,
ret_val == 0 ? 1 : 0);
audit_log_end(audit_buf);
}
return ret_val;
}
/*
* NetLabel Generic NETLINK Command Definitions
*/
static struct genl_ops netlbl_cipsov4_genl_c_add = {
.cmd = NLBL_CIPSOV4_C_ADD,
.flags = GENL_ADMIN_PERM,
.policy = netlbl_cipsov4_genl_policy,
.doit = netlbl_cipsov4_add,
.dumpit = NULL,
};
static struct genl_ops netlbl_cipsov4_genl_c_remove = {
.cmd = NLBL_CIPSOV4_C_REMOVE,
.flags = GENL_ADMIN_PERM,
.policy = netlbl_cipsov4_genl_policy,
.doit = netlbl_cipsov4_remove,
.dumpit = NULL,
};
static struct genl_ops netlbl_cipsov4_genl_c_list = {
.cmd = NLBL_CIPSOV4_C_LIST,
.flags = 0,
.policy = netlbl_cipsov4_genl_policy,
.doit = netlbl_cipsov4_list,
.dumpit = NULL,
};
static struct genl_ops netlbl_cipsov4_genl_c_listall = {
.cmd = NLBL_CIPSOV4_C_LISTALL,
.flags = 0,
.policy = netlbl_cipsov4_genl_policy,
.doit = NULL,
.dumpit = netlbl_cipsov4_listall,
};
/*
* NetLabel Generic NETLINK Protocol Functions
*/
/**
* netlbl_cipsov4_genl_init - Register the CIPSOv4 NetLabel component
*
* Description:
* Register the CIPSOv4 packet NetLabel component with the Generic NETLINK
* mechanism. Returns zero on success, negative values on failure.
*
*/
int netlbl_cipsov4_genl_init(void)
{
int ret_val;
ret_val = genl_register_family(&netlbl_cipsov4_gnl_family);
if (ret_val != 0)
return ret_val;
ret_val = genl_register_ops(&netlbl_cipsov4_gnl_family,
&netlbl_cipsov4_genl_c_add);
if (ret_val != 0)
return ret_val;
ret_val = genl_register_ops(&netlbl_cipsov4_gnl_family,
&netlbl_cipsov4_genl_c_remove);
if (ret_val != 0)
return ret_val;
ret_val = genl_register_ops(&netlbl_cipsov4_gnl_family,
&netlbl_cipsov4_genl_c_list);
if (ret_val != 0)
return ret_val;
ret_val = genl_register_ops(&netlbl_cipsov4_gnl_family,
&netlbl_cipsov4_genl_c_listall);
if (ret_val != 0)
return ret_val;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4735_0 |
crossvul-cpp_data_good_4907_1 | /*
* linux/fs/proc/root.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* proc root directory handling functions
*/
#include <asm/uaccess.h>
#include <linux/errno.h>
#include <linux/time.h>
#include <linux/proc_fs.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/module.h>
#include <linux/bitops.h>
#include <linux/user_namespace.h>
#include <linux/mount.h>
#include <linux/pid_namespace.h>
#include <linux/parser.h>
#include "internal.h"
static int proc_test_super(struct super_block *sb, void *data)
{
return sb->s_fs_info == data;
}
static int proc_set_super(struct super_block *sb, void *data)
{
int err = set_anon_super(sb, NULL);
if (!err) {
struct pid_namespace *ns = (struct pid_namespace *)data;
sb->s_fs_info = get_pid_ns(ns);
}
return err;
}
enum {
Opt_gid, Opt_hidepid, Opt_err,
};
static const match_table_t tokens = {
{Opt_hidepid, "hidepid=%u"},
{Opt_gid, "gid=%u"},
{Opt_err, NULL},
};
static int proc_parse_options(char *options, struct pid_namespace *pid)
{
char *p;
substring_t args[MAX_OPT_ARGS];
int option;
if (!options)
return 1;
while ((p = strsep(&options, ",")) != NULL) {
int token;
if (!*p)
continue;
args[0].to = args[0].from = NULL;
token = match_token(p, tokens, args);
switch (token) {
case Opt_gid:
if (match_int(&args[0], &option))
return 0;
pid->pid_gid = make_kgid(current_user_ns(), option);
break;
case Opt_hidepid:
if (match_int(&args[0], &option))
return 0;
if (option < 0 || option > 2) {
pr_err("proc: hidepid value must be between 0 and 2.\n");
return 0;
}
pid->hide_pid = option;
break;
default:
pr_err("proc: unrecognized mount option \"%s\" "
"or missing value\n", p);
return 0;
}
}
return 1;
}
int proc_remount(struct super_block *sb, int *flags, char *data)
{
struct pid_namespace *pid = sb->s_fs_info;
sync_filesystem(sb);
return !proc_parse_options(data, pid);
}
static struct dentry *proc_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
int err;
struct super_block *sb;
struct pid_namespace *ns;
char *options;
if (flags & MS_KERNMOUNT) {
ns = (struct pid_namespace *)data;
options = NULL;
} else {
ns = task_active_pid_ns(current);
options = data;
/* Does the mounter have privilege over the pid namespace? */
if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN))
return ERR_PTR(-EPERM);
}
sb = sget(fs_type, proc_test_super, proc_set_super, flags, ns);
if (IS_ERR(sb))
return ERR_CAST(sb);
/*
* procfs isn't actually a stacking filesystem; however, there is
* too much magic going on inside it to permit stacking things on
* top of it
*/
sb->s_stack_depth = FILESYSTEM_MAX_STACK_DEPTH;
if (!proc_parse_options(options, ns)) {
deactivate_locked_super(sb);
return ERR_PTR(-EINVAL);
}
if (!sb->s_root) {
err = proc_fill_super(sb);
if (err) {
deactivate_locked_super(sb);
return ERR_PTR(err);
}
sb->s_flags |= MS_ACTIVE;
/* User space would break if executables appear on proc */
sb->s_iflags |= SB_I_NOEXEC;
}
return dget(sb->s_root);
}
static void proc_kill_sb(struct super_block *sb)
{
struct pid_namespace *ns;
ns = (struct pid_namespace *)sb->s_fs_info;
if (ns->proc_self)
dput(ns->proc_self);
if (ns->proc_thread_self)
dput(ns->proc_thread_self);
kill_anon_super(sb);
put_pid_ns(ns);
}
static struct file_system_type proc_fs_type = {
.name = "proc",
.mount = proc_mount,
.kill_sb = proc_kill_sb,
.fs_flags = FS_USERNS_VISIBLE | FS_USERNS_MOUNT,
};
void __init proc_root_init(void)
{
int err;
proc_init_inodecache();
err = register_filesystem(&proc_fs_type);
if (err)
return;
proc_self_init();
proc_thread_self_init();
proc_symlink("mounts", NULL, "self/mounts");
proc_net_init();
#ifdef CONFIG_SYSVIPC
proc_mkdir("sysvipc", NULL);
#endif
proc_mkdir("fs", NULL);
proc_mkdir("driver", NULL);
proc_create_mount_point("fs/nfsd"); /* somewhere for the nfsd filesystem to be mounted */
#if defined(CONFIG_SUN_OPENPROMFS) || defined(CONFIG_SUN_OPENPROMFS_MODULE)
/* just give it a mountpoint */
proc_create_mount_point("openprom");
#endif
proc_tty_init();
proc_mkdir("bus", NULL);
proc_sys_init();
}
static int proc_root_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat
)
{
generic_fillattr(d_inode(dentry), stat);
stat->nlink = proc_root.nlink + nr_processes();
return 0;
}
static struct dentry *proc_root_lookup(struct inode * dir, struct dentry * dentry, unsigned int flags)
{
if (!proc_pid_lookup(dir, dentry, flags))
return NULL;
return proc_lookup(dir, dentry, flags);
}
static int proc_root_readdir(struct file *file, struct dir_context *ctx)
{
if (ctx->pos < FIRST_PROCESS_ENTRY) {
int error = proc_readdir(file, ctx);
if (unlikely(error <= 0))
return error;
ctx->pos = FIRST_PROCESS_ENTRY;
}
return proc_pid_readdir(file, ctx);
}
/*
* The root /proc directory is special, as it has the
* <pid> directories. Thus we don't use the generic
* directory handling functions for that..
*/
static const struct file_operations proc_root_operations = {
.read = generic_read_dir,
.iterate_shared = proc_root_readdir,
.llseek = generic_file_llseek,
};
/*
* proc root can do almost nothing..
*/
static const struct inode_operations proc_root_inode_operations = {
.lookup = proc_root_lookup,
.getattr = proc_root_getattr,
};
/*
* This is the root "inode" in the /proc tree..
*/
struct proc_dir_entry proc_root = {
.low_ino = PROC_ROOT_INO,
.namelen = 5,
.mode = S_IFDIR | S_IRUGO | S_IXUGO,
.nlink = 2,
.count = ATOMIC_INIT(1),
.proc_iops = &proc_root_inode_operations,
.proc_fops = &proc_root_operations,
.parent = &proc_root,
.subdir = RB_ROOT,
.name = "/proc",
};
int pid_ns_prepare_proc(struct pid_namespace *ns)
{
struct vfsmount *mnt;
mnt = kern_mount_data(&proc_fs_type, ns);
if (IS_ERR(mnt))
return PTR_ERR(mnt);
ns->proc_mnt = mnt;
return 0;
}
void pid_ns_release_proc(struct pid_namespace *ns)
{
kern_unmount(ns->proc_mnt);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4907_1 |
crossvul-cpp_data_bad_5477_1 | /* $Id$ */
/*
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
/*
* TIFF Library.
*
* Predictor Tag Support (used by multiple codecs).
*/
#include "tiffiop.h"
#include "tif_predict.h"
#define PredictorState(tif) ((TIFFPredictorState*) (tif)->tif_data)
static int horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc);
static int horAcc16(TIFF* tif, uint8* cp0, tmsize_t cc);
static int horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc);
static int swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc);
static int swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc);
static int horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc);
static int horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc);
static int horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc);
static int swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc);
static int swabHorDiff32(TIFF* tif, uint8* cp0, tmsize_t cc);
static int fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc);
static int fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc);
static int PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s);
static int PredictorDecodeTile(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s);
static int PredictorEncodeRow(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s);
static int PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s);
static int
PredictorSetup(TIFF* tif)
{
static const char module[] = "PredictorSetup";
TIFFPredictorState* sp = PredictorState(tif);
TIFFDirectory* td = &tif->tif_dir;
switch (sp->predictor) /* no differencing */
{
case PREDICTOR_NONE:
return 1;
case PREDICTOR_HORIZONTAL:
if (td->td_bitspersample != 8
&& td->td_bitspersample != 16
&& td->td_bitspersample != 32) {
TIFFErrorExt(tif->tif_clientdata, module,
"Horizontal differencing \"Predictor\" not supported with %d-bit samples",
td->td_bitspersample);
return 0;
}
break;
case PREDICTOR_FLOATINGPOINT:
if (td->td_sampleformat != SAMPLEFORMAT_IEEEFP) {
TIFFErrorExt(tif->tif_clientdata, module,
"Floating point \"Predictor\" not supported with %d data format",
td->td_sampleformat);
return 0;
}
if (td->td_bitspersample != 16
&& td->td_bitspersample != 24
&& td->td_bitspersample != 32
&& td->td_bitspersample != 64) { /* Should 64 be allowed? */
TIFFErrorExt(tif->tif_clientdata, module,
"Floating point \"Predictor\" not supported with %d-bit samples",
td->td_bitspersample);
return 0;
}
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"\"Predictor\" value %d not supported",
sp->predictor);
return 0;
}
sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
/*
* Calculate the scanline/tile-width size in bytes.
*/
if (isTiled(tif))
sp->rowsize = TIFFTileRowSize(tif);
else
sp->rowsize = TIFFScanlineSize(tif);
if (sp->rowsize == 0)
return 0;
return 1;
}
static int
PredictorSetupDecode(TIFF* tif)
{
TIFFPredictorState* sp = PredictorState(tif);
TIFFDirectory* td = &tif->tif_dir;
if (!(*sp->setupdecode)(tif) || !PredictorSetup(tif))
return 0;
if (sp->predictor == 2) {
switch (td->td_bitspersample) {
case 8: sp->decodepfunc = horAcc8; break;
case 16: sp->decodepfunc = horAcc16; break;
case 32: sp->decodepfunc = horAcc32; break;
}
/*
* Override default decoding method with one that does the
* predictor stuff.
*/
if( tif->tif_decoderow != PredictorDecodeRow )
{
sp->decoderow = tif->tif_decoderow;
tif->tif_decoderow = PredictorDecodeRow;
sp->decodestrip = tif->tif_decodestrip;
tif->tif_decodestrip = PredictorDecodeTile;
sp->decodetile = tif->tif_decodetile;
tif->tif_decodetile = PredictorDecodeTile;
}
/*
* If the data is horizontally differenced 16-bit data that
* requires byte-swapping, then it must be byte swapped before
* the accumulation step. We do this with a special-purpose
* routine and override the normal post decoding logic that
* the library setup when the directory was read.
*/
if (tif->tif_flags & TIFF_SWAB) {
if (sp->decodepfunc == horAcc16) {
sp->decodepfunc = swabHorAcc16;
tif->tif_postdecode = _TIFFNoPostDecode;
} else if (sp->decodepfunc == horAcc32) {
sp->decodepfunc = swabHorAcc32;
tif->tif_postdecode = _TIFFNoPostDecode;
}
}
}
else if (sp->predictor == 3) {
sp->decodepfunc = fpAcc;
/*
* Override default decoding method with one that does the
* predictor stuff.
*/
if( tif->tif_decoderow != PredictorDecodeRow )
{
sp->decoderow = tif->tif_decoderow;
tif->tif_decoderow = PredictorDecodeRow;
sp->decodestrip = tif->tif_decodestrip;
tif->tif_decodestrip = PredictorDecodeTile;
sp->decodetile = tif->tif_decodetile;
tif->tif_decodetile = PredictorDecodeTile;
}
/*
* The data should not be swapped outside of the floating
* point predictor, the accumulation routine should return
* byres in the native order.
*/
if (tif->tif_flags & TIFF_SWAB) {
tif->tif_postdecode = _TIFFNoPostDecode;
}
/*
* Allocate buffer to keep the decoded bytes before
* rearranging in the right order
*/
}
return 1;
}
static int
PredictorSetupEncode(TIFF* tif)
{
TIFFPredictorState* sp = PredictorState(tif);
TIFFDirectory* td = &tif->tif_dir;
if (!(*sp->setupencode)(tif) || !PredictorSetup(tif))
return 0;
if (sp->predictor == 2) {
switch (td->td_bitspersample) {
case 8: sp->encodepfunc = horDiff8; break;
case 16: sp->encodepfunc = horDiff16; break;
case 32: sp->encodepfunc = horDiff32; break;
}
/*
* Override default encoding method with one that does the
* predictor stuff.
*/
if( tif->tif_encoderow != PredictorEncodeRow )
{
sp->encoderow = tif->tif_encoderow;
tif->tif_encoderow = PredictorEncodeRow;
sp->encodestrip = tif->tif_encodestrip;
tif->tif_encodestrip = PredictorEncodeTile;
sp->encodetile = tif->tif_encodetile;
tif->tif_encodetile = PredictorEncodeTile;
}
/*
* If the data is horizontally differenced 16-bit data that
* requires byte-swapping, then it must be byte swapped after
* the differentiation step. We do this with a special-purpose
* routine and override the normal post decoding logic that
* the library setup when the directory was read.
*/
if (tif->tif_flags & TIFF_SWAB) {
if (sp->encodepfunc == horDiff16) {
sp->encodepfunc = swabHorDiff16;
tif->tif_postdecode = _TIFFNoPostDecode;
} else if (sp->encodepfunc == horDiff32) {
sp->encodepfunc = swabHorDiff32;
tif->tif_postdecode = _TIFFNoPostDecode;
}
}
}
else if (sp->predictor == 3) {
sp->encodepfunc = fpDiff;
/*
* Override default encoding method with one that does the
* predictor stuff.
*/
if( tif->tif_encoderow != PredictorEncodeRow )
{
sp->encoderow = tif->tif_encoderow;
tif->tif_encoderow = PredictorEncodeRow;
sp->encodestrip = tif->tif_encodestrip;
tif->tif_encodestrip = PredictorEncodeTile;
sp->encodetile = tif->tif_encodetile;
tif->tif_encodetile = PredictorEncodeTile;
}
}
return 1;
}
#define REPEAT4(n, op) \
switch (n) { \
default: { tmsize_t i; for (i = n-4; i > 0; i--) { op; } } \
case 4: op; \
case 3: op; \
case 2: op; \
case 1: op; \
case 0: ; \
}
/* Remarks related to C standard compliance in all below functions : */
/* - to avoid any undefined behaviour, we only operate on unsigned types */
/* since the behaviour of "overflows" is defined (wrap over) */
/* - when storing into the byte stream, we explicitly mask with 0xff so */
/* as to make icc -check=conversions happy (not necessary by the standard) */
static int
horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
unsigned char* cp = (unsigned char*) cp0;
if((cc%stride)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horAcc8",
"%s", "(cc%stride)!=0");
return 0;
}
if (cc > stride) {
/*
* Pipeline the most common cases.
*/
if (stride == 3) {
unsigned int cr = cp[0];
unsigned int cg = cp[1];
unsigned int cb = cp[2];
cc -= 3;
cp += 3;
while (cc>0) {
cp[0] = (unsigned char) ((cr += cp[0]) & 0xff);
cp[1] = (unsigned char) ((cg += cp[1]) & 0xff);
cp[2] = (unsigned char) ((cb += cp[2]) & 0xff);
cc -= 3;
cp += 3;
}
} else if (stride == 4) {
unsigned int cr = cp[0];
unsigned int cg = cp[1];
unsigned int cb = cp[2];
unsigned int ca = cp[3];
cc -= 4;
cp += 4;
while (cc>0) {
cp[0] = (unsigned char) ((cr += cp[0]) & 0xff);
cp[1] = (unsigned char) ((cg += cp[1]) & 0xff);
cp[2] = (unsigned char) ((cb += cp[2]) & 0xff);
cp[3] = (unsigned char) ((ca += cp[3]) & 0xff);
cc -= 4;
cp += 4;
}
} else {
cc -= stride;
do {
REPEAT4(stride, cp[stride] =
(unsigned char) ((cp[stride] + *cp) & 0xff); cp++)
cc -= stride;
} while (cc>0);
}
}
return 1;
}
static int
swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
TIFFSwabArrayOfShort(wp, wc);
return horAcc16(tif, cp0, cc);
}
static int
horAcc16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
if((cc%(2*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horAcc16",
"%s", "cc%(2*stride))!=0");
return 0;
}
if (wc > stride) {
wc -= stride;
do {
REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] + (unsigned int)wp[0]) & 0xffff); wp++)
wc -= stride;
} while (wc > 0);
}
return 1;
}
static int
swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
TIFFSwabArrayOfLong(wp, wc);
return horAcc32(tif, cp0, cc);
}
static int
horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
if((cc%(4*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horAcc32",
"%s", "cc%(4*stride))!=0");
return 0;
}
if (wc > stride) {
wc -= stride;
do {
REPEAT4(stride, wp[stride] += wp[0]; wp++)
wc -= stride;
} while (wc > 0);
}
return 1;
}
/*
* Floating point predictor accumulation routine.
*/
static int
fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32 bps = tif->tif_dir.td_bitspersample / 8;
tmsize_t wc = cc / bps;
tmsize_t count = cc;
uint8 *cp = (uint8 *) cp0;
uint8 *tmp = (uint8 *)_TIFFmalloc(cc);
if(cc%(bps*stride)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "fpAcc",
"%s", "cc%(bps*stride))!=0");
return 0;
}
if (!tmp)
return 0;
while (count > stride) {
REPEAT4(stride, cp[stride] =
(unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++)
count -= stride;
}
_TIFFmemcpy(tmp, cp0, cc);
cp = (uint8 *) cp0;
for (count = 0; count < wc; count++) {
uint32 byte;
for (byte = 0; byte < bps; byte++) {
#if WORDS_BIGENDIAN
cp[bps * count + byte] = tmp[byte * wc + count];
#else
cp[bps * count + byte] =
tmp[(bps - byte - 1) * wc + count];
#endif
}
}
_TIFFfree(tmp);
return 1;
}
/*
* Decode a scanline and apply the predictor routine.
*/
static int
PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->decoderow != NULL);
assert(sp->decodepfunc != NULL);
if ((*sp->decoderow)(tif, op0, occ0, s)) {
return (*sp->decodepfunc)(tif, op0, occ0);
} else
return 0;
}
/*
* Decode a tile/strip and apply the predictor routine.
* Note that horizontal differencing must be done on a
* row-by-row basis. The width of a "row" has already
* been calculated at pre-decode time according to the
* strip/tile dimensions.
*/
static int
PredictorDecodeTile(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->decodetile != NULL);
if ((*sp->decodetile)(tif, op0, occ0, s)) {
tmsize_t rowsize = sp->rowsize;
assert(rowsize > 0);
if((occ0%rowsize) !=0)
{
TIFFErrorExt(tif->tif_clientdata, "PredictorDecodeTile",
"%s", "occ0%rowsize != 0");
return 0;
}
assert(sp->decodepfunc != NULL);
while (occ0 > 0) {
if( !(*sp->decodepfunc)(tif, op0, rowsize) )
return 0;
occ0 -= rowsize;
op0 += rowsize;
}
return 1;
} else
return 0;
}
static int
horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
unsigned char* cp = (unsigned char*) cp0;
if((cc%stride)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horDiff8",
"%s", "(cc%stride)!=0");
return 0;
}
if (cc > stride) {
cc -= stride;
/*
* Pipeline the most common cases.
*/
if (stride == 3) {
unsigned int r1, g1, b1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
do {
r1 = cp[3]; cp[3] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[4]; cp[4] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[5]; cp[5] = (unsigned char)((b1-b2)&0xff); b2 = b1;
cp += 3;
} while ((cc -= 3) > 0);
} else if (stride == 4) {
unsigned int r1, g1, b1, a1;
unsigned int r2 = cp[0];
unsigned int g2 = cp[1];
unsigned int b2 = cp[2];
unsigned int a2 = cp[3];
do {
r1 = cp[4]; cp[4] = (unsigned char)((r1-r2)&0xff); r2 = r1;
g1 = cp[5]; cp[5] = (unsigned char)((g1-g2)&0xff); g2 = g1;
b1 = cp[6]; cp[6] = (unsigned char)((b1-b2)&0xff); b2 = b1;
a1 = cp[7]; cp[7] = (unsigned char)((a1-a2)&0xff); a2 = a1;
cp += 4;
} while ((cc -= 4) > 0);
} else {
cp += cc - 1;
do {
REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
} while ((cc -= stride) > 0);
}
}
return 1;
}
static int
horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
uint16 *wp = (uint16*) cp0;
tmsize_t wc = cc/2;
if((cc%(2*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horDiff8",
"%s", "(cc%(2*stride))!=0");
return 0;
}
if (wc > stride) {
wc -= stride;
wp += wc - 1;
do {
REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] - (unsigned int)wp[0]) & 0xffff); wp--)
wc -= stride;
} while (wc > 0);
}
return 1;
}
static int
swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
if( !horDiff16(tif, cp0, cc) )
return 0;
TIFFSwabArrayOfShort(wp, wc);
return 1;
}
static int
horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
uint32 *wp = (uint32*) cp0;
tmsize_t wc = cc/4;
if((cc%(4*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horDiff32",
"%s", "(cc%(4*stride))!=0");
return 0;
}
if (wc > stride) {
wc -= stride;
wp += wc - 1;
do {
REPEAT4(stride, wp[stride] -= wp[0]; wp--)
wc -= stride;
} while (wc > 0);
}
return 1;
}
static int
swabHorDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
if( !horDiff32(tif, cp0, cc) )
return 0;
TIFFSwabArrayOfLong(wp, wc);
return 1;
}
/*
* Floating point predictor differencing routine.
*/
static int
fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32 bps = tif->tif_dir.td_bitspersample / 8;
tmsize_t wc = cc / bps;
tmsize_t count;
uint8 *cp = (uint8 *) cp0;
uint8 *tmp = (uint8 *)_TIFFmalloc(cc);
if((cc%(bps*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "fpDiff",
"%s", "(cc%(bps*stride))!=0");
return 0;
}
if (!tmp)
return 0;
_TIFFmemcpy(tmp, cp0, cc);
for (count = 0; count < wc; count++) {
uint32 byte;
for (byte = 0; byte < bps; byte++) {
#if WORDS_BIGENDIAN
cp[byte * wc + count] = tmp[bps * count + byte];
#else
cp[(bps - byte - 1) * wc + count] =
tmp[bps * count + byte];
#endif
}
}
_TIFFfree(tmp);
cp = (uint8 *) cp0;
cp += cc - stride - 1;
for (count = cc; count > stride; count -= stride)
REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
return 1;
}
static int
PredictorEncodeRow(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encoderow != NULL);
/* XXX horizontal differencing alters user's data XXX */
if( !(*sp->encodepfunc)(tif, bp, cc) )
return 0;
return (*sp->encoderow)(tif, bp, cc, s);
}
static int
PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s)
{
static const char module[] = "PredictorEncodeTile";
TIFFPredictorState *sp = PredictorState(tif);
uint8 *working_copy;
tmsize_t cc = cc0, rowsize;
unsigned char* bp;
int result_code;
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encodetile != NULL);
/*
* Do predictor manipulation in a working buffer to avoid altering
* the callers buffer. http://trac.osgeo.org/gdal/ticket/1965
*/
working_copy = (uint8*) _TIFFmalloc(cc0);
if( working_copy == NULL )
{
TIFFErrorExt(tif->tif_clientdata, module,
"Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.",
cc0 );
return 0;
}
memcpy( working_copy, bp0, cc0 );
bp = working_copy;
rowsize = sp->rowsize;
assert(rowsize > 0);
if((cc0%rowsize)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "PredictorEncodeTile",
"%s", "(cc0%rowsize)!=0");
return 0;
}
while (cc > 0) {
(*sp->encodepfunc)(tif, bp, rowsize);
cc -= rowsize;
bp += rowsize;
}
result_code = (*sp->encodetile)(tif, working_copy, cc0, s);
_TIFFfree( working_copy );
return result_code;
}
#define FIELD_PREDICTOR (FIELD_CODEC+0) /* XXX */
static const TIFFField predictFields[] = {
{ TIFFTAG_PREDICTOR, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UINT16, FIELD_PREDICTOR, FALSE, FALSE, "Predictor", NULL },
};
static int
PredictorVSetField(TIFF* tif, uint32 tag, va_list ap)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->vsetparent != NULL);
switch (tag) {
case TIFFTAG_PREDICTOR:
sp->predictor = (uint16) va_arg(ap, uint16_vap);
TIFFSetFieldBit(tif, FIELD_PREDICTOR);
break;
default:
return (*sp->vsetparent)(tif, tag, ap);
}
tif->tif_flags |= TIFF_DIRTYDIRECT;
return 1;
}
static int
PredictorVGetField(TIFF* tif, uint32 tag, va_list ap)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->vgetparent != NULL);
switch (tag) {
case TIFFTAG_PREDICTOR:
*va_arg(ap, uint16*) = (uint16)sp->predictor;
break;
default:
return (*sp->vgetparent)(tif, tag, ap);
}
return 1;
}
static void
PredictorPrintDir(TIFF* tif, FILE* fd, long flags)
{
TIFFPredictorState* sp = PredictorState(tif);
(void) flags;
if (TIFFFieldSet(tif,FIELD_PREDICTOR)) {
fprintf(fd, " Predictor: ");
switch (sp->predictor) {
case 1: fprintf(fd, "none "); break;
case 2: fprintf(fd, "horizontal differencing "); break;
case 3: fprintf(fd, "floating point predictor "); break;
}
fprintf(fd, "%u (0x%x)\n", sp->predictor, sp->predictor);
}
if (sp->printdir)
(*sp->printdir)(tif, fd, flags);
}
int
TIFFPredictorInit(TIFF* tif)
{
TIFFPredictorState* sp = PredictorState(tif);
assert(sp != 0);
/*
* Merge codec-specific tag information.
*/
if (!_TIFFMergeFields(tif, predictFields,
TIFFArrayCount(predictFields))) {
TIFFErrorExt(tif->tif_clientdata, "TIFFPredictorInit",
"Merging Predictor codec-specific tags failed");
return 0;
}
/*
* Override parent get/set field methods.
*/
sp->vgetparent = tif->tif_tagmethods.vgetfield;
tif->tif_tagmethods.vgetfield =
PredictorVGetField;/* hook for predictor tag */
sp->vsetparent = tif->tif_tagmethods.vsetfield;
tif->tif_tagmethods.vsetfield =
PredictorVSetField;/* hook for predictor tag */
sp->printdir = tif->tif_tagmethods.printdir;
tif->tif_tagmethods.printdir =
PredictorPrintDir; /* hook for predictor tag */
sp->setupdecode = tif->tif_setupdecode;
tif->tif_setupdecode = PredictorSetupDecode;
sp->setupencode = tif->tif_setupencode;
tif->tif_setupencode = PredictorSetupEncode;
sp->predictor = 1; /* default value */
sp->encodepfunc = NULL; /* no predictor routine */
sp->decodepfunc = NULL; /* no predictor routine */
return 1;
}
int
TIFFPredictorCleanup(TIFF* tif)
{
TIFFPredictorState* sp = PredictorState(tif);
assert(sp != 0);
tif->tif_tagmethods.vgetfield = sp->vgetparent;
tif->tif_tagmethods.vsetfield = sp->vsetparent;
tif->tif_tagmethods.printdir = sp->printdir;
tif->tif_setupdecode = sp->setupdecode;
tif->tif_setupencode = sp->setupencode;
return 1;
}
/* vim: set ts=8 sts=8 sw=8 noet: */
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5477_1 |
crossvul-cpp_data_bad_410_0 | /* util.c
*
* Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
* 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
*
* You may distribute under the terms of either the GNU General Public
* License or the Artistic License, as specified in the README file.
*
*/
/*
* 'Very useful, no doubt, that was to Saruman; yet it seems that he was
* not content.' --Gandalf to Pippin
*
* [p.598 of _The Lord of the Rings_, III/xi: "The Palantír"]
*/
/* This file contains assorted utility routines.
* Which is a polite way of saying any stuff that people couldn't think of
* a better place for. Amongst other things, it includes the warning and
* dieing stuff, plus wrappers for malloc code.
*/
#include "EXTERN.h"
#define PERL_IN_UTIL_C
#include "perl.h"
#include "reentr.h"
#if defined(USE_PERLIO)
#include "perliol.h" /* For PerlIOUnix_refcnt */
#endif
#ifndef PERL_MICRO
#include <signal.h>
#ifndef SIG_ERR
# define SIG_ERR ((Sighandler_t) -1)
#endif
#endif
#include <math.h>
#include <stdlib.h>
#ifdef __Lynx__
/* Missing protos on LynxOS */
int putenv(char *);
#endif
#ifdef __amigaos__
# include "amigaos4/amigaio.h"
#endif
#ifdef HAS_SELECT
# ifdef I_SYS_SELECT
# include <sys/select.h>
# endif
#endif
#ifdef USE_C_BACKTRACE
# ifdef I_BFD
# define USE_BFD
# ifdef PERL_DARWIN
# undef USE_BFD /* BFD is useless in OS X. */
# endif
# ifdef USE_BFD
# include <bfd.h>
# endif
# endif
# ifdef I_DLFCN
# include <dlfcn.h>
# endif
# ifdef I_EXECINFO
# include <execinfo.h>
# endif
#endif
#ifdef PERL_DEBUG_READONLY_COW
# include <sys/mman.h>
#endif
#define FLUSH
/* NOTE: Do not call the next three routines directly. Use the macros
* in handy.h, so that we can easily redefine everything to do tracking of
* allocated hunks back to the original New to track down any memory leaks.
* XXX This advice seems to be widely ignored :-( --AD August 1996.
*/
#if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
# define ALWAYS_NEED_THX
#endif
#if defined(PERL_TRACK_MEMPOOL) && defined(PERL_DEBUG_READONLY_COW)
static void
S_maybe_protect_rw(pTHX_ struct perl_memory_debug_header *header)
{
if (header->readonly
&& mprotect(header, header->size, PROT_READ|PROT_WRITE))
Perl_warn(aTHX_ "mprotect for COW string %p %lu failed with %d",
header, header->size, errno);
}
static void
S_maybe_protect_ro(pTHX_ struct perl_memory_debug_header *header)
{
if (header->readonly
&& mprotect(header, header->size, PROT_READ))
Perl_warn(aTHX_ "mprotect RW for COW string %p %lu failed with %d",
header, header->size, errno);
}
# define maybe_protect_rw(foo) S_maybe_protect_rw(aTHX_ foo)
# define maybe_protect_ro(foo) S_maybe_protect_ro(aTHX_ foo)
#else
# define maybe_protect_rw(foo) NOOP
# define maybe_protect_ro(foo) NOOP
#endif
#if defined(PERL_TRACK_MEMPOOL) || defined(PERL_DEBUG_READONLY_COW)
/* Use memory_debug_header */
# define USE_MDH
# if (defined(PERL_POISON) && defined(PERL_TRACK_MEMPOOL)) \
|| defined(PERL_DEBUG_READONLY_COW)
# define MDH_HAS_SIZE
# endif
#endif
/* paranoid version of system's malloc() */
Malloc_t
Perl_safesysmalloc(MEM_SIZE size)
{
#ifdef ALWAYS_NEED_THX
dTHX;
#endif
Malloc_t ptr;
#ifdef USE_MDH
if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size)
goto out_of_memory;
size += PERL_MEMORY_DEBUG_HEADER_SIZE;
#endif
#ifdef DEBUGGING
if ((SSize_t)size < 0)
Perl_croak_nocontext("panic: malloc, size=%" UVuf, (UV) size);
#endif
if (!size) size = 1; /* malloc(0) is NASTY on our system */
#ifdef PERL_DEBUG_READONLY_COW
if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
perror("mmap failed");
abort();
}
#else
ptr = (Malloc_t)PerlMem_malloc(size?size:1);
#endif
PERL_ALLOC_CHECK(ptr);
if (ptr != NULL) {
#ifdef USE_MDH
struct perl_memory_debug_header *const header
= (struct perl_memory_debug_header *)ptr;
#endif
#ifdef PERL_POISON
PoisonNew(((char *)ptr), size, char);
#endif
#ifdef PERL_TRACK_MEMPOOL
header->interpreter = aTHX;
/* Link us into the list. */
header->prev = &PL_memory_debug_header;
header->next = PL_memory_debug_header.next;
PL_memory_debug_header.next = header;
maybe_protect_rw(header->next);
header->next->prev = header;
maybe_protect_ro(header->next);
# ifdef PERL_DEBUG_READONLY_COW
header->readonly = 0;
# endif
#endif
#ifdef MDH_HAS_SIZE
header->size = size;
#endif
ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
}
else {
#ifdef USE_MDH
out_of_memory:
#endif
{
#ifndef ALWAYS_NEED_THX
dTHX;
#endif
if (PL_nomemok)
ptr = NULL;
else
croak_no_mem();
}
}
return ptr;
}
/* paranoid version of system's realloc() */
Malloc_t
Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
{
#ifdef ALWAYS_NEED_THX
dTHX;
#endif
Malloc_t ptr;
#ifdef PERL_DEBUG_READONLY_COW
const MEM_SIZE oldsize = where
? ((struct perl_memory_debug_header *)((char *)where - PERL_MEMORY_DEBUG_HEADER_SIZE))->size
: 0;
#endif
if (!size) {
safesysfree(where);
ptr = NULL;
}
else if (!where) {
ptr = safesysmalloc(size);
}
else {
#ifdef USE_MDH
where = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size)
goto out_of_memory;
size += PERL_MEMORY_DEBUG_HEADER_SIZE;
{
struct perl_memory_debug_header *const header
= (struct perl_memory_debug_header *)where;
# ifdef PERL_TRACK_MEMPOOL
if (header->interpreter != aTHX) {
Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
header->interpreter, aTHX);
}
assert(header->next->prev == header);
assert(header->prev->next == header);
# ifdef PERL_POISON
if (header->size > size) {
const MEM_SIZE freed_up = header->size - size;
char *start_of_freed = ((char *)where) + size;
PoisonFree(start_of_freed, freed_up, char);
}
# endif
# endif
# ifdef MDH_HAS_SIZE
header->size = size;
# endif
}
#endif
#ifdef DEBUGGING
if ((SSize_t)size < 0)
Perl_croak_nocontext("panic: realloc, size=%" UVuf, (UV)size);
#endif
#ifdef PERL_DEBUG_READONLY_COW
if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
perror("mmap failed");
abort();
}
Copy(where,ptr,oldsize < size ? oldsize : size,char);
if (munmap(where, oldsize)) {
perror("munmap failed");
abort();
}
#else
ptr = (Malloc_t)PerlMem_realloc(where,size);
#endif
PERL_ALLOC_CHECK(ptr);
/* MUST do this fixup first, before doing ANYTHING else, as anything else
might allocate memory/free/move memory, and until we do the fixup, it
may well be chasing (and writing to) free memory. */
if (ptr != NULL) {
#ifdef PERL_TRACK_MEMPOOL
struct perl_memory_debug_header *const header
= (struct perl_memory_debug_header *)ptr;
# ifdef PERL_POISON
if (header->size < size) {
const MEM_SIZE fresh = size - header->size;
char *start_of_fresh = ((char *)ptr) + size;
PoisonNew(start_of_fresh, fresh, char);
}
# endif
maybe_protect_rw(header->next);
header->next->prev = header;
maybe_protect_ro(header->next);
maybe_protect_rw(header->prev);
header->prev->next = header;
maybe_protect_ro(header->prev);
#endif
ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
}
/* In particular, must do that fixup above before logging anything via
*printf(), as it can reallocate memory, which can cause SEGVs. */
DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
if (ptr == NULL) {
#ifdef USE_MDH
out_of_memory:
#endif
{
#ifndef ALWAYS_NEED_THX
dTHX;
#endif
if (PL_nomemok)
ptr = NULL;
else
croak_no_mem();
}
}
}
return ptr;
}
/* safe version of system's free() */
Free_t
Perl_safesysfree(Malloc_t where)
{
#ifdef ALWAYS_NEED_THX
dTHX;
#endif
DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
if (where) {
#ifdef USE_MDH
Malloc_t where_intrn = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
{
struct perl_memory_debug_header *const header
= (struct perl_memory_debug_header *)where_intrn;
# ifdef MDH_HAS_SIZE
const MEM_SIZE size = header->size;
# endif
# ifdef PERL_TRACK_MEMPOOL
if (header->interpreter != aTHX) {
Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
header->interpreter, aTHX);
}
if (!header->prev) {
Perl_croak_nocontext("panic: duplicate free");
}
if (!(header->next))
Perl_croak_nocontext("panic: bad free, header->next==NULL");
if (header->next->prev != header || header->prev->next != header) {
Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
"header=%p, ->prev->next=%p",
header->next->prev, header,
header->prev->next);
}
/* Unlink us from the chain. */
maybe_protect_rw(header->next);
header->next->prev = header->prev;
maybe_protect_ro(header->next);
maybe_protect_rw(header->prev);
header->prev->next = header->next;
maybe_protect_ro(header->prev);
maybe_protect_rw(header);
# ifdef PERL_POISON
PoisonNew(where_intrn, size, char);
# endif
/* Trigger the duplicate free warning. */
header->next = NULL;
# endif
# ifdef PERL_DEBUG_READONLY_COW
if (munmap(where_intrn, size)) {
perror("munmap failed");
abort();
}
# endif
}
#else
Malloc_t where_intrn = where;
#endif /* USE_MDH */
#ifndef PERL_DEBUG_READONLY_COW
PerlMem_free(where_intrn);
#endif
}
}
/* safe version of system's calloc() */
Malloc_t
Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
{
#ifdef ALWAYS_NEED_THX
dTHX;
#endif
Malloc_t ptr;
#if defined(USE_MDH) || defined(DEBUGGING)
MEM_SIZE total_size = 0;
#endif
/* Even though calloc() for zero bytes is strange, be robust. */
if (size && (count <= MEM_SIZE_MAX / size)) {
#if defined(USE_MDH) || defined(DEBUGGING)
total_size = size * count;
#endif
}
else
croak_memory_wrap();
#ifdef USE_MDH
if (PERL_MEMORY_DEBUG_HEADER_SIZE <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
total_size += PERL_MEMORY_DEBUG_HEADER_SIZE;
else
croak_memory_wrap();
#endif
#ifdef DEBUGGING
if ((SSize_t)size < 0 || (SSize_t)count < 0)
Perl_croak_nocontext("panic: calloc, size=%" UVuf ", count=%" UVuf,
(UV)size, (UV)count);
#endif
#ifdef PERL_DEBUG_READONLY_COW
if ((ptr = mmap(0, total_size ? total_size : 1, PROT_READ|PROT_WRITE,
MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
perror("mmap failed");
abort();
}
#elif defined(PERL_TRACK_MEMPOOL)
/* Have to use malloc() because we've added some space for our tracking
header. */
/* malloc(0) is non-portable. */
ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
#else
/* Use calloc() because it might save a memset() if the memory is fresh
and clean from the OS. */
if (count && size)
ptr = (Malloc_t)PerlMem_calloc(count, size);
else /* calloc(0) is non-portable. */
ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
#endif
PERL_ALLOC_CHECK(ptr);
DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)total_size));
if (ptr != NULL) {
#ifdef USE_MDH
{
struct perl_memory_debug_header *const header
= (struct perl_memory_debug_header *)ptr;
# ifndef PERL_DEBUG_READONLY_COW
memset((void*)ptr, 0, total_size);
# endif
# ifdef PERL_TRACK_MEMPOOL
header->interpreter = aTHX;
/* Link us into the list. */
header->prev = &PL_memory_debug_header;
header->next = PL_memory_debug_header.next;
PL_memory_debug_header.next = header;
maybe_protect_rw(header->next);
header->next->prev = header;
maybe_protect_ro(header->next);
# ifdef PERL_DEBUG_READONLY_COW
header->readonly = 0;
# endif
# endif
# ifdef MDH_HAS_SIZE
header->size = total_size;
# endif
ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
}
#endif
return ptr;
}
else {
#ifndef ALWAYS_NEED_THX
dTHX;
#endif
if (PL_nomemok)
return NULL;
croak_no_mem();
}
}
/* These must be defined when not using Perl's malloc for binary
* compatibility */
#ifndef MYMALLOC
Malloc_t Perl_malloc (MEM_SIZE nbytes)
{
#ifdef PERL_IMPLICIT_SYS
dTHX;
#endif
return (Malloc_t)PerlMem_malloc(nbytes);
}
Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
{
#ifdef PERL_IMPLICIT_SYS
dTHX;
#endif
return (Malloc_t)PerlMem_calloc(elements, size);
}
Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
{
#ifdef PERL_IMPLICIT_SYS
dTHX;
#endif
return (Malloc_t)PerlMem_realloc(where, nbytes);
}
Free_t Perl_mfree (Malloc_t where)
{
#ifdef PERL_IMPLICIT_SYS
dTHX;
#endif
PerlMem_free(where);
}
#endif
/* copy a string up to some (non-backslashed) delimiter, if any.
* With allow_escape, converts \<delimiter> to <delimiter>, while leaves
* \<non-delimiter> as-is.
* Returns the position in the src string of the closing delimiter, if
* any, or returns fromend otherwise.
* This is the internal implementation for Perl_delimcpy and
* Perl_delimcpy_no_escape.
*/
static char *
S_delimcpy_intern(char *to, const char *toend, const char *from,
const char *fromend, int delim, I32 *retlen,
const bool allow_escape)
{
I32 tolen;
PERL_ARGS_ASSERT_DELIMCPY;
for (tolen = 0; from < fromend; from++, tolen++) {
if (allow_escape && *from == '\\' && from + 1 < fromend) {
if (from[1] != delim) {
if (to < toend)
*to++ = *from;
tolen++;
}
from++;
}
else if (*from == delim)
break;
if (to < toend)
*to++ = *from;
}
if (to < toend)
*to = '\0';
*retlen = tolen;
return (char *)from;
}
char *
Perl_delimcpy(char *to, const char *toend, const char *from, const char *fromend, int delim, I32 *retlen)
{
PERL_ARGS_ASSERT_DELIMCPY;
return S_delimcpy_intern(to, toend, from, fromend, delim, retlen, 1);
}
char *
Perl_delimcpy_no_escape(char *to, const char *toend, const char *from,
const char *fromend, int delim, I32 *retlen)
{
PERL_ARGS_ASSERT_DELIMCPY_NO_ESCAPE;
return S_delimcpy_intern(to, toend, from, fromend, delim, retlen, 0);
}
/*
=head1 Miscellaneous Functions
=for apidoc Am|char *|ninstr|char * big|char * bigend|char * little|char * little_end
Find the first (leftmost) occurrence of a sequence of bytes within another
sequence. This is the Perl version of C<strstr()>, extended to handle
arbitrary sequences, potentially containing embedded C<NUL> characters (C<NUL>
is what the initial C<n> in the function name stands for; some systems have an
equivalent, C<memmem()>, but with a somewhat different API).
Another way of thinking about this function is finding a needle in a haystack.
C<big> points to the first byte in the haystack. C<big_end> points to one byte
beyond the final byte in the haystack. C<little> points to the first byte in
the needle. C<little_end> points to one byte beyond the final byte in the
needle. All the parameters must be non-C<NULL>.
The function returns C<NULL> if there is no occurrence of C<little> within
C<big>. If C<little> is the empty string, C<big> is returned.
Because this function operates at the byte level, and because of the inherent
characteristics of UTF-8 (or UTF-EBCDIC), it will work properly if both the
needle and the haystack are strings with the same UTF-8ness, but not if the
UTF-8ness differs.
=cut
*/
char *
Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
{
PERL_ARGS_ASSERT_NINSTR;
#ifdef HAS_MEMMEM
return ninstr(big, bigend, little, lend);
#else
if (little >= lend)
return (char*)big;
{
const char first = *little;
bigend -= lend - little++;
OUTER:
while (big <= bigend) {
if (*big++ == first) {
const char *s, *x;
for (x=big,s=little; s < lend; x++,s++) {
if (*s != *x)
goto OUTER;
}
return (char*)(big-1);
}
}
}
return NULL;
#endif
}
/*
=head1 Miscellaneous Functions
=for apidoc Am|char *|rninstr|char * big|char * bigend|char * little|char * little_end
Like C<L</ninstr>>, but instead finds the final (rightmost) occurrence of a
sequence of bytes within another sequence, returning C<NULL> if there is no
such occurrence.
=cut
*/
char *
Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend)
{
const char *bigbeg;
const I32 first = *little;
const char * const littleend = lend;
PERL_ARGS_ASSERT_RNINSTR;
if (little >= littleend)
return (char*)bigend;
bigbeg = big;
big = bigend - (littleend - little++);
while (big >= bigbeg) {
const char *s, *x;
if (*big-- != first)
continue;
for (x=big+2,s=little; s < littleend; /**/ ) {
if (*s != *x)
break;
else {
x++;
s++;
}
}
if (s >= littleend)
return (char*)(big+1);
}
return NULL;
}
/* As a space optimization, we do not compile tables for strings of length
0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
special-cased in fbm_instr().
If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
/*
=head1 Miscellaneous Functions
=for apidoc fbm_compile
Analyzes the string in order to make fast searches on it using C<fbm_instr()>
-- the Boyer-Moore algorithm.
=cut
*/
void
Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
{
const U8 *s;
STRLEN i;
STRLEN len;
U32 frequency = 256;
MAGIC *mg;
PERL_DEB( STRLEN rarest = 0 );
PERL_ARGS_ASSERT_FBM_COMPILE;
if (isGV_with_GP(sv) || SvROK(sv))
return;
if (SvVALID(sv))
return;
if (flags & FBMcf_TAIL) {
MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
if (mg && mg->mg_len >= 0)
mg->mg_len++;
}
if (!SvPOK(sv) || SvNIOKp(sv))
s = (U8*)SvPV_force_mutable(sv, len);
else s = (U8 *)SvPV_mutable(sv, len);
if (len == 0) /* TAIL might be on a zero-length string. */
return;
SvUPGRADE(sv, SVt_PVMG);
SvIOK_off(sv);
SvNOK_off(sv);
/* add PERL_MAGIC_bm magic holding the FBM lookup table */
assert(!mg_find(sv, PERL_MAGIC_bm));
mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
assert(mg);
if (len > 2) {
/* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
the BM table. */
const U8 mlen = (len>255) ? 255 : (U8)len;
const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
U8 *table;
Newx(table, 256, U8);
memset((void*)table, mlen, 256);
mg->mg_ptr = (char *)table;
mg->mg_len = 256;
s += len - 1; /* last char */
i = 0;
while (s >= sb) {
if (table[*s] == mlen)
table[*s] = (U8)i;
s--, i++;
}
}
s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
for (i = 0; i < len; i++) {
if (PL_freq[s[i]] < frequency) {
PERL_DEB( rarest = i );
frequency = PL_freq[s[i]];
}
}
BmUSEFUL(sv) = 100; /* Initial value */
((XPVNV*)SvANY(sv))->xnv_u.xnv_bm_tail = cBOOL(flags & FBMcf_TAIL);
DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %" UVuf "\n",
s[rarest], (UV)rarest));
}
/*
=for apidoc fbm_instr
Returns the location of the SV in the string delimited by C<big> and
C<bigend> (C<bigend>) is the char following the last char).
It returns C<NULL> if the string can't be found. The C<sv>
does not have to be C<fbm_compiled>, but the search will not be as fast
then.
=cut
If SvTAIL(littlestr) is true, a fake "\n" was appended to to the string
during FBM compilation due to FBMcf_TAIL in flags. It indicates that
the littlestr must be anchored to the end of bigstr (or to any \n if
FBMrf_MULTILINE).
E.g. The regex compiler would compile /abc/ to a littlestr of "abc",
while /abc$/ compiles to "abc\n" with SvTAIL() true.
A littlestr of "abc", !SvTAIL matches as /abc/;
a littlestr of "ab\n", SvTAIL matches as:
without FBMrf_MULTILINE: /ab\n?\z/
with FBMrf_MULTILINE: /ab\n/ || /ab\z/;
(According to Ilya from 1999; I don't know if this is still true, DAPM 2015):
"If SvTAIL is actually due to \Z or \z, this gives false positives
if multiline".
*/
char *
Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags)
{
unsigned char *s;
STRLEN l;
const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
STRLEN littlelen = l;
const I32 multiline = flags & FBMrf_MULTILINE;
bool valid = SvVALID(littlestr);
bool tail = valid ? cBOOL(SvTAIL(littlestr)) : FALSE;
PERL_ARGS_ASSERT_FBM_INSTR;
assert(bigend >= big);
if ((STRLEN)(bigend - big) < littlelen) {
if ( tail
&& ((STRLEN)(bigend - big) == littlelen - 1)
&& (littlelen == 1
|| (*big == *little &&
memEQ((char *)big, (char *)little, littlelen - 1))))
return (char*)big;
return NULL;
}
switch (littlelen) { /* Special cases for 0, 1 and 2 */
case 0:
return (char*)big; /* Cannot be SvTAIL! */
case 1:
if (tail && !multiline) /* Anchor only! */
/* [-1] is safe because we know that bigend != big. */
return (char *) (bigend - (bigend[-1] == '\n'));
s = (unsigned char *)memchr((void*)big, *little, bigend-big);
if (s)
return (char *)s;
if (tail)
return (char *) bigend;
return NULL;
case 2:
if (tail && !multiline) {
/* a littlestr with SvTAIL must be of the form "X\n" (where X
* is a single char). It is anchored, and can only match
* "....X\n" or "....X" */
if (bigend[-2] == *little && bigend[-1] == '\n')
return (char*)bigend - 2;
if (bigend[-1] == *little)
return (char*)bigend - 1;
return NULL;
}
{
/* memchr() is likely to be very fast, possibly using whatever
* hardware support is available, such as checking a whole
* cache line in one instruction.
* So for a 2 char pattern, calling memchr() is likely to be
* faster than running FBM, or rolling our own. The previous
* version of this code was roll-your-own which typically
* only needed to read every 2nd char, which was good back in
* the day, but no longer.
*/
unsigned char c1 = little[0];
unsigned char c2 = little[1];
/* *** for all this case, bigend points to the last char,
* not the trailing \0: this makes the conditions slightly
* simpler */
bigend--;
s = big;
if (c1 != c2) {
while (s < bigend) {
/* do a quick test for c1 before calling memchr();
* this avoids the expensive fn call overhead when
* there are lots of c1's */
if (LIKELY(*s != c1)) {
s++;
s = (unsigned char *)memchr((void*)s, c1, bigend - s);
if (!s)
break;
}
if (s[1] == c2)
return (char*)s;
/* failed; try searching for c2 this time; that way
* we don't go pathologically slow when the string
* consists mostly of c1's or vice versa.
*/
s += 2;
if (s > bigend)
break;
s = (unsigned char *)memchr((void*)s, c2, bigend - s + 1);
if (!s)
break;
if (s[-1] == c1)
return (char*)s - 1;
}
}
else {
/* c1, c2 the same */
while (s < bigend) {
if (s[0] == c1) {
got_1char:
if (s[1] == c1)
return (char*)s;
s += 2;
}
else {
s++;
s = (unsigned char *)memchr((void*)s, c1, bigend - s);
if (!s || s >= bigend)
break;
goto got_1char;
}
}
}
/* failed to find 2 chars; try anchored match at end without
* the \n */
if (tail && bigend[0] == little[0])
return (char *)bigend;
return NULL;
}
default:
break; /* Only lengths 0 1 and 2 have special-case code. */
}
if (tail && !multiline) { /* tail anchored? */
s = bigend - littlelen;
if (s >= big && bigend[-1] == '\n' && *s == *little
/* Automatically of length > 2 */
&& memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
{
return (char*)s; /* how sweet it is */
}
if (s[1] == *little
&& memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
{
return (char*)s + 1; /* how sweet it is */
}
return NULL;
}
if (!valid) {
/* not compiled; use Perl_ninstr() instead */
char * const b = ninstr((char*)big,(char*)bigend,
(char*)little, (char*)little + littlelen);
assert(!tail); /* valid => FBM; tail only set on SvVALID SVs */
return b;
}
/* Do actual FBM. */
if (littlelen > (STRLEN)(bigend - big))
return NULL;
{
const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
const unsigned char *oldlittle;
assert(mg);
--littlelen; /* Last char found by table lookup */
s = big + littlelen;
little += littlelen; /* last char */
oldlittle = little;
if (s < bigend) {
const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
const unsigned char lastc = *little;
I32 tmp;
top2:
if ((tmp = table[*s])) {
/* *s != lastc; earliest position it could match now is
* tmp slots further on */
if ((s += tmp) >= bigend)
goto check_end;
if (LIKELY(*s != lastc)) {
s++;
s = (unsigned char *)memchr((void*)s, lastc, bigend - s);
if (!s) {
s = bigend;
goto check_end;
}
goto top2;
}
}
/* hand-rolled strncmp(): less expensive than calling the
* real function (maybe???) */
{
unsigned char * const olds = s;
tmp = littlelen;
while (tmp--) {
if (*--s == *--little)
continue;
s = olds + 1; /* here we pay the price for failure */
little = oldlittle;
if (s < bigend) /* fake up continue to outer loop */
goto top2;
goto check_end;
}
return (char *)s;
}
}
check_end:
if ( s == bigend
&& tail
&& memEQ((char *)(bigend - littlelen),
(char *)(oldlittle - littlelen), littlelen) )
return (char*)bigend - littlelen;
return NULL;
}
}
/* copy a string to a safe spot */
/*
=head1 Memory Management
=for apidoc savepv
Perl's version of C<strdup()>. Returns a pointer to a newly allocated
string which is a duplicate of C<pv>. The size of the string is
determined by C<strlen()>, which means it may not contain embedded C<NUL>
characters and must have a trailing C<NUL>. The memory allocated for the new
string can be freed with the C<Safefree()> function.
On some platforms, Windows for example, all allocated memory owned by a thread
is deallocated when that thread ends. So if you need that not to happen, you
need to use the shared memory functions, such as C<L</savesharedpv>>.
=cut
*/
char *
Perl_savepv(pTHX_ const char *pv)
{
PERL_UNUSED_CONTEXT;
if (!pv)
return NULL;
else {
char *newaddr;
const STRLEN pvlen = strlen(pv)+1;
Newx(newaddr, pvlen, char);
return (char*)memcpy(newaddr, pv, pvlen);
}
}
/* same thing but with a known length */
/*
=for apidoc savepvn
Perl's version of what C<strndup()> would be if it existed. Returns a
pointer to a newly allocated string which is a duplicate of the first
C<len> bytes from C<pv>, plus a trailing
C<NUL> byte. The memory allocated for
the new string can be freed with the C<Safefree()> function.
On some platforms, Windows for example, all allocated memory owned by a thread
is deallocated when that thread ends. So if you need that not to happen, you
need to use the shared memory functions, such as C<L</savesharedpvn>>.
=cut
*/
char *
Perl_savepvn(pTHX_ const char *pv, I32 len)
{
char *newaddr;
PERL_UNUSED_CONTEXT;
assert(len >= 0);
Newx(newaddr,len+1,char);
/* Give a meaning to NULL pointer mainly for the use in sv_magic() */
if (pv) {
/* might not be null terminated */
newaddr[len] = '\0';
return (char *) CopyD(pv,newaddr,len,char);
}
else {
return (char *) ZeroD(newaddr,len+1,char);
}
}
/*
=for apidoc savesharedpv
A version of C<savepv()> which allocates the duplicate string in memory
which is shared between threads.
=cut
*/
char *
Perl_savesharedpv(pTHX_ const char *pv)
{
char *newaddr;
STRLEN pvlen;
PERL_UNUSED_CONTEXT;
if (!pv)
return NULL;
pvlen = strlen(pv)+1;
newaddr = (char*)PerlMemShared_malloc(pvlen);
if (!newaddr) {
croak_no_mem();
}
return (char*)memcpy(newaddr, pv, pvlen);
}
/*
=for apidoc savesharedpvn
A version of C<savepvn()> which allocates the duplicate string in memory
which is shared between threads. (With the specific difference that a C<NULL>
pointer is not acceptable)
=cut
*/
char *
Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
{
char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
PERL_UNUSED_CONTEXT;
/* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
if (!newaddr) {
croak_no_mem();
}
newaddr[len] = '\0';
return (char*)memcpy(newaddr, pv, len);
}
/*
=for apidoc savesvpv
A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
the passed in SV using C<SvPV()>
On some platforms, Windows for example, all allocated memory owned by a thread
is deallocated when that thread ends. So if you need that not to happen, you
need to use the shared memory functions, such as C<L</savesharedsvpv>>.
=cut
*/
char *
Perl_savesvpv(pTHX_ SV *sv)
{
STRLEN len;
const char * const pv = SvPV_const(sv, len);
char *newaddr;
PERL_ARGS_ASSERT_SAVESVPV;
++len;
Newx(newaddr,len,char);
return (char *) CopyD(pv,newaddr,len,char);
}
/*
=for apidoc savesharedsvpv
A version of C<savesharedpv()> which allocates the duplicate string in
memory which is shared between threads.
=cut
*/
char *
Perl_savesharedsvpv(pTHX_ SV *sv)
{
STRLEN len;
const char * const pv = SvPV_const(sv, len);
PERL_ARGS_ASSERT_SAVESHAREDSVPV;
return savesharedpvn(pv, len);
}
/* the SV for Perl_form() and mess() is not kept in an arena */
STATIC SV *
S_mess_alloc(pTHX)
{
SV *sv;
XPVMG *any;
if (PL_phase != PERL_PHASE_DESTRUCT)
return newSVpvs_flags("", SVs_TEMP);
if (PL_mess_sv)
return PL_mess_sv;
/* Create as PVMG now, to avoid any upgrading later */
Newx(sv, 1, SV);
Newxz(any, 1, XPVMG);
SvFLAGS(sv) = SVt_PVMG;
SvANY(sv) = (void*)any;
SvPV_set(sv, NULL);
SvREFCNT(sv) = 1 << 30; /* practically infinite */
PL_mess_sv = sv;
return sv;
}
#if defined(PERL_IMPLICIT_CONTEXT)
char *
Perl_form_nocontext(const char* pat, ...)
{
dTHX;
char *retval;
va_list args;
PERL_ARGS_ASSERT_FORM_NOCONTEXT;
va_start(args, pat);
retval = vform(pat, &args);
va_end(args);
return retval;
}
#endif /* PERL_IMPLICIT_CONTEXT */
/*
=head1 Miscellaneous Functions
=for apidoc form
Takes a sprintf-style format pattern and conventional
(non-SV) arguments and returns the formatted string.
(char *) Perl_form(pTHX_ const char* pat, ...)
can be used any place a string (char *) is required:
char * s = Perl_form("%d.%d",major,minor);
Uses a single private buffer so if you want to format several strings you
must explicitly copy the earlier strings away (and free the copies when you
are done).
=cut
*/
char *
Perl_form(pTHX_ const char* pat, ...)
{
char *retval;
va_list args;
PERL_ARGS_ASSERT_FORM;
va_start(args, pat);
retval = vform(pat, &args);
va_end(args);
return retval;
}
char *
Perl_vform(pTHX_ const char *pat, va_list *args)
{
SV * const sv = mess_alloc();
PERL_ARGS_ASSERT_VFORM;
sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
return SvPVX(sv);
}
/*
=for apidoc Am|SV *|mess|const char *pat|...
Take a sprintf-style format pattern and argument list. These are used to
generate a string message. If the message does not end with a newline,
then it will be extended with some indication of the current location
in the code, as described for L</mess_sv>.
Normally, the resulting message is returned in a new mortal SV.
During global destruction a single SV may be shared between uses of
this function.
=cut
*/
#if defined(PERL_IMPLICIT_CONTEXT)
SV *
Perl_mess_nocontext(const char *pat, ...)
{
dTHX;
SV *retval;
va_list args;
PERL_ARGS_ASSERT_MESS_NOCONTEXT;
va_start(args, pat);
retval = vmess(pat, &args);
va_end(args);
return retval;
}
#endif /* PERL_IMPLICIT_CONTEXT */
SV *
Perl_mess(pTHX_ const char *pat, ...)
{
SV *retval;
va_list args;
PERL_ARGS_ASSERT_MESS;
va_start(args, pat);
retval = vmess(pat, &args);
va_end(args);
return retval;
}
const COP*
Perl_closest_cop(pTHX_ const COP *cop, const OP *o, const OP *curop,
bool opnext)
{
/* Look for curop starting from o. cop is the last COP we've seen. */
/* opnext means that curop is actually the ->op_next of the op we are
seeking. */
PERL_ARGS_ASSERT_CLOSEST_COP;
if (!o || !curop || (
opnext ? o->op_next == curop && o->op_type != OP_SCOPE : o == curop
))
return cop;
if (o->op_flags & OPf_KIDS) {
const OP *kid;
for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
const COP *new_cop;
/* If the OP_NEXTSTATE has been optimised away we can still use it
* the get the file and line number. */
if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
cop = (const COP *)kid;
/* Keep searching, and return when we've found something. */
new_cop = closest_cop(cop, kid, curop, opnext);
if (new_cop)
return new_cop;
}
}
/* Nothing found. */
return NULL;
}
/*
=for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
Expands a message, intended for the user, to include an indication of
the current location in the code, if the message does not already appear
to be complete.
C<basemsg> is the initial message or object. If it is a reference, it
will be used as-is and will be the result of this function. Otherwise it
is used as a string, and if it already ends with a newline, it is taken
to be complete, and the result of this function will be the same string.
If the message does not end with a newline, then a segment such as C<at
foo.pl line 37> will be appended, and possibly other clauses indicating
the current state of execution. The resulting message will end with a
dot and a newline.
Normally, the resulting message is returned in a new mortal SV.
During global destruction a single SV may be shared between uses of this
function. If C<consume> is true, then the function is permitted (but not
required) to modify and return C<basemsg> instead of allocating a new SV.
=cut
*/
SV *
Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
{
SV *sv;
#if defined(USE_C_BACKTRACE) && defined(USE_C_BACKTRACE_ON_ERROR)
{
char *ws;
UV wi;
/* The PERL_C_BACKTRACE_ON_WARN must be an integer of one or more. */
if ((ws = PerlEnv_getenv("PERL_C_BACKTRACE_ON_ERROR"))
&& grok_atoUV(ws, &wi, NULL)
&& wi <= PERL_INT_MAX
) {
Perl_dump_c_backtrace(aTHX_ Perl_debug_log, (int)wi, 1);
}
}
#endif
PERL_ARGS_ASSERT_MESS_SV;
if (SvROK(basemsg)) {
if (consume) {
sv = basemsg;
}
else {
sv = mess_alloc();
sv_setsv(sv, basemsg);
}
return sv;
}
if (SvPOK(basemsg) && consume) {
sv = basemsg;
}
else {
sv = mess_alloc();
sv_copypv(sv, basemsg);
}
if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
/*
* Try and find the file and line for PL_op. This will usually be
* PL_curcop, but it might be a cop that has been optimised away. We
* can try to find such a cop by searching through the optree starting
* from the sibling of PL_curcop.
*/
if (PL_curcop) {
const COP *cop =
closest_cop(PL_curcop, OpSIBLING(PL_curcop), PL_op, FALSE);
if (!cop)
cop = PL_curcop;
if (CopLINE(cop))
Perl_sv_catpvf(aTHX_ sv, " at %s line %" IVdf,
OutCopFILE(cop), (IV)CopLINE(cop));
}
/* Seems that GvIO() can be untrustworthy during global destruction. */
if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
&& IoLINES(GvIOp(PL_last_in_gv)))
{
STRLEN l;
const bool line_mode = (RsSIMPLE(PL_rs) &&
*SvPV_const(PL_rs,l) == '\n' && l == 1);
Perl_sv_catpvf(aTHX_ sv, ", <%" SVf "> %s %" IVdf,
SVfARG(PL_last_in_gv == PL_argvgv
? &PL_sv_no
: sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
line_mode ? "line" : "chunk",
(IV)IoLINES(GvIOp(PL_last_in_gv)));
}
if (PL_phase == PERL_PHASE_DESTRUCT)
sv_catpvs(sv, " during global destruction");
sv_catpvs(sv, ".\n");
}
return sv;
}
/*
=for apidoc Am|SV *|vmess|const char *pat|va_list *args
C<pat> and C<args> are a sprintf-style format pattern and encapsulated
argument list, respectively. These are used to generate a string message. If
the
message does not end with a newline, then it will be extended with
some indication of the current location in the code, as described for
L</mess_sv>.
Normally, the resulting message is returned in a new mortal SV.
During global destruction a single SV may be shared between uses of
this function.
=cut
*/
SV *
Perl_vmess(pTHX_ const char *pat, va_list *args)
{
SV * const sv = mess_alloc();
PERL_ARGS_ASSERT_VMESS;
sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
return mess_sv(sv, 1);
}
void
Perl_write_to_stderr(pTHX_ SV* msv)
{
IO *io;
MAGIC *mg;
PERL_ARGS_ASSERT_WRITE_TO_STDERR;
if (PL_stderrgv && SvREFCNT(PL_stderrgv)
&& (io = GvIO(PL_stderrgv))
&& (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, SV_CONST(PRINT),
G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
else {
PerlIO * const serr = Perl_error_log;
do_print(msv, serr);
(void)PerlIO_flush(serr);
}
}
/*
=head1 Warning and Dieing
*/
/* Common code used in dieing and warning */
STATIC SV *
S_with_queued_errors(pTHX_ SV *ex)
{
PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
sv_catsv(PL_errors, ex);
ex = sv_mortalcopy(PL_errors);
SvCUR_set(PL_errors, 0);
}
return ex;
}
STATIC bool
S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
{
HV *stash;
GV *gv;
CV *cv;
SV **const hook = warn ? &PL_warnhook : &PL_diehook;
/* sv_2cv might call Perl_croak() or Perl_warner() */
SV * const oldhook = *hook;
if (!oldhook)
return FALSE;
ENTER;
SAVESPTR(*hook);
*hook = NULL;
cv = sv_2cv(oldhook, &stash, &gv, 0);
LEAVE;
if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
dSP;
SV *exarg;
ENTER;
save_re_context();
if (warn) {
SAVESPTR(*hook);
*hook = NULL;
}
exarg = newSVsv(ex);
SvREADONLY_on(exarg);
SAVEFREESV(exarg);
PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
PUSHMARK(SP);
XPUSHs(exarg);
PUTBACK;
call_sv(MUTABLE_SV(cv), G_DISCARD);
POPSTACK;
LEAVE;
return TRUE;
}
return FALSE;
}
/*
=for apidoc Am|OP *|die_sv|SV *baseex
Behaves the same as L</croak_sv>, except for the return type.
It should be used only where the C<OP *> return type is required.
The function never actually returns.
=cut
*/
#ifdef _MSC_VER
# pragma warning( push )
# pragma warning( disable : 4646 ) /* warning C4646: function declared with
__declspec(noreturn) has non-void return type */
# pragma warning( disable : 4645 ) /* warning C4645: function declared with
__declspec(noreturn) has a return statement */
#endif
OP *
Perl_die_sv(pTHX_ SV *baseex)
{
PERL_ARGS_ASSERT_DIE_SV;
croak_sv(baseex);
/* NOTREACHED */
NORETURN_FUNCTION_END;
}
#ifdef _MSC_VER
# pragma warning( pop )
#endif
/*
=for apidoc Am|OP *|die|const char *pat|...
Behaves the same as L</croak>, except for the return type.
It should be used only where the C<OP *> return type is required.
The function never actually returns.
=cut
*/
#if defined(PERL_IMPLICIT_CONTEXT)
#ifdef _MSC_VER
# pragma warning( push )
# pragma warning( disable : 4646 ) /* warning C4646: function declared with
__declspec(noreturn) has non-void return type */
# pragma warning( disable : 4645 ) /* warning C4645: function declared with
__declspec(noreturn) has a return statement */
#endif
OP *
Perl_die_nocontext(const char* pat, ...)
{
dTHX;
va_list args;
va_start(args, pat);
vcroak(pat, &args);
NOT_REACHED; /* NOTREACHED */
va_end(args);
NORETURN_FUNCTION_END;
}
#ifdef _MSC_VER
# pragma warning( pop )
#endif
#endif /* PERL_IMPLICIT_CONTEXT */
#ifdef _MSC_VER
# pragma warning( push )
# pragma warning( disable : 4646 ) /* warning C4646: function declared with
__declspec(noreturn) has non-void return type */
# pragma warning( disable : 4645 ) /* warning C4645: function declared with
__declspec(noreturn) has a return statement */
#endif
OP *
Perl_die(pTHX_ const char* pat, ...)
{
va_list args;
va_start(args, pat);
vcroak(pat, &args);
NOT_REACHED; /* NOTREACHED */
va_end(args);
NORETURN_FUNCTION_END;
}
#ifdef _MSC_VER
# pragma warning( pop )
#endif
/*
=for apidoc Am|void|croak_sv|SV *baseex
This is an XS interface to Perl's C<die> function.
C<baseex> is the error message or object. If it is a reference, it
will be used as-is. Otherwise it is used as a string, and if it does
not end with a newline then it will be extended with some indication of
the current location in the code, as described for L</mess_sv>.
The error message or object will be used as an exception, by default
returning control to the nearest enclosing C<eval>, but subject to
modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
function never returns normally.
To die with a simple string message, the L</croak> function may be
more convenient.
=cut
*/
void
Perl_croak_sv(pTHX_ SV *baseex)
{
SV *ex = with_queued_errors(mess_sv(baseex, 0));
PERL_ARGS_ASSERT_CROAK_SV;
invoke_exception_hook(ex, FALSE);
die_unwind(ex);
}
/*
=for apidoc Am|void|vcroak|const char *pat|va_list *args
This is an XS interface to Perl's C<die> function.
C<pat> and C<args> are a sprintf-style format pattern and encapsulated
argument list. These are used to generate a string message. If the
message does not end with a newline, then it will be extended with
some indication of the current location in the code, as described for
L</mess_sv>.
The error message will be used as an exception, by default
returning control to the nearest enclosing C<eval>, but subject to
modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
function never returns normally.
For historical reasons, if C<pat> is null then the contents of C<ERRSV>
(C<$@>) will be used as an error message or object instead of building an
error message from arguments. If you want to throw a non-string object,
or build an error message in an SV yourself, it is preferable to use
the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
=cut
*/
void
Perl_vcroak(pTHX_ const char* pat, va_list *args)
{
SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
invoke_exception_hook(ex, FALSE);
die_unwind(ex);
}
/*
=for apidoc Am|void|croak|const char *pat|...
This is an XS interface to Perl's C<die> function.
Take a sprintf-style format pattern and argument list. These are used to
generate a string message. If the message does not end with a newline,
then it will be extended with some indication of the current location
in the code, as described for L</mess_sv>.
The error message will be used as an exception, by default
returning control to the nearest enclosing C<eval>, but subject to
modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
function never returns normally.
For historical reasons, if C<pat> is null then the contents of C<ERRSV>
(C<$@>) will be used as an error message or object instead of building an
error message from arguments. If you want to throw a non-string object,
or build an error message in an SV yourself, it is preferable to use
the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
=cut
*/
#if defined(PERL_IMPLICIT_CONTEXT)
void
Perl_croak_nocontext(const char *pat, ...)
{
dTHX;
va_list args;
va_start(args, pat);
vcroak(pat, &args);
NOT_REACHED; /* NOTREACHED */
va_end(args);
}
#endif /* PERL_IMPLICIT_CONTEXT */
void
Perl_croak(pTHX_ const char *pat, ...)
{
va_list args;
va_start(args, pat);
vcroak(pat, &args);
NOT_REACHED; /* NOTREACHED */
va_end(args);
}
/*
=for apidoc Am|void|croak_no_modify
Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
terser object code than using C<Perl_croak>. Less code used on exception code
paths reduces CPU cache pressure.
=cut
*/
void
Perl_croak_no_modify(void)
{
Perl_croak_nocontext( "%s", PL_no_modify);
}
/* does not return, used in util.c perlio.c and win32.c
This is typically called when malloc returns NULL.
*/
void
Perl_croak_no_mem(void)
{
dTHX;
int fd = PerlIO_fileno(Perl_error_log);
if (fd < 0)
SETERRNO(EBADF,RMS_IFI);
else {
/* Can't use PerlIO to write as it allocates memory */
PERL_UNUSED_RESULT(PerlLIO_write(fd, PL_no_mem, sizeof(PL_no_mem)-1));
}
my_exit(1);
}
/* does not return, used only in POPSTACK */
void
Perl_croak_popstack(void)
{
dTHX;
PerlIO_printf(Perl_error_log, "panic: POPSTACK\n");
my_exit(1);
}
/*
=for apidoc Am|void|warn_sv|SV *baseex
This is an XS interface to Perl's C<warn> function.
C<baseex> is the error message or object. If it is a reference, it
will be used as-is. Otherwise it is used as a string, and if it does
not end with a newline then it will be extended with some indication of
the current location in the code, as described for L</mess_sv>.
The error message or object will by default be written to standard error,
but this is subject to modification by a C<$SIG{__WARN__}> handler.
To warn with a simple string message, the L</warn> function may be
more convenient.
=cut
*/
void
Perl_warn_sv(pTHX_ SV *baseex)
{
SV *ex = mess_sv(baseex, 0);
PERL_ARGS_ASSERT_WARN_SV;
if (!invoke_exception_hook(ex, TRUE))
write_to_stderr(ex);
}
/*
=for apidoc Am|void|vwarn|const char *pat|va_list *args
This is an XS interface to Perl's C<warn> function.
C<pat> and C<args> are a sprintf-style format pattern and encapsulated
argument list. These are used to generate a string message. If the
message does not end with a newline, then it will be extended with
some indication of the current location in the code, as described for
L</mess_sv>.
The error message or object will by default be written to standard error,
but this is subject to modification by a C<$SIG{__WARN__}> handler.
Unlike with L</vcroak>, C<pat> is not permitted to be null.
=cut
*/
void
Perl_vwarn(pTHX_ const char* pat, va_list *args)
{
SV *ex = vmess(pat, args);
PERL_ARGS_ASSERT_VWARN;
if (!invoke_exception_hook(ex, TRUE))
write_to_stderr(ex);
}
/*
=for apidoc Am|void|warn|const char *pat|...
This is an XS interface to Perl's C<warn> function.
Take a sprintf-style format pattern and argument list. These are used to
generate a string message. If the message does not end with a newline,
then it will be extended with some indication of the current location
in the code, as described for L</mess_sv>.
The error message or object will by default be written to standard error,
but this is subject to modification by a C<$SIG{__WARN__}> handler.
Unlike with L</croak>, C<pat> is not permitted to be null.
=cut
*/
#if defined(PERL_IMPLICIT_CONTEXT)
void
Perl_warn_nocontext(const char *pat, ...)
{
dTHX;
va_list args;
PERL_ARGS_ASSERT_WARN_NOCONTEXT;
va_start(args, pat);
vwarn(pat, &args);
va_end(args);
}
#endif /* PERL_IMPLICIT_CONTEXT */
void
Perl_warn(pTHX_ const char *pat, ...)
{
va_list args;
PERL_ARGS_ASSERT_WARN;
va_start(args, pat);
vwarn(pat, &args);
va_end(args);
}
#if defined(PERL_IMPLICIT_CONTEXT)
void
Perl_warner_nocontext(U32 err, const char *pat, ...)
{
dTHX;
va_list args;
PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
va_start(args, pat);
vwarner(err, pat, &args);
va_end(args);
}
#endif /* PERL_IMPLICIT_CONTEXT */
void
Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
{
PERL_ARGS_ASSERT_CK_WARNER_D;
if (Perl_ckwarn_d(aTHX_ err)) {
va_list args;
va_start(args, pat);
vwarner(err, pat, &args);
va_end(args);
}
}
void
Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
{
PERL_ARGS_ASSERT_CK_WARNER;
if (Perl_ckwarn(aTHX_ err)) {
va_list args;
va_start(args, pat);
vwarner(err, pat, &args);
va_end(args);
}
}
void
Perl_warner(pTHX_ U32 err, const char* pat,...)
{
va_list args;
PERL_ARGS_ASSERT_WARNER;
va_start(args, pat);
vwarner(err, pat, &args);
va_end(args);
}
void
Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
{
dVAR;
PERL_ARGS_ASSERT_VWARNER;
if (
(PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) &&
!(PL_in_eval & EVAL_KEEPERR)
) {
SV * const msv = vmess(pat, args);
if (PL_parser && PL_parser->error_count) {
qerror(msv);
}
else {
invoke_exception_hook(msv, FALSE);
die_unwind(msv);
}
}
else {
Perl_vwarn(aTHX_ pat, args);
}
}
/* implements the ckWARN? macros */
bool
Perl_ckwarn(pTHX_ U32 w)
{
/* If lexical warnings have not been set, use $^W. */
if (isLEXWARN_off)
return PL_dowarn & G_WARN_ON;
return ckwarn_common(w);
}
/* implements the ckWARN?_d macro */
bool
Perl_ckwarn_d(pTHX_ U32 w)
{
/* If lexical warnings have not been set then default classes warn. */
if (isLEXWARN_off)
return TRUE;
return ckwarn_common(w);
}
static bool
S_ckwarn_common(pTHX_ U32 w)
{
if (PL_curcop->cop_warnings == pWARN_ALL)
return TRUE;
if (PL_curcop->cop_warnings == pWARN_NONE)
return FALSE;
/* Check the assumption that at least the first slot is non-zero. */
assert(unpackWARN1(w));
/* Check the assumption that it is valid to stop as soon as a zero slot is
seen. */
if (!unpackWARN2(w)) {
assert(!unpackWARN3(w));
assert(!unpackWARN4(w));
} else if (!unpackWARN3(w)) {
assert(!unpackWARN4(w));
}
/* Right, dealt with all the special cases, which are implemented as non-
pointers, so there is a pointer to a real warnings mask. */
do {
if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
return TRUE;
} while (w >>= WARNshift);
return FALSE;
}
/* Set buffer=NULL to get a new one. */
STRLEN *
Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
STRLEN size) {
const MEM_SIZE len_wanted =
sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
PERL_UNUSED_CONTEXT;
PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
buffer = (STRLEN*)
(specialWARN(buffer) ?
PerlMemShared_malloc(len_wanted) :
PerlMemShared_realloc(buffer, len_wanted));
buffer[0] = size;
Copy(bits, (buffer + 1), size, char);
if (size < WARNsize)
Zero((char *)(buffer + 1) + size, WARNsize - size, char);
return buffer;
}
/* since we've already done strlen() for both nam and val
* we can use that info to make things faster than
* sprintf(s, "%s=%s", nam, val)
*/
#define my_setenv_format(s, nam, nlen, val, vlen) \
Copy(nam, s, nlen, char); \
*(s+nlen) = '='; \
Copy(val, s+(nlen+1), vlen, char); \
*(s+(nlen+1+vlen)) = '\0'
#ifdef USE_ENVIRON_ARRAY
/* VMS' my_setenv() is in vms.c */
#if !defined(WIN32) && !defined(NETWARE)
void
Perl_my_setenv(pTHX_ const char *nam, const char *val)
{
dVAR;
#ifdef __amigaos4__
amigaos4_obtain_environ(__FUNCTION__);
#endif
#ifdef USE_ITHREADS
/* only parent thread can modify process environment */
if (PL_curinterp == aTHX)
#endif
{
#ifndef PERL_USE_SAFE_PUTENV
if (!PL_use_safe_putenv) {
/* most putenv()s leak, so we manipulate environ directly */
I32 i;
const I32 len = strlen(nam);
int nlen, vlen;
/* where does it go? */
for (i = 0; environ[i]; i++) {
if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
break;
}
if (environ == PL_origenviron) { /* need we copy environment? */
I32 j;
I32 max;
char **tmpenv;
max = i;
while (environ[max])
max++;
tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
for (j=0; j<max; j++) { /* copy environment */
const int len = strlen(environ[j]);
tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
Copy(environ[j], tmpenv[j], len+1, char);
}
tmpenv[max] = NULL;
environ = tmpenv; /* tell exec where it is now */
}
if (!val) {
safesysfree(environ[i]);
while (environ[i]) {
environ[i] = environ[i+1];
i++;
}
#ifdef __amigaos4__
goto my_setenv_out;
#else
return;
#endif
}
if (!environ[i]) { /* does not exist yet */
environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
environ[i+1] = NULL; /* make sure it's null terminated */
}
else
safesysfree(environ[i]);
nlen = strlen(nam);
vlen = strlen(val);
environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
/* all that work just for this */
my_setenv_format(environ[i], nam, nlen, val, vlen);
} else {
# endif
/* This next branch should only be called #if defined(HAS_SETENV), but
Configure doesn't test for that yet. For Solaris, setenv() and unsetenv()
were introduced in Solaris 9, so testing for HAS UNSETENV is sufficient.
*/
# if defined(__CYGWIN__)|| defined(__SYMBIAN32__) || defined(__riscos__) || (defined(__sun) && defined(HAS_UNSETENV)) || defined(PERL_DARWIN)
# if defined(HAS_UNSETENV)
if (val == NULL) {
(void)unsetenv(nam);
} else {
(void)setenv(nam, val, 1);
}
# else /* ! HAS_UNSETENV */
(void)setenv(nam, val, 1);
# endif /* HAS_UNSETENV */
# elif defined(HAS_UNSETENV)
if (val == NULL) {
if (environ) /* old glibc can crash with null environ */
(void)unsetenv(nam);
} else {
const int nlen = strlen(nam);
const int vlen = strlen(val);
char * const new_env =
(char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
my_setenv_format(new_env, nam, nlen, val, vlen);
(void)putenv(new_env);
}
# else /* ! HAS_UNSETENV */
char *new_env;
const int nlen = strlen(nam);
int vlen;
if (!val) {
val = "";
}
vlen = strlen(val);
new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
/* all that work just for this */
my_setenv_format(new_env, nam, nlen, val, vlen);
(void)putenv(new_env);
# endif /* __CYGWIN__ */
#ifndef PERL_USE_SAFE_PUTENV
}
#endif
}
#ifdef __amigaos4__
my_setenv_out:
amigaos4_release_environ(__FUNCTION__);
#endif
}
#else /* WIN32 || NETWARE */
void
Perl_my_setenv(pTHX_ const char *nam, const char *val)
{
dVAR;
char *envstr;
const int nlen = strlen(nam);
int vlen;
if (!val) {
val = "";
}
vlen = strlen(val);
Newx(envstr, nlen+vlen+2, char);
my_setenv_format(envstr, nam, nlen, val, vlen);
(void)PerlEnv_putenv(envstr);
Safefree(envstr);
}
#endif /* WIN32 || NETWARE */
#endif /* !VMS */
#ifdef UNLINK_ALL_VERSIONS
I32
Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
{
I32 retries = 0;
PERL_ARGS_ASSERT_UNLNK;
while (PerlLIO_unlink(f) >= 0)
retries++;
return retries ? 0 : -1;
}
#endif
PerlIO *
Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
{
#if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(OS2) && !defined(VMS) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
int p[2];
I32 This, that;
Pid_t pid;
SV *sv;
I32 did_pipes = 0;
int pp[2];
PERL_ARGS_ASSERT_MY_POPEN_LIST;
PERL_FLUSHALL_FOR_CHILD;
This = (*mode == 'w');
that = !This;
if (TAINTING_get) {
taint_env();
taint_proper("Insecure %s%s", "EXEC");
}
if (PerlProc_pipe_cloexec(p) < 0)
return NULL;
/* Try for another pipe pair for error return */
if (PerlProc_pipe_cloexec(pp) >= 0)
did_pipes = 1;
while ((pid = PerlProc_fork()) < 0) {
if (errno != EAGAIN) {
PerlLIO_close(p[This]);
PerlLIO_close(p[that]);
if (did_pipes) {
PerlLIO_close(pp[0]);
PerlLIO_close(pp[1]);
}
return NULL;
}
Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
sleep(5);
}
if (pid == 0) {
/* Child */
#undef THIS
#undef THAT
#define THIS that
#define THAT This
/* Close parent's end of error status pipe (if any) */
if (did_pipes)
PerlLIO_close(pp[0]);
/* Now dup our end of _the_ pipe to right position */
if (p[THIS] != (*mode == 'r')) {
PerlLIO_dup2(p[THIS], *mode == 'r');
PerlLIO_close(p[THIS]);
if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
}
else
PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
#if !defined(HAS_FCNTL) || !defined(F_SETFD)
/* No automatic close - do it by hand */
# ifndef NOFILE
# define NOFILE 20
# endif
{
int fd;
for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
if (fd != pp[1])
PerlLIO_close(fd);
}
}
#endif
do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
PerlProc__exit(1);
#undef THIS
#undef THAT
}
/* Parent */
if (did_pipes)
PerlLIO_close(pp[1]);
/* Keep the lower of the two fd numbers */
if (p[that] < p[This]) {
PerlLIO_dup2_cloexec(p[This], p[that]);
PerlLIO_close(p[This]);
p[This] = p[that];
}
else
PerlLIO_close(p[that]); /* close child's end of pipe */
sv = *av_fetch(PL_fdpid,p[This],TRUE);
SvUPGRADE(sv,SVt_IV);
SvIV_set(sv, pid);
PL_forkprocess = pid;
/* If we managed to get status pipe check for exec fail */
if (did_pipes && pid > 0) {
int errkid;
unsigned n = 0;
while (n < sizeof(int)) {
const SSize_t n1 = PerlLIO_read(pp[0],
(void*)(((char*)&errkid)+n),
(sizeof(int)) - n);
if (n1 <= 0)
break;
n += n1;
}
PerlLIO_close(pp[0]);
did_pipes = 0;
if (n) { /* Error */
int pid2, status;
PerlLIO_close(p[This]);
if (n != sizeof(int))
Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
do {
pid2 = wait4pid(pid, &status, 0);
} while (pid2 == -1 && errno == EINTR);
errno = errkid; /* Propagate errno from kid */
return NULL;
}
}
if (did_pipes)
PerlLIO_close(pp[0]);
return PerlIO_fdopen(p[This], mode);
#else
# if defined(OS2) /* Same, without fork()ing and all extra overhead... */
return my_syspopen4(aTHX_ NULL, mode, n, args);
# elif defined(WIN32)
return win32_popenlist(mode, n, args);
# else
Perl_croak(aTHX_ "List form of piped open not implemented");
return (PerlIO *) NULL;
# endif
#endif
}
/* VMS' my_popen() is in VMS.c, same with OS/2 and AmigaOS 4. */
#if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(VMS) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
PerlIO *
Perl_my_popen(pTHX_ const char *cmd, const char *mode)
{
int p[2];
I32 This, that;
Pid_t pid;
SV *sv;
const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
I32 did_pipes = 0;
int pp[2];
PERL_ARGS_ASSERT_MY_POPEN;
PERL_FLUSHALL_FOR_CHILD;
#ifdef OS2
if (doexec) {
return my_syspopen(aTHX_ cmd,mode);
}
#endif
This = (*mode == 'w');
that = !This;
if (doexec && TAINTING_get) {
taint_env();
taint_proper("Insecure %s%s", "EXEC");
}
if (PerlProc_pipe_cloexec(p) < 0)
return NULL;
if (doexec && PerlProc_pipe_cloexec(pp) >= 0)
did_pipes = 1;
while ((pid = PerlProc_fork()) < 0) {
if (errno != EAGAIN) {
PerlLIO_close(p[This]);
PerlLIO_close(p[that]);
if (did_pipes) {
PerlLIO_close(pp[0]);
PerlLIO_close(pp[1]);
}
if (!doexec)
Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
return NULL;
}
Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
sleep(5);
}
if (pid == 0) {
#undef THIS
#undef THAT
#define THIS that
#define THAT This
if (did_pipes)
PerlLIO_close(pp[0]);
if (p[THIS] != (*mode == 'r')) {
PerlLIO_dup2(p[THIS], *mode == 'r');
PerlLIO_close(p[THIS]);
if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
PerlLIO_close(p[THAT]);
}
else
PerlLIO_close(p[THAT]);
#ifndef OS2
if (doexec) {
#if !defined(HAS_FCNTL) || !defined(F_SETFD)
#ifndef NOFILE
#define NOFILE 20
#endif
{
int fd;
for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
if (fd != pp[1])
PerlLIO_close(fd);
}
#endif
/* may or may not use the shell */
do_exec3(cmd, pp[1], did_pipes);
PerlProc__exit(1);
}
#endif /* defined OS2 */
#ifdef PERLIO_USING_CRLF
/* Since we circumvent IO layers when we manipulate low-level
filedescriptors directly, need to manually switch to the
default, binary, low-level mode; see PerlIOBuf_open(). */
PerlLIO_setmode((*mode == 'r'), O_BINARY);
#endif
PL_forkprocess = 0;
#ifdef PERL_USES_PL_PIDSTATUS
hv_clear(PL_pidstatus); /* we have no children */
#endif
return NULL;
#undef THIS
#undef THAT
}
if (did_pipes)
PerlLIO_close(pp[1]);
if (p[that] < p[This]) {
PerlLIO_dup2_cloexec(p[This], p[that]);
PerlLIO_close(p[This]);
p[This] = p[that];
}
else
PerlLIO_close(p[that]);
sv = *av_fetch(PL_fdpid,p[This],TRUE);
SvUPGRADE(sv,SVt_IV);
SvIV_set(sv, pid);
PL_forkprocess = pid;
if (did_pipes && pid > 0) {
int errkid;
unsigned n = 0;
while (n < sizeof(int)) {
const SSize_t n1 = PerlLIO_read(pp[0],
(void*)(((char*)&errkid)+n),
(sizeof(int)) - n);
if (n1 <= 0)
break;
n += n1;
}
PerlLIO_close(pp[0]);
did_pipes = 0;
if (n) { /* Error */
int pid2, status;
PerlLIO_close(p[This]);
if (n != sizeof(int))
Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
do {
pid2 = wait4pid(pid, &status, 0);
} while (pid2 == -1 && errno == EINTR);
errno = errkid; /* Propagate errno from kid */
return NULL;
}
}
if (did_pipes)
PerlLIO_close(pp[0]);
return PerlIO_fdopen(p[This], mode);
}
#elif defined(DJGPP)
FILE *djgpp_popen();
PerlIO *
Perl_my_popen(pTHX_ const char *cmd, const char *mode)
{
PERL_FLUSHALL_FOR_CHILD;
/* Call system's popen() to get a FILE *, then import it.
used 0 for 2nd parameter to PerlIO_importFILE;
apparently not used
*/
return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
}
#elif defined(__LIBCATAMOUNT__)
PerlIO *
Perl_my_popen(pTHX_ const char *cmd, const char *mode)
{
return NULL;
}
#endif /* !DOSISH */
/* this is called in parent before the fork() */
void
Perl_atfork_lock(void)
#if defined(USE_ITHREADS)
# ifdef USE_PERLIO
PERL_TSA_ACQUIRE(PL_perlio_mutex)
# endif
# ifdef MYMALLOC
PERL_TSA_ACQUIRE(PL_malloc_mutex)
# endif
PERL_TSA_ACQUIRE(PL_op_mutex)
#endif
{
#if defined(USE_ITHREADS)
dVAR;
/* locks must be held in locking order (if any) */
# ifdef USE_PERLIO
MUTEX_LOCK(&PL_perlio_mutex);
# endif
# ifdef MYMALLOC
MUTEX_LOCK(&PL_malloc_mutex);
# endif
OP_REFCNT_LOCK;
#endif
}
/* this is called in both parent and child after the fork() */
void
Perl_atfork_unlock(void)
#if defined(USE_ITHREADS)
# ifdef USE_PERLIO
PERL_TSA_RELEASE(PL_perlio_mutex)
# endif
# ifdef MYMALLOC
PERL_TSA_RELEASE(PL_malloc_mutex)
# endif
PERL_TSA_RELEASE(PL_op_mutex)
#endif
{
#if defined(USE_ITHREADS)
dVAR;
/* locks must be released in same order as in atfork_lock() */
# ifdef USE_PERLIO
MUTEX_UNLOCK(&PL_perlio_mutex);
# endif
# ifdef MYMALLOC
MUTEX_UNLOCK(&PL_malloc_mutex);
# endif
OP_REFCNT_UNLOCK;
#endif
}
Pid_t
Perl_my_fork(void)
{
#if defined(HAS_FORK)
Pid_t pid;
#if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
atfork_lock();
pid = fork();
atfork_unlock();
#else
/* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
* handlers elsewhere in the code */
pid = fork();
#endif
return pid;
#elif defined(__amigaos4__)
return amigaos_fork();
#else
/* this "canna happen" since nothing should be calling here if !HAS_FORK */
Perl_croak_nocontext("fork() not available");
return 0;
#endif /* HAS_FORK */
}
#ifndef HAS_DUP2
int
dup2(int oldfd, int newfd)
{
#if defined(HAS_FCNTL) && defined(F_DUPFD)
if (oldfd == newfd)
return oldfd;
PerlLIO_close(newfd);
return fcntl(oldfd, F_DUPFD, newfd);
#else
#define DUP2_MAX_FDS 256
int fdtmp[DUP2_MAX_FDS];
I32 fdx = 0;
int fd;
if (oldfd == newfd)
return oldfd;
PerlLIO_close(newfd);
/* good enough for low fd's... */
while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
if (fdx >= DUP2_MAX_FDS) {
PerlLIO_close(fd);
fd = -1;
break;
}
fdtmp[fdx++] = fd;
}
while (fdx > 0)
PerlLIO_close(fdtmp[--fdx]);
return fd;
#endif
}
#endif
#ifndef PERL_MICRO
#ifdef HAS_SIGACTION
Sighandler_t
Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
{
struct sigaction act, oact;
#ifdef USE_ITHREADS
dVAR;
/* only "parent" interpreter can diddle signals */
if (PL_curinterp != aTHX)
return (Sighandler_t) SIG_ERR;
#endif
act.sa_handler = (void(*)(int))handler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
#ifdef SA_RESTART
if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
#endif
#if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
act.sa_flags |= SA_NOCLDWAIT;
#endif
if (sigaction(signo, &act, &oact) == -1)
return (Sighandler_t) SIG_ERR;
else
return (Sighandler_t) oact.sa_handler;
}
Sighandler_t
Perl_rsignal_state(pTHX_ int signo)
{
struct sigaction oact;
PERL_UNUSED_CONTEXT;
if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
return (Sighandler_t) SIG_ERR;
else
return (Sighandler_t) oact.sa_handler;
}
int
Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
{
#ifdef USE_ITHREADS
dVAR;
#endif
struct sigaction act;
PERL_ARGS_ASSERT_RSIGNAL_SAVE;
#ifdef USE_ITHREADS
/* only "parent" interpreter can diddle signals */
if (PL_curinterp != aTHX)
return -1;
#endif
act.sa_handler = (void(*)(int))handler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
#ifdef SA_RESTART
if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
#endif
#if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
act.sa_flags |= SA_NOCLDWAIT;
#endif
return sigaction(signo, &act, save);
}
int
Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
{
#ifdef USE_ITHREADS
dVAR;
#endif
PERL_UNUSED_CONTEXT;
#ifdef USE_ITHREADS
/* only "parent" interpreter can diddle signals */
if (PL_curinterp != aTHX)
return -1;
#endif
return sigaction(signo, save, (struct sigaction *)NULL);
}
#else /* !HAS_SIGACTION */
Sighandler_t
Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
{
#if defined(USE_ITHREADS) && !defined(WIN32)
/* only "parent" interpreter can diddle signals */
if (PL_curinterp != aTHX)
return (Sighandler_t) SIG_ERR;
#endif
return PerlProc_signal(signo, handler);
}
static Signal_t
sig_trap(int signo)
{
dVAR;
PL_sig_trapped++;
}
Sighandler_t
Perl_rsignal_state(pTHX_ int signo)
{
dVAR;
Sighandler_t oldsig;
#if defined(USE_ITHREADS) && !defined(WIN32)
/* only "parent" interpreter can diddle signals */
if (PL_curinterp != aTHX)
return (Sighandler_t) SIG_ERR;
#endif
PL_sig_trapped = 0;
oldsig = PerlProc_signal(signo, sig_trap);
PerlProc_signal(signo, oldsig);
if (PL_sig_trapped)
PerlProc_kill(PerlProc_getpid(), signo);
return oldsig;
}
int
Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
{
#if defined(USE_ITHREADS) && !defined(WIN32)
/* only "parent" interpreter can diddle signals */
if (PL_curinterp != aTHX)
return -1;
#endif
*save = PerlProc_signal(signo, handler);
return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
}
int
Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
{
#if defined(USE_ITHREADS) && !defined(WIN32)
/* only "parent" interpreter can diddle signals */
if (PL_curinterp != aTHX)
return -1;
#endif
return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
}
#endif /* !HAS_SIGACTION */
#endif /* !PERL_MICRO */
/* VMS' my_pclose() is in VMS.c; same with OS/2 */
#if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(VMS) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
I32
Perl_my_pclose(pTHX_ PerlIO *ptr)
{
int status;
SV **svp;
Pid_t pid;
Pid_t pid2 = 0;
bool close_failed;
dSAVEDERRNO;
const int fd = PerlIO_fileno(ptr);
bool should_wait;
svp = av_fetch(PL_fdpid,fd,TRUE);
pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
SvREFCNT_dec(*svp);
*svp = NULL;
#if defined(USE_PERLIO)
/* Find out whether the refcount is low enough for us to wait for the
child proc without blocking. */
should_wait = PerlIOUnix_refcnt(fd) == 1 && pid > 0;
#else
should_wait = pid > 0;
#endif
#ifdef OS2
if (pid == -1) { /* Opened by popen. */
return my_syspclose(ptr);
}
#endif
close_failed = (PerlIO_close(ptr) == EOF);
SAVE_ERRNO;
if (should_wait) do {
pid2 = wait4pid(pid, &status, 0);
} while (pid2 == -1 && errno == EINTR);
if (close_failed) {
RESTORE_ERRNO;
return -1;
}
return(
should_wait
? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
: 0
);
}
#elif defined(__LIBCATAMOUNT__)
I32
Perl_my_pclose(pTHX_ PerlIO *ptr)
{
return -1;
}
#endif /* !DOSISH */
#if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
I32
Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
{
I32 result = 0;
PERL_ARGS_ASSERT_WAIT4PID;
#ifdef PERL_USES_PL_PIDSTATUS
if (!pid) {
/* PERL_USES_PL_PIDSTATUS is only defined when neither
waitpid() nor wait4() is available, or on OS/2, which
doesn't appear to support waiting for a progress group
member, so we can only treat a 0 pid as an unknown child.
*/
errno = ECHILD;
return -1;
}
{
if (pid > 0) {
/* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
pid, rather than a string form. */
SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
if (svp && *svp != &PL_sv_undef) {
*statusp = SvIVX(*svp);
(void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
G_DISCARD);
return pid;
}
}
else {
HE *entry;
hv_iterinit(PL_pidstatus);
if ((entry = hv_iternext(PL_pidstatus))) {
SV * const sv = hv_iterval(PL_pidstatus,entry);
I32 len;
const char * const spid = hv_iterkey(entry,&len);
assert (len == sizeof(Pid_t));
memcpy((char *)&pid, spid, len);
*statusp = SvIVX(sv);
/* The hash iterator is currently on this entry, so simply
calling hv_delete would trigger the lazy delete, which on
aggregate does more work, because next call to hv_iterinit()
would spot the flag, and have to call the delete routine,
while in the meantime any new entries can't re-use that
memory. */
hv_iterinit(PL_pidstatus);
(void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
return pid;
}
}
}
#endif
#ifdef HAS_WAITPID
# ifdef HAS_WAITPID_RUNTIME
if (!HAS_WAITPID_RUNTIME)
goto hard_way;
# endif
result = PerlProc_waitpid(pid,statusp,flags);
goto finish;
#endif
#if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
result = wait4(pid,statusp,flags,NULL);
goto finish;
#endif
#ifdef PERL_USES_PL_PIDSTATUS
#if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
hard_way:
#endif
{
if (flags)
Perl_croak(aTHX_ "Can't do waitpid with flags");
else {
while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
pidgone(result,*statusp);
if (result < 0)
*statusp = -1;
}
}
#endif
#if defined(HAS_WAITPID) || defined(HAS_WAIT4)
finish:
#endif
if (result < 0 && errno == EINTR) {
PERL_ASYNC_CHECK();
errno = EINTR; /* reset in case a signal handler changed $! */
}
return result;
}
#endif /* !DOSISH || OS2 || WIN32 || NETWARE */
#ifdef PERL_USES_PL_PIDSTATUS
void
S_pidgone(pTHX_ Pid_t pid, int status)
{
SV *sv;
sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
SvUPGRADE(sv,SVt_IV);
SvIV_set(sv, status);
return;
}
#endif
#if defined(OS2)
int pclose();
#ifdef HAS_FORK
int /* Cannot prototype with I32
in os2ish.h. */
my_syspclose(PerlIO *ptr)
#else
I32
Perl_my_pclose(pTHX_ PerlIO *ptr)
#endif
{
/* Needs work for PerlIO ! */
FILE * const f = PerlIO_findFILE(ptr);
const I32 result = pclose(f);
PerlIO_releaseFILE(ptr,f);
return result;
}
#endif
#if defined(DJGPP)
int djgpp_pclose();
I32
Perl_my_pclose(pTHX_ PerlIO *ptr)
{
/* Needs work for PerlIO ! */
FILE * const f = PerlIO_findFILE(ptr);
I32 result = djgpp_pclose(f);
result = (result << 8) & 0xff00;
PerlIO_releaseFILE(ptr,f);
return result;
}
#endif
#define PERL_REPEATCPY_LINEAR 4
void
Perl_repeatcpy(char *to, const char *from, I32 len, IV count)
{
PERL_ARGS_ASSERT_REPEATCPY;
assert(len >= 0);
if (count < 0)
croak_memory_wrap();
if (len == 1)
memset(to, *from, count);
else if (count) {
char *p = to;
IV items, linear, half;
linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
for (items = 0; items < linear; ++items) {
const char *q = from;
IV todo;
for (todo = len; todo > 0; todo--)
*p++ = *q++;
}
half = count / 2;
while (items <= half) {
IV size = items * len;
memcpy(p, to, size);
p += size;
items *= 2;
}
if (count > items)
memcpy(p, to, (count - items) * len);
}
}
#ifndef HAS_RENAME
I32
Perl_same_dirent(pTHX_ const char *a, const char *b)
{
char *fa = strrchr(a,'/');
char *fb = strrchr(b,'/');
Stat_t tmpstatbuf1;
Stat_t tmpstatbuf2;
SV * const tmpsv = sv_newmortal();
PERL_ARGS_ASSERT_SAME_DIRENT;
if (fa)
fa++;
else
fa = a;
if (fb)
fb++;
else
fb = b;
if (strNE(a,b))
return FALSE;
if (fa == a)
sv_setpvs(tmpsv, ".");
else
sv_setpvn(tmpsv, a, fa - a);
if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
return FALSE;
if (fb == b)
sv_setpvs(tmpsv, ".");
else
sv_setpvn(tmpsv, b, fb - b);
if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
return FALSE;
return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
}
#endif /* !HAS_RENAME */
char*
Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
const char *const *const search_ext, I32 flags)
{
const char *xfound = NULL;
char *xfailed = NULL;
char tmpbuf[MAXPATHLEN];
char *s;
I32 len = 0;
int retval;
char *bufend;
#if defined(DOSISH) && !defined(OS2)
# define SEARCH_EXTS ".bat", ".cmd", NULL
# define MAX_EXT_LEN 4
#endif
#ifdef OS2
# define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
# define MAX_EXT_LEN 4
#endif
#ifdef VMS
# define SEARCH_EXTS ".pl", ".com", NULL
# define MAX_EXT_LEN 4
#endif
/* additional extensions to try in each dir if scriptname not found */
#ifdef SEARCH_EXTS
static const char *const exts[] = { SEARCH_EXTS };
const char *const *const ext = search_ext ? search_ext : exts;
int extidx = 0, i = 0;
const char *curext = NULL;
#else
PERL_UNUSED_ARG(search_ext);
# define MAX_EXT_LEN 0
#endif
PERL_ARGS_ASSERT_FIND_SCRIPT;
/*
* If dosearch is true and if scriptname does not contain path
* delimiters, search the PATH for scriptname.
*
* If SEARCH_EXTS is also defined, will look for each
* scriptname{SEARCH_EXTS} whenever scriptname is not found
* while searching the PATH.
*
* Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
* proceeds as follows:
* If DOSISH or VMSISH:
* + look for ./scriptname{,.foo,.bar}
* + search the PATH for scriptname{,.foo,.bar}
*
* If !DOSISH:
* + look *only* in the PATH for scriptname{,.foo,.bar} (note
* this will not look in '.' if it's not in the PATH)
*/
tmpbuf[0] = '\0';
#ifdef VMS
# ifdef ALWAYS_DEFTYPES
len = strlen(scriptname);
if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
int idx = 0, deftypes = 1;
bool seen_dot = 1;
const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
# else
if (dosearch) {
int idx = 0, deftypes = 1;
bool seen_dot = 1;
const int hasdir = (strpbrk(scriptname,":[</") != NULL);
# endif
/* The first time through, just add SEARCH_EXTS to whatever we
* already have, so we can check for default file types. */
while (deftypes ||
(!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
{
Stat_t statbuf;
if (deftypes) {
deftypes = 0;
*tmpbuf = '\0';
}
if ((strlen(tmpbuf) + strlen(scriptname)
+ MAX_EXT_LEN) >= sizeof tmpbuf)
continue; /* don't search dir with too-long name */
my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
#else /* !VMS */
#ifdef DOSISH
if (strEQ(scriptname, "-"))
dosearch = 0;
if (dosearch) { /* Look in '.' first. */
const char *cur = scriptname;
#ifdef SEARCH_EXTS
if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
while (ext[i])
if (strEQ(ext[i++],curext)) {
extidx = -1; /* already has an ext */
break;
}
do {
#endif
DEBUG_p(PerlIO_printf(Perl_debug_log,
"Looking for %s\n",cur));
{
Stat_t statbuf;
if (PerlLIO_stat(cur,&statbuf) >= 0
&& !S_ISDIR(statbuf.st_mode)) {
dosearch = 0;
scriptname = cur;
#ifdef SEARCH_EXTS
break;
#endif
}
}
#ifdef SEARCH_EXTS
if (cur == scriptname) {
len = strlen(scriptname);
if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
break;
my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
cur = tmpbuf;
}
} while (extidx >= 0 && ext[extidx] /* try an extension? */
&& my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
#endif
}
#endif
if (dosearch && !strchr(scriptname, '/')
#ifdef DOSISH
&& !strchr(scriptname, '\\')
#endif
&& (s = PerlEnv_getenv("PATH")))
{
bool seen_dot = 0;
bufend = s + strlen(s);
while (s < bufend) {
Stat_t statbuf;
# ifdef DOSISH
for (len = 0; *s
&& *s != ';'; len++, s++) {
if (len < sizeof tmpbuf)
tmpbuf[len] = *s;
}
if (len < sizeof tmpbuf)
tmpbuf[len] = '\0';
# else
s = delimcpy_no_escape(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
':', &len);
# endif
if (s < bufend)
s++;
if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
continue; /* don't search dir with too-long name */
if (len
# ifdef DOSISH
&& tmpbuf[len - 1] != '/'
&& tmpbuf[len - 1] != '\\'
# endif
)
tmpbuf[len++] = '/';
if (len == 2 && tmpbuf[0] == '.')
seen_dot = 1;
(void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
#endif /* !VMS */
#ifdef SEARCH_EXTS
len = strlen(tmpbuf);
if (extidx > 0) /* reset after previous loop */
extidx = 0;
do {
#endif
DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
retval = PerlLIO_stat(tmpbuf,&statbuf);
if (S_ISDIR(statbuf.st_mode)) {
retval = -1;
}
#ifdef SEARCH_EXTS
} while ( retval < 0 /* not there */
&& extidx>=0 && ext[extidx] /* try an extension? */
&& my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
);
#endif
if (retval < 0)
continue;
if (S_ISREG(statbuf.st_mode)
&& cando(S_IRUSR,TRUE,&statbuf)
#if !defined(DOSISH)
&& cando(S_IXUSR,TRUE,&statbuf)
#endif
)
{
xfound = tmpbuf; /* bingo! */
break;
}
if (!xfailed)
xfailed = savepv(tmpbuf);
}
#ifndef DOSISH
{
Stat_t statbuf;
if (!xfound && !seen_dot && !xfailed &&
(PerlLIO_stat(scriptname,&statbuf) < 0
|| S_ISDIR(statbuf.st_mode)))
#endif
seen_dot = 1; /* Disable message. */
#ifndef DOSISH
}
#endif
if (!xfound) {
if (flags & 1) { /* do or die? */
/* diag_listed_as: Can't execute %s */
Perl_croak(aTHX_ "Can't %s %s%s%s",
(xfailed ? "execute" : "find"),
(xfailed ? xfailed : scriptname),
(xfailed ? "" : " on PATH"),
(xfailed || seen_dot) ? "" : ", '.' not in PATH");
}
scriptname = NULL;
}
Safefree(xfailed);
scriptname = xfound;
}
return (scriptname ? savepv(scriptname) : NULL);
}
#ifndef PERL_GET_CONTEXT_DEFINED
void *
Perl_get_context(void)
{
#if defined(USE_ITHREADS)
dVAR;
# ifdef OLD_PTHREADS_API
pthread_addr_t t;
int error = pthread_getspecific(PL_thr_key, &t)
if (error)
Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
return (void*)t;
# elif defined(I_MACH_CTHREADS)
return (void*)cthread_data(cthread_self());
# else
return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
# endif
#else
return (void*)NULL;
#endif
}
void
Perl_set_context(void *t)
{
#if defined(USE_ITHREADS)
dVAR;
#endif
PERL_ARGS_ASSERT_SET_CONTEXT;
#if defined(USE_ITHREADS)
# ifdef I_MACH_CTHREADS
cthread_set_data(cthread_self(), t);
# else
{
const int error = pthread_setspecific(PL_thr_key, t);
if (error)
Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
}
# endif
#else
PERL_UNUSED_ARG(t);
#endif
}
#endif /* !PERL_GET_CONTEXT_DEFINED */
#if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
struct perl_vars *
Perl_GetVars(pTHX)
{
PERL_UNUSED_CONTEXT;
return &PL_Vars;
}
#endif
char **
Perl_get_op_names(pTHX)
{
PERL_UNUSED_CONTEXT;
return (char **)PL_op_name;
}
char **
Perl_get_op_descs(pTHX)
{
PERL_UNUSED_CONTEXT;
return (char **)PL_op_desc;
}
const char *
Perl_get_no_modify(pTHX)
{
PERL_UNUSED_CONTEXT;
return PL_no_modify;
}
U32 *
Perl_get_opargs(pTHX)
{
PERL_UNUSED_CONTEXT;
return (U32 *)PL_opargs;
}
PPADDR_t*
Perl_get_ppaddr(pTHX)
{
dVAR;
PERL_UNUSED_CONTEXT;
return (PPADDR_t*)PL_ppaddr;
}
#ifndef HAS_GETENV_LEN
char *
Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
{
char * const env_trans = PerlEnv_getenv(env_elem);
PERL_UNUSED_CONTEXT;
PERL_ARGS_ASSERT_GETENV_LEN;
if (env_trans)
*len = strlen(env_trans);
return env_trans;
}
#endif
MGVTBL*
Perl_get_vtbl(pTHX_ int vtbl_id)
{
PERL_UNUSED_CONTEXT;
return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
? NULL : (MGVTBL*)PL_magic_vtables + vtbl_id;
}
I32
Perl_my_fflush_all(pTHX)
{
#if defined(USE_PERLIO) || defined(FFLUSH_NULL)
return PerlIO_flush(NULL);
#else
# if defined(HAS__FWALK)
extern int fflush(FILE *);
/* undocumented, unprototyped, but very useful BSDism */
extern void _fwalk(int (*)(FILE *));
_fwalk(&fflush);
return 0;
# else
# if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
long open_max = -1;
# ifdef PERL_FFLUSH_ALL_FOPEN_MAX
open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
# elif defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
open_max = sysconf(_SC_OPEN_MAX);
# elif defined(FOPEN_MAX)
open_max = FOPEN_MAX;
# elif defined(OPEN_MAX)
open_max = OPEN_MAX;
# elif defined(_NFILE)
open_max = _NFILE;
# endif
if (open_max > 0) {
long i;
for (i = 0; i < open_max; i++)
if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
STDIO_STREAM_ARRAY[i]._file < open_max &&
STDIO_STREAM_ARRAY[i]._flag)
PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
return 0;
}
# endif
SETERRNO(EBADF,RMS_IFI);
return EOF;
# endif
#endif
}
void
Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
{
if (ckWARN(WARN_IO)) {
HEK * const name
= gv && (isGV_with_GP(gv))
? GvENAME_HEK((gv))
: NULL;
const char * const direction = have == '>' ? "out" : "in";
if (name && HEK_LEN(name))
Perl_warner(aTHX_ packWARN(WARN_IO),
"Filehandle %" HEKf " opened only for %sput",
HEKfARG(name), direction);
else
Perl_warner(aTHX_ packWARN(WARN_IO),
"Filehandle opened only for %sput", direction);
}
}
void
Perl_report_evil_fh(pTHX_ const GV *gv)
{
const IO *io = gv ? GvIO(gv) : NULL;
const PERL_BITFIELD16 op = PL_op->op_type;
const char *vile;
I32 warn_type;
if (io && IoTYPE(io) == IoTYPE_CLOSED) {
vile = "closed";
warn_type = WARN_CLOSED;
}
else {
vile = "unopened";
warn_type = WARN_UNOPENED;
}
if (ckWARN(warn_type)) {
SV * const name
= gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
const char * const pars =
(const char *)(OP_IS_FILETEST(op) ? "" : "()");
const char * const func =
(const char *)
(op == OP_READLINE || op == OP_RCATLINE
? "readline" : /* "<HANDLE>" not nice */
op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
PL_op_desc[op]);
const char * const type =
(const char *)
(OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
? "socket" : "filehandle");
const bool have_name = name && SvCUR(name);
Perl_warner(aTHX_ packWARN(warn_type),
"%s%s on %s %s%s%" SVf, func, pars, vile, type,
have_name ? " " : "",
SVfARG(have_name ? name : &PL_sv_no));
if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
Perl_warner(
aTHX_ packWARN(warn_type),
"\t(Are you trying to call %s%s on dirhandle%s%" SVf "?)\n",
func, pars, have_name ? " " : "",
SVfARG(have_name ? name : &PL_sv_no)
);
}
}
/* To workaround core dumps from the uninitialised tm_zone we get the
* system to give us a reasonable struct to copy. This fix means that
* strftime uses the tm_zone and tm_gmtoff values returned by
* localtime(time()). That should give the desired result most of the
* time. But probably not always!
*
* This does not address tzname aspects of NETaa14816.
*
*/
#ifdef __GLIBC__
# ifndef STRUCT_TM_HASZONE
# define STRUCT_TM_HASZONE
# endif
#endif
#ifdef STRUCT_TM_HASZONE /* Backward compat */
# ifndef HAS_TM_TM_ZONE
# define HAS_TM_TM_ZONE
# endif
#endif
void
Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
{
#ifdef HAS_TM_TM_ZONE
Time_t now;
const struct tm* my_tm;
PERL_UNUSED_CONTEXT;
PERL_ARGS_ASSERT_INIT_TM;
(void)time(&now);
my_tm = localtime(&now);
if (my_tm)
Copy(my_tm, ptm, 1, struct tm);
#else
PERL_UNUSED_CONTEXT;
PERL_ARGS_ASSERT_INIT_TM;
PERL_UNUSED_ARG(ptm);
#endif
}
/*
* mini_mktime - normalise struct tm values without the localtime()
* semantics (and overhead) of mktime().
*/
void
Perl_mini_mktime(struct tm *ptm)
{
int yearday;
int secs;
int month, mday, year, jday;
int odd_cent, odd_year;
PERL_ARGS_ASSERT_MINI_MKTIME;
#define DAYS_PER_YEAR 365
#define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
#define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
#define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
#define SECS_PER_HOUR (60*60)
#define SECS_PER_DAY (24*SECS_PER_HOUR)
/* parentheses deliberately absent on these two, otherwise they don't work */
#define MONTH_TO_DAYS 153/5
#define DAYS_TO_MONTH 5/153
/* offset to bias by March (month 4) 1st between month/mday & year finding */
#define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
/* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
#define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
/*
* Year/day algorithm notes:
*
* With a suitable offset for numeric value of the month, one can find
* an offset into the year by considering months to have 30.6 (153/5) days,
* using integer arithmetic (i.e., with truncation). To avoid too much
* messing about with leap days, we consider January and February to be
* the 13th and 14th month of the previous year. After that transformation,
* we need the month index we use to be high by 1 from 'normal human' usage,
* so the month index values we use run from 4 through 15.
*
* Given that, and the rules for the Gregorian calendar (leap years are those
* divisible by 4 unless also divisible by 100, when they must be divisible
* by 400 instead), we can simply calculate the number of days since some
* arbitrary 'beginning of time' by futzing with the (adjusted) year number,
* the days we derive from our month index, and adding in the day of the
* month. The value used here is not adjusted for the actual origin which
* it normally would use (1 January A.D. 1), since we're not exposing it.
* We're only building the value so we can turn around and get the
* normalised values for the year, month, day-of-month, and day-of-year.
*
* For going backward, we need to bias the value we're using so that we find
* the right year value. (Basically, we don't want the contribution of
* March 1st to the number to apply while deriving the year). Having done
* that, we 'count up' the contribution to the year number by accounting for
* full quadracenturies (400-year periods) with their extra leap days, plus
* the contribution from full centuries (to avoid counting in the lost leap
* days), plus the contribution from full quad-years (to count in the normal
* leap days), plus the leftover contribution from any non-leap years.
* At this point, if we were working with an actual leap day, we'll have 0
* days left over. This is also true for March 1st, however. So, we have
* to special-case that result, and (earlier) keep track of the 'odd'
* century and year contributions. If we got 4 extra centuries in a qcent,
* or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
* Otherwise, we add back in the earlier bias we removed (the 123 from
* figuring in March 1st), find the month index (integer division by 30.6),
* and the remainder is the day-of-month. We then have to convert back to
* 'real' months (including fixing January and February from being 14/15 in
* the previous year to being in the proper year). After that, to get
* tm_yday, we work with the normalised year and get a new yearday value for
* January 1st, which we subtract from the yearday value we had earlier,
* representing the date we've re-built. This is done from January 1
* because tm_yday is 0-origin.
*
* Since POSIX time routines are only guaranteed to work for times since the
* UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
* applies Gregorian calendar rules even to dates before the 16th century
* doesn't bother me. Besides, you'd need cultural context for a given
* date to know whether it was Julian or Gregorian calendar, and that's
* outside the scope for this routine. Since we convert back based on the
* same rules we used to build the yearday, you'll only get strange results
* for input which needed normalising, or for the 'odd' century years which
* were leap years in the Julian calendar but not in the Gregorian one.
* I can live with that.
*
* This algorithm also fails to handle years before A.D. 1 gracefully, but
* that's still outside the scope for POSIX time manipulation, so I don't
* care.
*
* - lwall
*/
year = 1900 + ptm->tm_year;
month = ptm->tm_mon;
mday = ptm->tm_mday;
jday = 0;
if (month >= 2)
month+=2;
else
month+=14, year--;
yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
yearday += month*MONTH_TO_DAYS + mday + jday;
/*
* Note that we don't know when leap-seconds were or will be,
* so we have to trust the user if we get something which looks
* like a sensible leap-second. Wild values for seconds will
* be rationalised, however.
*/
if ((unsigned) ptm->tm_sec <= 60) {
secs = 0;
}
else {
secs = ptm->tm_sec;
ptm->tm_sec = 0;
}
secs += 60 * ptm->tm_min;
secs += SECS_PER_HOUR * ptm->tm_hour;
if (secs < 0) {
if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
/* got negative remainder, but need positive time */
/* back off an extra day to compensate */
yearday += (secs/SECS_PER_DAY)-1;
secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
}
else {
yearday += (secs/SECS_PER_DAY);
secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
}
}
else if (secs >= SECS_PER_DAY) {
yearday += (secs/SECS_PER_DAY);
secs %= SECS_PER_DAY;
}
ptm->tm_hour = secs/SECS_PER_HOUR;
secs %= SECS_PER_HOUR;
ptm->tm_min = secs/60;
secs %= 60;
ptm->tm_sec += secs;
/* done with time of day effects */
/*
* The algorithm for yearday has (so far) left it high by 428.
* To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
* bias it by 123 while trying to figure out what year it
* really represents. Even with this tweak, the reverse
* translation fails for years before A.D. 0001.
* It would still fail for Feb 29, but we catch that one below.
*/
jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
yearday -= YEAR_ADJUST;
year = (yearday / DAYS_PER_QCENT) * 400;
yearday %= DAYS_PER_QCENT;
odd_cent = yearday / DAYS_PER_CENT;
year += odd_cent * 100;
yearday %= DAYS_PER_CENT;
year += (yearday / DAYS_PER_QYEAR) * 4;
yearday %= DAYS_PER_QYEAR;
odd_year = yearday / DAYS_PER_YEAR;
year += odd_year;
yearday %= DAYS_PER_YEAR;
if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
month = 1;
yearday = 29;
}
else {
yearday += YEAR_ADJUST; /* recover March 1st crock */
month = yearday*DAYS_TO_MONTH;
yearday -= month*MONTH_TO_DAYS;
/* recover other leap-year adjustment */
if (month > 13) {
month-=14;
year++;
}
else {
month-=2;
}
}
ptm->tm_year = year - 1900;
if (yearday) {
ptm->tm_mday = yearday;
ptm->tm_mon = month;
}
else {
ptm->tm_mday = 31;
ptm->tm_mon = month - 1;
}
/* re-build yearday based on Jan 1 to get tm_yday */
year--;
yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
yearday += 14*MONTH_TO_DAYS + 1;
ptm->tm_yday = jday - yearday;
ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
}
char *
Perl_my_strftime(pTHX_ const char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
{
#ifdef HAS_STRFTIME
/* strftime(), but with a different API so that the return value is a pointer
* to the formatted result (which MUST be arranged to be FREED BY THE
* CALLER). This allows this function to increase the buffer size as needed,
* so that the caller doesn't have to worry about that.
*
* Note that yday and wday effectively are ignored by this function, as
* mini_mktime() overwrites them */
char *buf;
int buflen;
struct tm mytm;
int len;
PERL_ARGS_ASSERT_MY_STRFTIME;
init_tm(&mytm); /* XXX workaround - see init_tm() above */
mytm.tm_sec = sec;
mytm.tm_min = min;
mytm.tm_hour = hour;
mytm.tm_mday = mday;
mytm.tm_mon = mon;
mytm.tm_year = year;
mytm.tm_wday = wday;
mytm.tm_yday = yday;
mytm.tm_isdst = isdst;
mini_mktime(&mytm);
/* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
#if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
STMT_START {
struct tm mytm2;
mytm2 = mytm;
mktime(&mytm2);
#ifdef HAS_TM_TM_GMTOFF
mytm.tm_gmtoff = mytm2.tm_gmtoff;
#endif
#ifdef HAS_TM_TM_ZONE
mytm.tm_zone = mytm2.tm_zone;
#endif
} STMT_END;
#endif
buflen = 64;
Newx(buf, buflen, char);
GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); /* fmt checked by caller */
len = strftime(buf, buflen, fmt, &mytm);
GCC_DIAG_RESTORE_STMT;
/*
** The following is needed to handle to the situation where
** tmpbuf overflows. Basically we want to allocate a buffer
** and try repeatedly. The reason why it is so complicated
** is that getting a return value of 0 from strftime can indicate
** one of the following:
** 1. buffer overflowed,
** 2. illegal conversion specifier, or
** 3. the format string specifies nothing to be returned(not
** an error). This could be because format is an empty string
** or it specifies %p that yields an empty string in some locale.
** If there is a better way to make it portable, go ahead by
** all means.
*/
if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
return buf;
else {
/* Possibly buf overflowed - try again with a bigger buf */
const int fmtlen = strlen(fmt);
int bufsize = fmtlen + buflen;
Renew(buf, bufsize, char);
while (buf) {
GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); /* fmt checked by caller */
buflen = strftime(buf, bufsize, fmt, &mytm);
GCC_DIAG_RESTORE_STMT;
if (buflen > 0 && buflen < bufsize)
break;
/* heuristic to prevent out-of-memory errors */
if (bufsize > 100*fmtlen) {
Safefree(buf);
buf = NULL;
break;
}
bufsize *= 2;
Renew(buf, bufsize, char);
}
return buf;
}
#else
Perl_croak(aTHX_ "panic: no strftime");
return NULL;
#endif
}
#define SV_CWD_RETURN_UNDEF \
sv_set_undef(sv); \
return FALSE
#define SV_CWD_ISDOT(dp) \
(dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
(dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
/*
=head1 Miscellaneous Functions
=for apidoc getcwd_sv
Fill C<sv> with current working directory
=cut
*/
/* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
* rewritten again by dougm, optimized for use with xs TARG, and to prefer
* getcwd(3) if available
* Comments from the original:
* This is a faster version of getcwd. It's also more dangerous
* because you might chdir out of a directory that you can't chdir
* back into. */
int
Perl_getcwd_sv(pTHX_ SV *sv)
{
#ifndef PERL_MICRO
SvTAINTED_on(sv);
PERL_ARGS_ASSERT_GETCWD_SV;
#ifdef HAS_GETCWD
{
char buf[MAXPATHLEN];
/* Some getcwd()s automatically allocate a buffer of the given
* size from the heap if they are given a NULL buffer pointer.
* The problem is that this behaviour is not portable. */
if (getcwd(buf, sizeof(buf) - 1)) {
sv_setpv(sv, buf);
return TRUE;
}
else {
SV_CWD_RETURN_UNDEF;
}
}
#else
Stat_t statbuf;
int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
int pathlen=0;
Direntry_t *dp;
SvUPGRADE(sv, SVt_PV);
if (PerlLIO_lstat(".", &statbuf) < 0) {
SV_CWD_RETURN_UNDEF;
}
orig_cdev = statbuf.st_dev;
orig_cino = statbuf.st_ino;
cdev = orig_cdev;
cino = orig_cino;
for (;;) {
DIR *dir;
int namelen;
odev = cdev;
oino = cino;
if (PerlDir_chdir("..") < 0) {
SV_CWD_RETURN_UNDEF;
}
if (PerlLIO_stat(".", &statbuf) < 0) {
SV_CWD_RETURN_UNDEF;
}
cdev = statbuf.st_dev;
cino = statbuf.st_ino;
if (odev == cdev && oino == cino) {
break;
}
if (!(dir = PerlDir_open("."))) {
SV_CWD_RETURN_UNDEF;
}
while ((dp = PerlDir_read(dir)) != NULL) {
#ifdef DIRNAMLEN
namelen = dp->d_namlen;
#else
namelen = strlen(dp->d_name);
#endif
/* skip . and .. */
if (SV_CWD_ISDOT(dp)) {
continue;
}
if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
SV_CWD_RETURN_UNDEF;
}
tdev = statbuf.st_dev;
tino = statbuf.st_ino;
if (tino == oino && tdev == odev) {
break;
}
}
if (!dp) {
SV_CWD_RETURN_UNDEF;
}
if (pathlen + namelen + 1 >= MAXPATHLEN) {
SV_CWD_RETURN_UNDEF;
}
SvGROW(sv, pathlen + namelen + 1);
if (pathlen) {
/* shift down */
Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
}
/* prepend current directory to the front */
*SvPVX(sv) = '/';
Move(dp->d_name, SvPVX(sv)+1, namelen, char);
pathlen += (namelen + 1);
#ifdef VOID_CLOSEDIR
PerlDir_close(dir);
#else
if (PerlDir_close(dir) < 0) {
SV_CWD_RETURN_UNDEF;
}
#endif
}
if (pathlen) {
SvCUR_set(sv, pathlen);
*SvEND(sv) = '\0';
SvPOK_only(sv);
if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
SV_CWD_RETURN_UNDEF;
}
}
if (PerlLIO_stat(".", &statbuf) < 0) {
SV_CWD_RETURN_UNDEF;
}
cdev = statbuf.st_dev;
cino = statbuf.st_ino;
if (cdev != orig_cdev || cino != orig_cino) {
Perl_croak(aTHX_ "Unstable directory path, "
"current directory changed unexpectedly");
}
return TRUE;
#endif
#else
return FALSE;
#endif
}
#include "vutil.c"
#if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
# define EMULATE_SOCKETPAIR_UDP
#endif
#ifdef EMULATE_SOCKETPAIR_UDP
static int
S_socketpair_udp (int fd[2]) {
dTHX;
/* Fake a datagram socketpair using UDP to localhost. */
int sockets[2] = {-1, -1};
struct sockaddr_in addresses[2];
int i;
Sock_size_t size = sizeof(struct sockaddr_in);
unsigned short port;
int got;
memset(&addresses, 0, sizeof(addresses));
i = 1;
do {
sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
if (sockets[i] == -1)
goto tidy_up_and_fail;
addresses[i].sin_family = AF_INET;
addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addresses[i].sin_port = 0; /* kernel choses port. */
if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
sizeof(struct sockaddr_in)) == -1)
goto tidy_up_and_fail;
} while (i--);
/* Now have 2 UDP sockets. Find out which port each is connected to, and
for each connect the other socket to it. */
i = 1;
do {
if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
&size) == -1)
goto tidy_up_and_fail;
if (size != sizeof(struct sockaddr_in))
goto abort_tidy_up_and_fail;
/* !1 is 0, !0 is 1 */
if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
sizeof(struct sockaddr_in)) == -1)
goto tidy_up_and_fail;
} while (i--);
/* Now we have 2 sockets connected to each other. I don't trust some other
process not to have already sent a packet to us (by random) so send
a packet from each to the other. */
i = 1;
do {
/* I'm going to send my own port number. As a short.
(Who knows if someone somewhere has sin_port as a bitfield and needs
this routine. (I'm assuming crays have socketpair)) */
port = addresses[i].sin_port;
got = PerlLIO_write(sockets[i], &port, sizeof(port));
if (got != sizeof(port)) {
if (got == -1)
goto tidy_up_and_fail;
goto abort_tidy_up_and_fail;
}
} while (i--);
/* Packets sent. I don't trust them to have arrived though.
(As I understand it Solaris TCP stack is multithreaded. Non-blocking
connect to localhost will use a second kernel thread. In 2.6 the
first thread running the connect() returns before the second completes,
so EINPROGRESS> In 2.7 the improved stack is faster and connect()
returns 0. Poor programs have tripped up. One poor program's authors'
had a 50-1 reverse stock split. Not sure how connected these were.)
So I don't trust someone not to have an unpredictable UDP stack.
*/
{
struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
fd_set rset;
FD_ZERO(&rset);
FD_SET((unsigned int)sockets[0], &rset);
FD_SET((unsigned int)sockets[1], &rset);
got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
if (got != 2 || !FD_ISSET(sockets[0], &rset)
|| !FD_ISSET(sockets[1], &rset)) {
/* I hope this is portable and appropriate. */
if (got == -1)
goto tidy_up_and_fail;
goto abort_tidy_up_and_fail;
}
}
/* And the paranoia department even now doesn't trust it to have arrive
(hence MSG_DONTWAIT). Or that what arrives was sent by us. */
{
struct sockaddr_in readfrom;
unsigned short buffer[2];
i = 1;
do {
#ifdef MSG_DONTWAIT
got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
sizeof(buffer), MSG_DONTWAIT,
(struct sockaddr *) &readfrom, &size);
#else
got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
sizeof(buffer), 0,
(struct sockaddr *) &readfrom, &size);
#endif
if (got == -1)
goto tidy_up_and_fail;
if (got != sizeof(port)
|| size != sizeof(struct sockaddr_in)
/* Check other socket sent us its port. */
|| buffer[0] != (unsigned short) addresses[!i].sin_port
/* Check kernel says we got the datagram from that socket */
|| readfrom.sin_family != addresses[!i].sin_family
|| readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
|| readfrom.sin_port != addresses[!i].sin_port)
goto abort_tidy_up_and_fail;
} while (i--);
}
/* My caller (my_socketpair) has validated that this is non-NULL */
fd[0] = sockets[0];
fd[1] = sockets[1];
/* I hereby declare this connection open. May God bless all who cross
her. */
return 0;
abort_tidy_up_and_fail:
errno = ECONNABORTED;
tidy_up_and_fail:
{
dSAVE_ERRNO;
if (sockets[0] != -1)
PerlLIO_close(sockets[0]);
if (sockets[1] != -1)
PerlLIO_close(sockets[1]);
RESTORE_ERRNO;
return -1;
}
}
#endif /* EMULATE_SOCKETPAIR_UDP */
#if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
int
Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
/* Stevens says that family must be AF_LOCAL, protocol 0.
I'm going to enforce that, then ignore it, and use TCP (or UDP). */
dTHXa(NULL);
int listener = -1;
int connector = -1;
int acceptor = -1;
struct sockaddr_in listen_addr;
struct sockaddr_in connect_addr;
Sock_size_t size;
if (protocol
#ifdef AF_UNIX
|| family != AF_UNIX
#endif
) {
errno = EAFNOSUPPORT;
return -1;
}
if (!fd) {
errno = EINVAL;
return -1;
}
#ifdef SOCK_CLOEXEC
type &= ~SOCK_CLOEXEC;
#endif
#ifdef EMULATE_SOCKETPAIR_UDP
if (type == SOCK_DGRAM)
return S_socketpair_udp(fd);
#endif
aTHXa(PERL_GET_THX);
listener = PerlSock_socket(AF_INET, type, 0);
if (listener == -1)
return -1;
memset(&listen_addr, 0, sizeof(listen_addr));
listen_addr.sin_family = AF_INET;
listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
listen_addr.sin_port = 0; /* kernel choses port. */
if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
sizeof(listen_addr)) == -1)
goto tidy_up_and_fail;
if (PerlSock_listen(listener, 1) == -1)
goto tidy_up_and_fail;
connector = PerlSock_socket(AF_INET, type, 0);
if (connector == -1)
goto tidy_up_and_fail;
/* We want to find out the port number to connect to. */
size = sizeof(connect_addr);
if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
&size) == -1)
goto tidy_up_and_fail;
if (size != sizeof(connect_addr))
goto abort_tidy_up_and_fail;
if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
sizeof(connect_addr)) == -1)
goto tidy_up_and_fail;
size = sizeof(listen_addr);
acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
&size);
if (acceptor == -1)
goto tidy_up_and_fail;
if (size != sizeof(listen_addr))
goto abort_tidy_up_and_fail;
PerlLIO_close(listener);
/* Now check we are talking to ourself by matching port and host on the
two sockets. */
if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
&size) == -1)
goto tidy_up_and_fail;
if (size != sizeof(connect_addr)
|| listen_addr.sin_family != connect_addr.sin_family
|| listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
|| listen_addr.sin_port != connect_addr.sin_port) {
goto abort_tidy_up_and_fail;
}
fd[0] = connector;
fd[1] = acceptor;
return 0;
abort_tidy_up_and_fail:
#ifdef ECONNABORTED
errno = ECONNABORTED; /* This would be the standard thing to do. */
#elif defined(ECONNREFUSED)
errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
#else
errno = ETIMEDOUT; /* Desperation time. */
#endif
tidy_up_and_fail:
{
dSAVE_ERRNO;
if (listener != -1)
PerlLIO_close(listener);
if (connector != -1)
PerlLIO_close(connector);
if (acceptor != -1)
PerlLIO_close(acceptor);
RESTORE_ERRNO;
return -1;
}
}
#else
/* In any case have a stub so that there's code corresponding
* to the my_socketpair in embed.fnc. */
int
Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
#ifdef HAS_SOCKETPAIR
return socketpair(family, type, protocol, fd);
#else
return -1;
#endif
}
#endif
/*
=for apidoc sv_nosharing
Dummy routine which "shares" an SV when there is no sharing module present.
Or "locks" it. Or "unlocks" it. In other
words, ignores its single SV argument.
Exists to avoid test for a C<NULL> function pointer and because it could
potentially warn under some level of strict-ness.
=cut
*/
void
Perl_sv_nosharing(pTHX_ SV *sv)
{
PERL_UNUSED_CONTEXT;
PERL_UNUSED_ARG(sv);
}
/*
=for apidoc sv_destroyable
Dummy routine which reports that object can be destroyed when there is no
sharing module present. It ignores its single SV argument, and returns
'true'. Exists to avoid test for a C<NULL> function pointer and because it
could potentially warn under some level of strict-ness.
=cut
*/
bool
Perl_sv_destroyable(pTHX_ SV *sv)
{
PERL_UNUSED_CONTEXT;
PERL_UNUSED_ARG(sv);
return TRUE;
}
U32
Perl_parse_unicode_opts(pTHX_ const char **popt)
{
const char *p = *popt;
U32 opt = 0;
PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
if (*p) {
if (isDIGIT(*p)) {
const char* endptr = p + strlen(p);
UV uv;
if (grok_atoUV(p, &uv, &endptr) && uv <= U32_MAX) {
opt = (U32)uv;
p = endptr;
if (p && *p && *p != '\n' && *p != '\r') {
if (isSPACE(*p))
goto the_end_of_the_opts_parser;
else
Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
}
}
else {
Perl_croak(aTHX_ "Invalid number '%s' for -C option.\n", p);
}
}
else {
for (; *p; p++) {
switch (*p) {
case PERL_UNICODE_STDIN:
opt |= PERL_UNICODE_STDIN_FLAG; break;
case PERL_UNICODE_STDOUT:
opt |= PERL_UNICODE_STDOUT_FLAG; break;
case PERL_UNICODE_STDERR:
opt |= PERL_UNICODE_STDERR_FLAG; break;
case PERL_UNICODE_STD:
opt |= PERL_UNICODE_STD_FLAG; break;
case PERL_UNICODE_IN:
opt |= PERL_UNICODE_IN_FLAG; break;
case PERL_UNICODE_OUT:
opt |= PERL_UNICODE_OUT_FLAG; break;
case PERL_UNICODE_INOUT:
opt |= PERL_UNICODE_INOUT_FLAG; break;
case PERL_UNICODE_LOCALE:
opt |= PERL_UNICODE_LOCALE_FLAG; break;
case PERL_UNICODE_ARGV:
opt |= PERL_UNICODE_ARGV_FLAG; break;
case PERL_UNICODE_UTF8CACHEASSERT:
opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
default:
if (*p != '\n' && *p != '\r') {
if(isSPACE(*p)) goto the_end_of_the_opts_parser;
else
Perl_croak(aTHX_
"Unknown Unicode option letter '%c'", *p);
}
}
}
}
}
else
opt = PERL_UNICODE_DEFAULT_FLAGS;
the_end_of_the_opts_parser:
if (opt & ~PERL_UNICODE_ALL_FLAGS)
Perl_croak(aTHX_ "Unknown Unicode option value %" UVuf,
(UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
*popt = p;
return opt;
}
#ifdef VMS
# include <starlet.h>
#endif
U32
Perl_seed(pTHX)
{
/*
* This is really just a quick hack which grabs various garbage
* values. It really should be a real hash algorithm which
* spreads the effect of every input bit onto every output bit,
* if someone who knows about such things would bother to write it.
* Might be a good idea to add that function to CORE as well.
* No numbers below come from careful analysis or anything here,
* except they are primes and SEED_C1 > 1E6 to get a full-width
* value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
* probably be bigger too.
*/
#if RANDBITS > 16
# define SEED_C1 1000003
#define SEED_C4 73819
#else
# define SEED_C1 25747
#define SEED_C4 20639
#endif
#define SEED_C2 3
#define SEED_C3 269
#define SEED_C5 26107
#ifndef PERL_NO_DEV_RANDOM
int fd;
#endif
U32 u;
#ifdef HAS_GETTIMEOFDAY
struct timeval when;
#else
Time_t when;
#endif
/* This test is an escape hatch, this symbol isn't set by Configure. */
#ifndef PERL_NO_DEV_RANDOM
#ifndef PERL_RANDOM_DEVICE
/* /dev/random isn't used by default because reads from it will block
* if there isn't enough entropy available. You can compile with
* PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
* is enough real entropy to fill the seed. */
# ifdef __amigaos4__
# define PERL_RANDOM_DEVICE "RANDOM:SIZE=4"
# else
# define PERL_RANDOM_DEVICE "/dev/urandom"
# endif
#endif
fd = PerlLIO_open_cloexec(PERL_RANDOM_DEVICE, 0);
if (fd != -1) {
if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
u = 0;
PerlLIO_close(fd);
if (u)
return u;
}
#endif
#ifdef HAS_GETTIMEOFDAY
PerlProc_gettimeofday(&when,NULL);
u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
#else
(void)time(&when);
u = (U32)SEED_C1 * when;
#endif
u += SEED_C3 * (U32)PerlProc_getpid();
u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
#ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
u += SEED_C5 * (U32)PTR2UV(&when);
#endif
return u;
}
void
Perl_get_hash_seed(pTHX_ unsigned char * const seed_buffer)
{
#ifndef NO_PERL_HASH_ENV
const char *env_pv;
#endif
unsigned long i;
PERL_ARGS_ASSERT_GET_HASH_SEED;
#ifndef NO_PERL_HASH_ENV
env_pv= PerlEnv_getenv("PERL_HASH_SEED");
if ( env_pv )
{
/* ignore leading spaces */
while (isSPACE(*env_pv))
env_pv++;
# ifdef USE_PERL_PERTURB_KEYS
/* if they set it to "0" we disable key traversal randomization completely */
if (strEQ(env_pv,"0")) {
PL_hash_rand_bits_enabled= 0;
} else {
/* otherwise switch to deterministic mode */
PL_hash_rand_bits_enabled= 2;
}
# endif
/* ignore a leading 0x... if it is there */
if (env_pv[0] == '0' && env_pv[1] == 'x')
env_pv += 2;
for( i = 0; isXDIGIT(*env_pv) && i < PERL_HASH_SEED_BYTES; i++ ) {
seed_buffer[i] = READ_XDIGIT(env_pv) << 4;
if ( isXDIGIT(*env_pv)) {
seed_buffer[i] |= READ_XDIGIT(env_pv);
}
}
while (isSPACE(*env_pv))
env_pv++;
if (*env_pv && !isXDIGIT(*env_pv)) {
Perl_warn(aTHX_ "perl: warning: Non hex character in '$ENV{PERL_HASH_SEED}', seed only partially set\n");
}
/* should we check for unparsed crap? */
/* should we warn about unused hex? */
/* should we warn about insufficient hex? */
}
else
#endif /* NO_PERL_HASH_ENV */
{
for( i = 0; i < PERL_HASH_SEED_BYTES; i++ ) {
seed_buffer[i] = (unsigned char)(Perl_internal_drand48() * (U8_MAX+1));
}
}
#ifdef USE_PERL_PERTURB_KEYS
{ /* initialize PL_hash_rand_bits from the hash seed.
* This value is highly volatile, it is updated every
* hash insert, and is used as part of hash bucket chain
* randomization and hash iterator randomization. */
PL_hash_rand_bits= 0xbe49d17f; /* I just picked a number */
for( i = 0; i < sizeof(UV) ; i++ ) {
PL_hash_rand_bits += seed_buffer[i % PERL_HASH_SEED_BYTES];
PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,8);
}
}
# ifndef NO_PERL_HASH_ENV
env_pv= PerlEnv_getenv("PERL_PERTURB_KEYS");
if (env_pv) {
if (strEQ(env_pv,"0") || strEQ(env_pv,"NO")) {
PL_hash_rand_bits_enabled= 0;
} else if (strEQ(env_pv,"1") || strEQ(env_pv,"RANDOM")) {
PL_hash_rand_bits_enabled= 1;
} else if (strEQ(env_pv,"2") || strEQ(env_pv,"DETERMINISTIC")) {
PL_hash_rand_bits_enabled= 2;
} else {
Perl_warn(aTHX_ "perl: warning: strange setting in '$ENV{PERL_PERTURB_KEYS}': '%s'\n", env_pv);
}
}
# endif
#endif
}
#ifdef PERL_GLOBAL_STRUCT
#define PERL_GLOBAL_STRUCT_INIT
#include "opcode.h" /* the ppaddr and check */
struct perl_vars *
Perl_init_global_struct(pTHX)
{
struct perl_vars *plvarsp = NULL;
# ifdef PERL_GLOBAL_STRUCT
const IV nppaddr = C_ARRAY_LENGTH(Gppaddr);
const IV ncheck = C_ARRAY_LENGTH(Gcheck);
PERL_UNUSED_CONTEXT;
# ifdef PERL_GLOBAL_STRUCT_PRIVATE
/* PerlMem_malloc() because can't use even safesysmalloc() this early. */
plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
if (!plvarsp)
exit(1);
# else
plvarsp = PL_VarsPtr;
# endif /* PERL_GLOBAL_STRUCT_PRIVATE */
# undef PERLVAR
# undef PERLVARA
# undef PERLVARI
# undef PERLVARIC
# define PERLVAR(prefix,var,type) /**/
# define PERLVARA(prefix,var,n,type) /**/
# define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
# define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
# include "perlvars.h"
# undef PERLVAR
# undef PERLVARA
# undef PERLVARI
# undef PERLVARIC
# ifdef PERL_GLOBAL_STRUCT
plvarsp->Gppaddr =
(Perl_ppaddr_t*)
PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
if (!plvarsp->Gppaddr)
exit(1);
plvarsp->Gcheck =
(Perl_check_t*)
PerlMem_malloc(ncheck * sizeof(Perl_check_t));
if (!plvarsp->Gcheck)
exit(1);
Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
# endif
# ifdef PERL_SET_VARS
PERL_SET_VARS(plvarsp);
# endif
# ifdef PERL_GLOBAL_STRUCT_PRIVATE
plvarsp->Gsv_placeholder.sv_flags = 0;
memset(plvarsp->Ghash_seed, 0, sizeof(plvarsp->Ghash_seed));
# endif
# undef PERL_GLOBAL_STRUCT_INIT
# endif
return plvarsp;
}
#endif /* PERL_GLOBAL_STRUCT */
#ifdef PERL_GLOBAL_STRUCT
void
Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
{
int veto = plvarsp->Gveto_cleanup;
PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
PERL_UNUSED_CONTEXT;
# ifdef PERL_GLOBAL_STRUCT
# ifdef PERL_UNSET_VARS
PERL_UNSET_VARS(plvarsp);
# endif
if (veto)
return;
free(plvarsp->Gppaddr);
free(plvarsp->Gcheck);
# ifdef PERL_GLOBAL_STRUCT_PRIVATE
free(plvarsp);
# endif
# endif
}
#endif /* PERL_GLOBAL_STRUCT */
#ifdef PERL_MEM_LOG
/* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including
* the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
* given, and you supply your own implementation.
*
* The default implementation reads a single env var, PERL_MEM_LOG,
* expecting one or more of the following:
*
* \d+ - fd fd to write to : must be 1st (grok_atoUV)
* 'm' - memlog was PERL_MEM_LOG=1
* 's' - svlog was PERL_SV_LOG=1
* 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
*
* This makes the logger controllable enough that it can reasonably be
* added to the system perl.
*/
/* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
* the Perl_mem_log_...() will use (either via sprintf or snprintf).
*/
#define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
/* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
* writes to. In the default logger, this is settable at runtime.
*/
#ifndef PERL_MEM_LOG_FD
# define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
#endif
#ifndef PERL_MEM_LOG_NOIMPL
# ifdef DEBUG_LEAKING_SCALARS
# define SV_LOG_SERIAL_FMT " [%lu]"
# define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
# else
# define SV_LOG_SERIAL_FMT
# define _SV_LOG_SERIAL_ARG(sv)
# endif
static void
S_mem_log_common(enum mem_log_type mlt, const UV n,
const UV typesize, const char *type_name, const SV *sv,
Malloc_t oldalloc, Malloc_t newalloc,
const char *filename, const int linenumber,
const char *funcname)
{
const char *pmlenv;
PERL_ARGS_ASSERT_MEM_LOG_COMMON;
pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
if (!pmlenv)
return;
if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
{
/* We can't use SVs or PerlIO for obvious reasons,
* so we'll use stdio and low-level IO instead. */
char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
# ifdef HAS_GETTIMEOFDAY
# define MEM_LOG_TIME_FMT "%10d.%06d: "
# define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
struct timeval tv;
gettimeofday(&tv, 0);
# else
# define MEM_LOG_TIME_FMT "%10d: "
# define MEM_LOG_TIME_ARG (int)when
Time_t when;
(void)time(&when);
# endif
/* If there are other OS specific ways of hires time than
* gettimeofday() (see dist/Time-HiRes), the easiest way is
* probably that they would be used to fill in the struct
* timeval. */
{
STRLEN len;
const char* endptr = pmlenv + stren(pmlenv);
int fd;
UV uv;
if (grok_atoUV(pmlenv, &uv, &endptr) /* Ignore endptr. */
&& uv && uv <= PERL_INT_MAX
) {
fd = (int)uv;
} else {
fd = PERL_MEM_LOG_FD;
}
if (strchr(pmlenv, 't')) {
len = my_snprintf(buf, sizeof(buf),
MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
}
switch (mlt) {
case MLT_ALLOC:
len = my_snprintf(buf, sizeof(buf),
"alloc: %s:%d:%s: %" IVdf " %" UVuf
" %s = %" IVdf ": %" UVxf "\n",
filename, linenumber, funcname, n, typesize,
type_name, n * typesize, PTR2UV(newalloc));
break;
case MLT_REALLOC:
len = my_snprintf(buf, sizeof(buf),
"realloc: %s:%d:%s: %" IVdf " %" UVuf
" %s = %" IVdf ": %" UVxf " -> %" UVxf "\n",
filename, linenumber, funcname, n, typesize,
type_name, n * typesize, PTR2UV(oldalloc),
PTR2UV(newalloc));
break;
case MLT_FREE:
len = my_snprintf(buf, sizeof(buf),
"free: %s:%d:%s: %" UVxf "\n",
filename, linenumber, funcname,
PTR2UV(oldalloc));
break;
case MLT_NEW_SV:
case MLT_DEL_SV:
len = my_snprintf(buf, sizeof(buf),
"%s_SV: %s:%d:%s: %" UVxf SV_LOG_SERIAL_FMT "\n",
mlt == MLT_NEW_SV ? "new" : "del",
filename, linenumber, funcname,
PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
break;
default:
len = 0;
}
PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
}
}
}
#endif /* !PERL_MEM_LOG_NOIMPL */
#ifndef PERL_MEM_LOG_NOIMPL
# define \
mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
#else
/* this is suboptimal, but bug compatible. User is providing their
own implementation, but is getting these functions anyway, and they
do nothing. But _NOIMPL users should be able to cope or fix */
# define \
mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
/* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
#endif
Malloc_t
Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
Malloc_t newalloc,
const char *filename, const int linenumber,
const char *funcname)
{
PERL_ARGS_ASSERT_MEM_LOG_ALLOC;
mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
NULL, NULL, newalloc,
filename, linenumber, funcname);
return newalloc;
}
Malloc_t
Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
Malloc_t oldalloc, Malloc_t newalloc,
const char *filename, const int linenumber,
const char *funcname)
{
PERL_ARGS_ASSERT_MEM_LOG_REALLOC;
mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
NULL, oldalloc, newalloc,
filename, linenumber, funcname);
return newalloc;
}
Malloc_t
Perl_mem_log_free(Malloc_t oldalloc,
const char *filename, const int linenumber,
const char *funcname)
{
PERL_ARGS_ASSERT_MEM_LOG_FREE;
mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
filename, linenumber, funcname);
return oldalloc;
}
void
Perl_mem_log_new_sv(const SV *sv,
const char *filename, const int linenumber,
const char *funcname)
{
mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
filename, linenumber, funcname);
}
void
Perl_mem_log_del_sv(const SV *sv,
const char *filename, const int linenumber,
const char *funcname)
{
mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
filename, linenumber, funcname);
}
#endif /* PERL_MEM_LOG */
/*
=for apidoc quadmath_format_single
C<quadmath_snprintf()> is very strict about its C<format> string and will
fail, returning -1, if the format is invalid. It accepts exactly
one format spec.
C<quadmath_format_single()> checks that the intended single spec looks
sane: begins with C<%>, has only one C<%>, ends with C<[efgaEFGA]>,
and has C<Q> before it. This is not a full "printf syntax check",
just the basics.
Returns the format if it is valid, NULL if not.
C<quadmath_format_single()> can and will actually patch in the missing
C<Q>, if necessary. In this case it will return the modified copy of
the format, B<which the caller will need to free.>
See also L</quadmath_format_needed>.
=cut
*/
#ifdef USE_QUADMATH
const char*
Perl_quadmath_format_single(const char* format)
{
STRLEN len;
PERL_ARGS_ASSERT_QUADMATH_FORMAT_SINGLE;
if (format[0] != '%' || strchr(format + 1, '%'))
return NULL;
len = strlen(format);
/* minimum length three: %Qg */
if (len < 3 || strchr("efgaEFGA", format[len - 1]) == NULL)
return NULL;
if (format[len - 2] != 'Q') {
char* fixed;
Newx(fixed, len + 1, char);
memcpy(fixed, format, len - 1);
fixed[len - 1] = 'Q';
fixed[len ] = format[len - 1];
fixed[len + 1] = 0;
return (const char*)fixed;
}
return format;
}
#endif
/*
=for apidoc quadmath_format_needed
C<quadmath_format_needed()> returns true if the C<format> string seems to
contain at least one non-Q-prefixed C<%[efgaEFGA]> format specifier,
or returns false otherwise.
The format specifier detection is not complete printf-syntax detection,
but it should catch most common cases.
If true is returned, those arguments B<should> in theory be processed
with C<quadmath_snprintf()>, but in case there is more than one such
format specifier (see L</quadmath_format_single>), and if there is
anything else beyond that one (even just a single byte), they
B<cannot> be processed because C<quadmath_snprintf()> is very strict,
accepting only one format spec, and nothing else.
In this case, the code should probably fail.
=cut
*/
#ifdef USE_QUADMATH
bool
Perl_quadmath_format_needed(const char* format)
{
const char *p = format;
const char *q;
PERL_ARGS_ASSERT_QUADMATH_FORMAT_NEEDED;
while ((q = strchr(p, '%'))) {
q++;
if (*q == '+') /* plus */
q++;
if (*q == '#') /* alt */
q++;
if (*q == '*') /* width */
q++;
else {
if (isDIGIT(*q)) {
while (isDIGIT(*q)) q++;
}
}
if (*q == '.' && (q[1] == '*' || isDIGIT(q[1]))) { /* prec */
q++;
if (*q == '*')
q++;
else
while (isDIGIT(*q)) q++;
}
if (strchr("efgaEFGA", *q)) /* Would have needed 'Q' in front. */
return TRUE;
p = q + 1;
}
return FALSE;
}
#endif
/*
=for apidoc my_snprintf
The C library C<snprintf> functionality, if available and
standards-compliant (uses C<vsnprintf>, actually). However, if the
C<vsnprintf> is not available, will unfortunately use the unsafe
C<vsprintf> which can overrun the buffer (there is an overrun check,
but that may be too late). Consider using C<sv_vcatpvf> instead, or
getting C<vsnprintf>.
=cut
*/
int
Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
{
int retval = -1;
va_list ap;
PERL_ARGS_ASSERT_MY_SNPRINTF;
#ifndef HAS_VSNPRINTF
PERL_UNUSED_VAR(len);
#endif
va_start(ap, format);
#ifdef USE_QUADMATH
{
const char* qfmt = quadmath_format_single(format);
bool quadmath_valid = FALSE;
if (qfmt) {
/* If the format looked promising, use it as quadmath. */
retval = quadmath_snprintf(buffer, len, qfmt, va_arg(ap, NV));
if (retval == -1) {
if (qfmt != format) {
dTHX;
SAVEFREEPV(qfmt);
}
Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", qfmt);
}
quadmath_valid = TRUE;
if (qfmt != format)
Safefree(qfmt);
qfmt = NULL;
}
assert(qfmt == NULL);
/* quadmath_format_single() will return false for example for
* "foo = %g", or simply "%g". We could handle the %g by
* using quadmath for the NV args. More complex cases of
* course exist: "foo = %g, bar = %g", or "foo=%Qg" (otherwise
* quadmath-valid but has stuff in front).
*
* Handling the "Q-less" cases right would require walking
* through the va_list and rewriting the format, calling
* quadmath for the NVs, building a new va_list, and then
* letting vsnprintf/vsprintf to take care of the other
* arguments. This may be doable.
*
* We do not attempt that now. But for paranoia, we here try
* to detect some common (but not all) cases where the
* "Q-less" %[efgaEFGA] formats are present, and die if
* detected. This doesn't fix the problem, but it stops the
* vsnprintf/vsprintf pulling doubles off the va_list when
* __float128 NVs should be pulled off instead.
*
* If quadmath_format_needed() returns false, we are reasonably
* certain that we can call vnsprintf() or vsprintf() safely. */
if (!quadmath_valid && quadmath_format_needed(format))
Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", format);
}
#endif
if (retval == -1)
#ifdef HAS_VSNPRINTF
retval = vsnprintf(buffer, len, format, ap);
#else
retval = vsprintf(buffer, format, ap);
#endif
va_end(ap);
/* vsprintf() shows failure with < 0 */
if (retval < 0
#ifdef HAS_VSNPRINTF
/* vsnprintf() shows failure with >= len */
||
(len > 0 && (Size_t)retval >= len)
#endif
)
Perl_croak_nocontext("panic: my_snprintf buffer overflow");
return retval;
}
/*
=for apidoc my_vsnprintf
The C library C<vsnprintf> if available and standards-compliant.
However, if if the C<vsnprintf> is not available, will unfortunately
use the unsafe C<vsprintf> which can overrun the buffer (there is an
overrun check, but that may be too late). Consider using
C<sv_vcatpvf> instead, or getting C<vsnprintf>.
=cut
*/
int
Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
{
#ifdef USE_QUADMATH
PERL_UNUSED_ARG(buffer);
PERL_UNUSED_ARG(len);
PERL_UNUSED_ARG(format);
/* the cast is to avoid gcc -Wsizeof-array-argument complaining */
PERL_UNUSED_ARG((void*)ap);
Perl_croak_nocontext("panic: my_vsnprintf not available with quadmath");
return 0;
#else
int retval;
#ifdef NEED_VA_COPY
va_list apc;
PERL_ARGS_ASSERT_MY_VSNPRINTF;
Perl_va_copy(ap, apc);
# ifdef HAS_VSNPRINTF
retval = vsnprintf(buffer, len, format, apc);
# else
PERL_UNUSED_ARG(len);
retval = vsprintf(buffer, format, apc);
# endif
va_end(apc);
#else
# ifdef HAS_VSNPRINTF
retval = vsnprintf(buffer, len, format, ap);
# else
PERL_UNUSED_ARG(len);
retval = vsprintf(buffer, format, ap);
# endif
#endif /* #ifdef NEED_VA_COPY */
/* vsprintf() shows failure with < 0 */
if (retval < 0
#ifdef HAS_VSNPRINTF
/* vsnprintf() shows failure with >= len */
||
(len > 0 && (Size_t)retval >= len)
#endif
)
Perl_croak_nocontext("panic: my_vsnprintf buffer overflow");
return retval;
#endif
}
void
Perl_my_clearenv(pTHX)
{
dVAR;
#if ! defined(PERL_MICRO)
# if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
PerlEnv_clearenv();
# else /* ! (PERL_IMPLICIT_SYS || WIN32) */
# if defined(USE_ENVIRON_ARRAY)
# if defined(USE_ITHREADS)
/* only the parent thread can clobber the process environment */
if (PL_curinterp == aTHX)
# endif /* USE_ITHREADS */
{
# if ! defined(PERL_USE_SAFE_PUTENV)
if ( !PL_use_safe_putenv) {
I32 i;
if (environ == PL_origenviron)
environ = (char**)safesysmalloc(sizeof(char*));
else
for (i = 0; environ[i]; i++)
(void)safesysfree(environ[i]);
}
environ[0] = NULL;
# else /* PERL_USE_SAFE_PUTENV */
# if defined(HAS_CLEARENV)
(void)clearenv();
# elif defined(HAS_UNSETENV)
int bsiz = 80; /* Most envvar names will be shorter than this. */
char *buf = (char*)safesysmalloc(bsiz);
while (*environ != NULL) {
char *e = strchr(*environ, '=');
int l = e ? e - *environ : (int)strlen(*environ);
if (bsiz < l + 1) {
(void)safesysfree(buf);
bsiz = l + 1; /* + 1 for the \0. */
buf = (char*)safesysmalloc(bsiz);
}
memcpy(buf, *environ, l);
buf[l] = '\0';
(void)unsetenv(buf);
}
(void)safesysfree(buf);
# else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
/* Just null environ and accept the leakage. */
*environ = NULL;
# endif /* HAS_CLEARENV || HAS_UNSETENV */
# endif /* ! PERL_USE_SAFE_PUTENV */
}
# endif /* USE_ENVIRON_ARRAY */
# endif /* PERL_IMPLICIT_SYS || WIN32 */
#endif /* PERL_MICRO */
}
#ifdef PERL_IMPLICIT_CONTEXT
/* Implements the MY_CXT_INIT macro. The first time a module is loaded,
the global PL_my_cxt_index is incremented, and that value is assigned to
that module's static my_cxt_index (who's address is passed as an arg).
Then, for each interpreter this function is called for, it makes sure a
void* slot is available to hang the static data off, by allocating or
extending the interpreter's PL_my_cxt_list array */
#ifndef PERL_GLOBAL_STRUCT_PRIVATE
void *
Perl_my_cxt_init(pTHX_ int *index, size_t size)
{
dVAR;
void *p;
PERL_ARGS_ASSERT_MY_CXT_INIT;
if (*index == -1) {
/* this module hasn't been allocated an index yet */
MUTEX_LOCK(&PL_my_ctx_mutex);
*index = PL_my_cxt_index++;
MUTEX_UNLOCK(&PL_my_ctx_mutex);
}
/* make sure the array is big enough */
if (PL_my_cxt_size <= *index) {
if (PL_my_cxt_size) {
IV new_size = PL_my_cxt_size;
while (new_size <= *index)
new_size *= 2;
Renew(PL_my_cxt_list, new_size, void *);
PL_my_cxt_size = new_size;
}
else {
PL_my_cxt_size = 16;
Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
}
}
/* newSV() allocates one more than needed */
p = (void*)SvPVX(newSV(size-1));
PL_my_cxt_list[*index] = p;
Zero(p, size, char);
return p;
}
#else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
int
Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
{
dVAR;
int index;
PERL_ARGS_ASSERT_MY_CXT_INDEX;
for (index = 0; index < PL_my_cxt_index; index++) {
const char *key = PL_my_cxt_keys[index];
/* try direct pointer compare first - there are chances to success,
* and it's much faster.
*/
if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
return index;
}
return -1;
}
void *
Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
{
dVAR;
void *p;
int index;
PERL_ARGS_ASSERT_MY_CXT_INIT;
index = Perl_my_cxt_index(aTHX_ my_cxt_key);
if (index == -1) {
/* this module hasn't been allocated an index yet */
MUTEX_LOCK(&PL_my_ctx_mutex);
index = PL_my_cxt_index++;
MUTEX_UNLOCK(&PL_my_ctx_mutex);
}
/* make sure the array is big enough */
if (PL_my_cxt_size <= index) {
int old_size = PL_my_cxt_size;
int i;
if (PL_my_cxt_size) {
IV new_size = PL_my_cxt_size;
while (new_size <= index)
new_size *= 2;
Renew(PL_my_cxt_list, new_size, void *);
Renew(PL_my_cxt_keys, new_size, const char *);
PL_my_cxt_size = new_size;
}
else {
PL_my_cxt_size = 16;
Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
}
for (i = old_size; i < PL_my_cxt_size; i++) {
PL_my_cxt_keys[i] = 0;
PL_my_cxt_list[i] = 0;
}
}
PL_my_cxt_keys[index] = my_cxt_key;
/* newSV() allocates one more than needed */
p = (void*)SvPVX(newSV(size-1));
PL_my_cxt_list[index] = p;
Zero(p, size, char);
return p;
}
#endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
#endif /* PERL_IMPLICIT_CONTEXT */
/* Perl_xs_handshake():
implement the various XS_*_BOOTCHECK macros, which are added to .c
files by ExtUtils::ParseXS, to check that the perl the module was built
with is binary compatible with the running perl.
usage:
Perl_xs_handshake(U32 key, void * v_my_perl, const char * file,
[U32 items, U32 ax], [char * api_version], [char * xs_version])
The meaning of the varargs is determined the U32 key arg (which is not
a format string). The fields of key are assembled by using HS_KEY().
Under PERL_IMPLICIT_CONTEX, the v_my_perl arg is of type
"PerlInterpreter *" and represents the callers context; otherwise it is
of type "CV *", and is the boot xsub's CV.
v_my_perl will catch where a threaded future perl526.dll calling IO.dll
for example, and IO.dll was linked with threaded perl524.dll, and both
perl526.dll and perl524.dll are in %PATH and the Win32 DLL loader
successfully can load IO.dll into the process but simultaneously it
loaded an interpreter of a different version into the process, and XS
code will naturally pass SV*s created by perl524.dll for perl526.dll to
use through perl526.dll's my_perl->Istack_base.
v_my_perl cannot be the first arg, since then 'key' will be out of
place in a threaded vs non-threaded mixup; and analyzing the key
number's bitfields won't reveal the problem, since it will be a valid
key (unthreaded perl) on interp side, but croak will report the XS mod's
key as gibberish (it is really a my_perl ptr) (threaded XS mod); or if
it's a threaded perl and an unthreaded XS module, threaded perl will
look at an uninit C stack or an uninit register to get 'key'
(remember that it assumes that the 1st arg is the interp cxt).
'file' is the source filename of the caller.
*/
I32
Perl_xs_handshake(const U32 key, void * v_my_perl, const char * file, ...)
{
va_list args;
U32 items, ax;
void * got;
void * need;
#ifdef PERL_IMPLICIT_CONTEXT
dTHX;
tTHX xs_interp;
#else
CV* cv;
SV *** xs_spp;
#endif
PERL_ARGS_ASSERT_XS_HANDSHAKE;
va_start(args, file);
got = INT2PTR(void*, (UV)(key & HSm_KEY_MATCH));
need = (void *)(HS_KEY(FALSE, FALSE, "", "") & HSm_KEY_MATCH);
if (UNLIKELY(got != need))
goto bad_handshake;
/* try to catch where a 2nd threaded perl interp DLL is loaded into a process
by a XS DLL compiled against the wrong interl DLL b/c of bad @INC, and the
2nd threaded perl interp DLL never initialized its TLS/PERL_SYS_INIT3 so
dTHX call from 2nd interp DLL can't return the my_perl that pp_entersub
passed to the XS DLL */
#ifdef PERL_IMPLICIT_CONTEXT
xs_interp = (tTHX)v_my_perl;
got = xs_interp;
need = my_perl;
#else
/* try to catch where an unthreaded perl interp DLL (for ex. perl522.dll) is
loaded into a process by a XS DLL built by an unthreaded perl522.dll perl,
but the DynaLoder/Perl that started the process and loaded the XS DLL is
unthreaded perl524.dll, since unthreadeds don't pass my_perl (a unique *)
through pp_entersub, use a unique value (which is a pointer to PL_stack_sp's
location in the unthreaded perl binary) stored in CV * to figure out if this
Perl_xs_handshake was called by the same pp_entersub */
cv = (CV*)v_my_perl;
xs_spp = (SV***)CvHSCXT(cv);
got = xs_spp;
need = &PL_stack_sp;
#endif
if(UNLIKELY(got != need)) {
bad_handshake:/* recycle branch and string from above */
if(got != (void *)HSf_NOCHK)
noperl_die("%s: loadable library and perl binaries are mismatched"
" (got handshake key %p, needed %p)\n",
file, got, need);
}
if(key & HSf_SETXSUBFN) { /* this might be called from a module bootstrap */
SAVEPPTR(PL_xsubfilename);/* which was require'd from a XSUB BEGIN */
PL_xsubfilename = file; /* so the old name must be restored for
additional XSUBs to register themselves */
/* XSUBs can't be perl lang/perl5db.pl debugged
if (PERLDB_LINE_OR_SAVESRC)
(void)gv_fetchfile(file); */
}
if(key & HSf_POPMARK) {
ax = POPMARK;
{ SV **mark = PL_stack_base + ax++;
{ dSP;
items = (I32)(SP - MARK);
}
}
} else {
items = va_arg(args, U32);
ax = va_arg(args, U32);
}
{
U32 apiverlen;
assert(HS_GETAPIVERLEN(key) <= UCHAR_MAX);
if((apiverlen = HS_GETAPIVERLEN(key))) {
char * api_p = va_arg(args, char*);
if(apiverlen != sizeof("v" PERL_API_VERSION_STRING)-1
|| memNE(api_p, "v" PERL_API_VERSION_STRING,
sizeof("v" PERL_API_VERSION_STRING)-1))
Perl_croak_nocontext("Perl API version %s of %" SVf " does not match %s",
api_p, SVfARG(PL_stack_base[ax + 0]),
"v" PERL_API_VERSION_STRING);
}
}
{
U32 xsverlen;
assert(HS_GETXSVERLEN(key) <= UCHAR_MAX && HS_GETXSVERLEN(key) <= HS_APIVERLEN_MAX);
if((xsverlen = HS_GETXSVERLEN(key)))
S_xs_version_bootcheck(aTHX_
items, ax, va_arg(args, char*), xsverlen);
}
va_end(args);
return ax;
}
STATIC void
S_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
STRLEN xs_len)
{
SV *sv;
const char *vn = NULL;
SV *const module = PL_stack_base[ax];
PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
if (items >= 2) /* version supplied as bootstrap arg */
sv = PL_stack_base[ax + 1];
else {
/* XXX GV_ADDWARN */
vn = "XS_VERSION";
sv = get_sv(Perl_form(aTHX_ "%" SVf "::%s", SVfARG(module), vn), 0);
if (!sv || !SvOK(sv)) {
vn = "VERSION";
sv = get_sv(Perl_form(aTHX_ "%" SVf "::%s", SVfARG(module), vn), 0);
}
}
if (sv) {
SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
SV *pmsv = sv_isobject(sv) && sv_derived_from(sv, "version")
? sv : sv_2mortal(new_version(sv));
xssv = upg_version(xssv, 0);
if ( vcmp(pmsv,xssv) ) {
SV *string = vstringify(xssv);
SV *xpt = Perl_newSVpvf(aTHX_ "%" SVf " object version %" SVf
" does not match ", SVfARG(module), SVfARG(string));
SvREFCNT_dec(string);
string = vstringify(pmsv);
if (vn) {
Perl_sv_catpvf(aTHX_ xpt, "$%" SVf "::%s %" SVf, SVfARG(module), vn,
SVfARG(string));
} else {
Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %" SVf, SVfARG(string));
}
SvREFCNT_dec(string);
Perl_sv_2mortal(aTHX_ xpt);
Perl_croak_sv(aTHX_ xpt);
}
}
}
/*
=for apidoc my_strlcat
The C library C<strlcat> if available, or a Perl implementation of it.
This operates on C C<NUL>-terminated strings.
C<my_strlcat()> appends string C<src> to the end of C<dst>. It will append at
most S<C<size - strlen(dst) - 1>> characters. It will then C<NUL>-terminate,
unless C<size> is 0 or the original C<dst> string was longer than C<size> (in
practice this should not happen as it means that either C<size> is incorrect or
that C<dst> is not a proper C<NUL>-terminated string).
Note that C<size> is the full size of the destination buffer and
the result is guaranteed to be C<NUL>-terminated if there is room. Note that
room for the C<NUL> should be included in C<size>.
The return value is the total length that C<dst> would have if C<size> is
sufficiently large. Thus it is the initial length of C<dst> plus the length of
C<src>. If C<size> is smaller than the return, the excess was not appended.
=cut
Description stolen from http://man.openbsd.org/strlcat.3
*/
#ifndef HAS_STRLCAT
Size_t
Perl_my_strlcat(char *dst, const char *src, Size_t size)
{
Size_t used, length, copy;
used = strlen(dst);
length = strlen(src);
if (size > 0 && used < size - 1) {
copy = (length >= size - used) ? size - used - 1 : length;
memcpy(dst + used, src, copy);
dst[used + copy] = '\0';
}
return used + length;
}
#endif
/*
=for apidoc my_strlcpy
The C library C<strlcpy> if available, or a Perl implementation of it.
This operates on C C<NUL>-terminated strings.
C<my_strlcpy()> copies up to S<C<size - 1>> characters from the string C<src>
to C<dst>, C<NUL>-terminating the result if C<size> is not 0.
The return value is the total length C<src> would be if the copy completely
succeeded. If it is larger than C<size>, the excess was not copied.
=cut
Description stolen from http://man.openbsd.org/strlcpy.3
*/
#ifndef HAS_STRLCPY
Size_t
Perl_my_strlcpy(char *dst, const char *src, Size_t size)
{
Size_t length, copy;
length = strlen(src);
if (size > 0) {
copy = (length >= size) ? size - 1 : length;
memcpy(dst, src, copy);
dst[copy] = '\0';
}
return length;
}
#endif
/*
=for apidoc my_strnlen
The C library C<strnlen> if available, or a Perl implementation of it.
C<my_strnlen()> computes the length of the string, up to C<maxlen>
characters. It will will never attempt to address more than C<maxlen>
characters, making it suitable for use with strings that are not
guaranteed to be NUL-terminated.
=cut
Description stolen from http://man.openbsd.org/strnlen.3,
implementation stolen from PostgreSQL.
*/
#ifndef HAS_STRNLEN
Size_t
Perl_my_strnlen(const char *str, Size_t maxlen)
{
const char *p = str;
PERL_ARGS_ASSERT_MY_STRNLEN;
while(maxlen-- && *p)
p++;
return p - str;
}
#endif
#if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
/* VC7 or 7.1, building with pre-VC7 runtime libraries. */
long _ftol( double ); /* Defined by VC6 C libs. */
long _ftol2( double dblSource ) { return _ftol( dblSource ); }
#endif
PERL_STATIC_INLINE bool
S_gv_has_usable_name(pTHX_ GV *gv)
{
GV **gvp;
return GvSTASH(gv)
&& HvENAME(GvSTASH(gv))
&& (gvp = (GV **)hv_fetchhek(
GvSTASH(gv), GvNAME_HEK(gv), 0
))
&& *gvp == gv;
}
void
Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
{
SV * const dbsv = GvSVn(PL_DBsub);
const bool save_taint = TAINT_get;
/* When we are called from pp_goto (svp is null),
* we do not care about using dbsv to call CV;
* it's for informational purposes only.
*/
PERL_ARGS_ASSERT_GET_DB_SUB;
TAINT_set(FALSE);
save_item(dbsv);
if (!PERLDB_SUB_NN) {
GV *gv = CvGV(cv);
if (!svp && !CvLEXICAL(cv)) {
gv_efullname3(dbsv, gv, NULL);
}
else if ( (CvFLAGS(cv) & (CVf_ANON | CVf_CLONED)) || CvLEXICAL(cv)
|| strEQ(GvNAME(gv), "END")
|| ( /* Could be imported, and old sub redefined. */
(GvCV(gv) != cv || !S_gv_has_usable_name(aTHX_ gv))
&&
!( (SvTYPE(*svp) == SVt_PVGV)
&& (GvCV((const GV *)*svp) == cv)
/* Use GV from the stack as a fallback. */
&& S_gv_has_usable_name(aTHX_ gv = (GV *)*svp)
)
)
) {
/* GV is potentially non-unique, or contain different CV. */
SV * const tmp = newRV(MUTABLE_SV(cv));
sv_setsv(dbsv, tmp);
SvREFCNT_dec(tmp);
}
else {
sv_sethek(dbsv, HvENAME_HEK(GvSTASH(gv)));
sv_catpvs(dbsv, "::");
sv_cathek(dbsv, GvNAME_HEK(gv));
}
}
else {
const int type = SvTYPE(dbsv);
if (type < SVt_PVIV && type != SVt_IV)
sv_upgrade(dbsv, SVt_PVIV);
(void)SvIOK_on(dbsv);
SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
}
SvSETMAGIC(dbsv);
TAINT_IF(save_taint);
#ifdef NO_TAINT_SUPPORT
PERL_UNUSED_VAR(save_taint);
#endif
}
int
Perl_my_dirfd(DIR * dir) {
/* Most dirfd implementations have problems when passed NULL. */
if(!dir)
return -1;
#ifdef HAS_DIRFD
return dirfd(dir);
#elif defined(HAS_DIR_DD_FD)
return dir->dd_fd;
#else
Perl_croak_nocontext(PL_no_func, "dirfd");
NOT_REACHED; /* NOTREACHED */
return 0;
#endif
}
#if !defined(HAS_MKOSTEMP) || !defined(HAS_MKSTEMP)
#define TEMP_FILE_CH "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789"
#define TEMP_FILE_CH_COUNT (sizeof(TEMP_FILE_CH)-1)
static int
S_my_mkostemp(char *templte, int flags) {
dTHX;
STRLEN len = strlen(templte);
int fd;
int attempts = 0;
if (len < 6 ||
templte[len-1] != 'X' || templte[len-2] != 'X' || templte[len-3] != 'X' ||
templte[len-4] != 'X' || templte[len-5] != 'X' || templte[len-6] != 'X') {
SETERRNO(EINVAL, LIB_INVARG);
return -1;
}
do {
int i;
for (i = 1; i <= 6; ++i) {
templte[len-i] = TEMP_FILE_CH[(int)(Perl_internal_drand48() * TEMP_FILE_CH_COUNT)];
}
fd = PerlLIO_open3(templte, O_RDWR | O_CREAT | O_EXCL | flags, 0600);
} while (fd == -1 && errno == EEXIST && ++attempts <= 100);
return fd;
}
#endif
#ifndef HAS_MKOSTEMP
int
Perl_my_mkostemp(char *templte, int flags)
{
PERL_ARGS_ASSERT_MY_MKOSTEMP;
return S_my_mkostemp(templte, flags);
}
#endif
#ifndef HAS_MKSTEMP
int
Perl_my_mkstemp(char *templte)
{
PERL_ARGS_ASSERT_MY_MKSTEMP;
return S_my_mkostemp(templte, 0);
}
#endif
REGEXP *
Perl_get_re_arg(pTHX_ SV *sv) {
if (sv) {
if (SvMAGICAL(sv))
mg_get(sv);
if (SvROK(sv))
sv = MUTABLE_SV(SvRV(sv));
if (SvTYPE(sv) == SVt_REGEXP)
return (REGEXP*) sv;
}
return NULL;
}
/*
* This code is derived from drand48() implementation from FreeBSD,
* found in lib/libc/gen/_rand48.c.
*
* The U64 implementation is original, based on the POSIX
* specification for drand48().
*/
/*
* Copyright (c) 1993 Martin Birgmeier
* All rights reserved.
*
* You may redistribute unmodified or modified versions of this source
* code provided that the above copyright notice and this and the
* following conditions are retained.
*
* This software is provided ``as is'', and comes with no warranties
* of any kind. I shall in no event be liable for anything that happens
* to anyone/anything when using this software.
*/
#define FREEBSD_DRAND48_SEED_0 (0x330e)
#ifdef PERL_DRAND48_QUAD
#define DRAND48_MULT UINT64_C(0x5deece66d)
#define DRAND48_ADD 0xb
#define DRAND48_MASK UINT64_C(0xffffffffffff)
#else
#define FREEBSD_DRAND48_SEED_1 (0xabcd)
#define FREEBSD_DRAND48_SEED_2 (0x1234)
#define FREEBSD_DRAND48_MULT_0 (0xe66d)
#define FREEBSD_DRAND48_MULT_1 (0xdeec)
#define FREEBSD_DRAND48_MULT_2 (0x0005)
#define FREEBSD_DRAND48_ADD (0x000b)
const unsigned short _rand48_mult[3] = {
FREEBSD_DRAND48_MULT_0,
FREEBSD_DRAND48_MULT_1,
FREEBSD_DRAND48_MULT_2
};
const unsigned short _rand48_add = FREEBSD_DRAND48_ADD;
#endif
void
Perl_drand48_init_r(perl_drand48_t *random_state, U32 seed)
{
PERL_ARGS_ASSERT_DRAND48_INIT_R;
#ifdef PERL_DRAND48_QUAD
*random_state = FREEBSD_DRAND48_SEED_0 + ((U64)seed << 16);
#else
random_state->seed[0] = FREEBSD_DRAND48_SEED_0;
random_state->seed[1] = (U16) seed;
random_state->seed[2] = (U16) (seed >> 16);
#endif
}
double
Perl_drand48_r(perl_drand48_t *random_state)
{
PERL_ARGS_ASSERT_DRAND48_R;
#ifdef PERL_DRAND48_QUAD
*random_state = (*random_state * DRAND48_MULT + DRAND48_ADD)
& DRAND48_MASK;
return ldexp((double)*random_state, -48);
#else
{
U32 accu;
U16 temp[2];
accu = (U32) _rand48_mult[0] * (U32) random_state->seed[0]
+ (U32) _rand48_add;
temp[0] = (U16) accu; /* lower 16 bits */
accu >>= sizeof(U16) * 8;
accu += (U32) _rand48_mult[0] * (U32) random_state->seed[1]
+ (U32) _rand48_mult[1] * (U32) random_state->seed[0];
temp[1] = (U16) accu; /* middle 16 bits */
accu >>= sizeof(U16) * 8;
accu += _rand48_mult[0] * random_state->seed[2]
+ _rand48_mult[1] * random_state->seed[1]
+ _rand48_mult[2] * random_state->seed[0];
random_state->seed[0] = temp[0];
random_state->seed[1] = temp[1];
random_state->seed[2] = (U16) accu;
return ldexp((double) random_state->seed[0], -48) +
ldexp((double) random_state->seed[1], -32) +
ldexp((double) random_state->seed[2], -16);
}
#endif
}
#ifdef USE_C_BACKTRACE
/* Possibly move all this USE_C_BACKTRACE code into a new file. */
#ifdef USE_BFD
typedef struct {
/* abfd is the BFD handle. */
bfd* abfd;
/* bfd_syms is the BFD symbol table. */
asymbol** bfd_syms;
/* bfd_text is handle to the the ".text" section of the object file. */
asection* bfd_text;
/* Since opening the executable and scanning its symbols is quite
* heavy operation, we remember the filename we used the last time,
* and do the opening and scanning only if the filename changes.
* This removes most (but not all) open+scan cycles. */
const char* fname_prev;
} bfd_context;
/* Given a dl_info, update the BFD context if necessary. */
static void bfd_update(bfd_context* ctx, Dl_info* dl_info)
{
/* BFD open and scan only if the filename changed. */
if (ctx->fname_prev == NULL ||
strNE(dl_info->dli_fname, ctx->fname_prev)) {
if (ctx->abfd) {
bfd_close(ctx->abfd);
}
ctx->abfd = bfd_openr(dl_info->dli_fname, 0);
if (ctx->abfd) {
if (bfd_check_format(ctx->abfd, bfd_object)) {
IV symbol_size = bfd_get_symtab_upper_bound(ctx->abfd);
if (symbol_size > 0) {
Safefree(ctx->bfd_syms);
Newx(ctx->bfd_syms, symbol_size, asymbol*);
ctx->bfd_text =
bfd_get_section_by_name(ctx->abfd, ".text");
}
else
ctx->abfd = NULL;
}
else
ctx->abfd = NULL;
}
ctx->fname_prev = dl_info->dli_fname;
}
}
/* Given a raw frame, try to symbolize it and store
* symbol information (source file, line number) away. */
static void bfd_symbolize(bfd_context* ctx,
void* raw_frame,
char** symbol_name,
STRLEN* symbol_name_size,
char** source_name,
STRLEN* source_name_size,
STRLEN* source_line)
{
*symbol_name = NULL;
*symbol_name_size = 0;
if (ctx->abfd) {
IV offset = PTR2IV(raw_frame) - PTR2IV(ctx->bfd_text->vma);
if (offset > 0 &&
bfd_canonicalize_symtab(ctx->abfd, ctx->bfd_syms) > 0) {
const char *file;
const char *func;
unsigned int line = 0;
if (bfd_find_nearest_line(ctx->abfd, ctx->bfd_text,
ctx->bfd_syms, offset,
&file, &func, &line) &&
file && func && line > 0) {
/* Size and copy the source file, use only
* the basename of the source file.
*
* NOTE: the basenames are fine for the
* Perl source files, but may not always
* be the best idea for XS files. */
const char *p, *b = NULL;
/* Look for the last slash. */
for (p = file; *p; p++) {
if (*p == '/')
b = p + 1;
}
if (b == NULL || *b == 0) {
b = file;
}
*source_name_size = p - b + 1;
Newx(*source_name, *source_name_size + 1, char);
Copy(b, *source_name, *source_name_size + 1, char);
*symbol_name_size = strlen(func);
Newx(*symbol_name, *symbol_name_size + 1, char);
Copy(func, *symbol_name, *symbol_name_size + 1, char);
*source_line = line;
}
}
}
}
#endif /* #ifdef USE_BFD */
#ifdef PERL_DARWIN
/* OS X has no public API for for 'symbolicating' (Apple official term)
* stack addresses to {function_name, source_file, line_number}.
* Good news: there is command line utility atos(1) which does that.
* Bad news 1: it's a command line utility.
* Bad news 2: one needs to have the Developer Tools installed.
* Bad news 3: in newer releases it needs to be run as 'xcrun atos'.
*
* To recap: we need to open a pipe for reading for a utility which
* might not exist, or exists in different locations, and then parse
* the output. And since this is all for a low-level API, we cannot
* use high-level stuff. Thanks, Apple. */
typedef struct {
/* tool is set to the absolute pathname of the tool to use:
* xcrun or atos. */
const char* tool;
/* format is set to a printf format string used for building
* the external command to run. */
const char* format;
/* unavail is set if e.g. xcrun cannot be found, or something
* else happens that makes getting the backtrace dubious. Note,
* however, that the context isn't persistent, the next call to
* get_c_backtrace() will start from scratch. */
bool unavail;
/* fname is the current object file name. */
const char* fname;
/* object_base_addr is the base address of the shared object. */
void* object_base_addr;
} atos_context;
/* Given |dl_info|, updates the context. If the context has been
* marked unavailable, return immediately. If not but the tool has
* not been set, set it to either "xcrun atos" or "atos" (also set the
* format to use for creating commands for piping), or if neither is
* unavailable (one needs the Developer Tools installed), mark the context
* an unavailable. Finally, update the filename (object name),
* and its base address. */
static void atos_update(atos_context* ctx,
Dl_info* dl_info)
{
if (ctx->unavail)
return;
if (ctx->tool == NULL) {
const char* tools[] = {
"/usr/bin/xcrun",
"/usr/bin/atos"
};
const char* formats[] = {
"/usr/bin/xcrun atos -o '%s' -l %08x %08x 2>&1",
"/usr/bin/atos -d -o '%s' -l %08x %08x 2>&1"
};
struct stat st;
UV i;
for (i = 0; i < C_ARRAY_LENGTH(tools); i++) {
if (stat(tools[i], &st) == 0 && S_ISREG(st.st_mode)) {
ctx->tool = tools[i];
ctx->format = formats[i];
break;
}
}
if (ctx->tool == NULL) {
ctx->unavail = TRUE;
return;
}
}
if (ctx->fname == NULL ||
strNE(dl_info->dli_fname, ctx->fname)) {
ctx->fname = dl_info->dli_fname;
ctx->object_base_addr = dl_info->dli_fbase;
}
}
/* Given an output buffer end |p| and its |start|, matches
* for the atos output, extracting the source code location
* and returning non-NULL if possible, returning NULL otherwise. */
static const char* atos_parse(const char* p,
const char* start,
STRLEN* source_name_size,
STRLEN* source_line) {
/* atos() output is something like:
* perl_parse (in miniperl) (perl.c:2314)\n\n".
* We cannot use Perl regular expressions, because we need to
* stay low-level. Therefore here we have a rolled-out version
* of a state machine which matches _backwards_from_the_end_ and
* if there's a success, returns the starts of the filename,
* also setting the filename size and the source line number.
* The matched regular expression is roughly "\(.*:\d+\)\s*$" */
const char* source_number_start;
const char* source_name_end;
const char* source_line_end = start;
const char* close_paren;
UV uv;
/* Skip trailing whitespace. */
while (p > start && isSPACE(*p)) p--;
/* Now we should be at the close paren. */
if (p == start || *p != ')')
return NULL;
close_paren = p;
p--;
/* Now we should be in the line number. */
if (p == start || !isDIGIT(*p))
return NULL;
/* Skip over the digits. */
while (p > start && isDIGIT(*p))
p--;
/* Now we should be at the colon. */
if (p == start || *p != ':')
return NULL;
source_number_start = p + 1;
source_name_end = p; /* Just beyond the end. */
p--;
/* Look for the open paren. */
while (p > start && *p != '(')
p--;
if (p == start)
return NULL;
p++;
*source_name_size = source_name_end - p;
if (grok_atoUV(source_number_start, &uv, &source_line_end)
&& source_line_end == close_paren
&& uv <= PERL_INT_MAX
) {
*source_line = (STRLEN)uv;
return p;
}
return NULL;
}
/* Given a raw frame, read a pipe from the symbolicator (that's the
* technical term) atos, reads the result, and parses the source code
* location. We must stay low-level, so we use snprintf(), pipe(),
* and fread(), and then also parse the output ourselves. */
static void atos_symbolize(atos_context* ctx,
void* raw_frame,
char** source_name,
STRLEN* source_name_size,
STRLEN* source_line)
{
char cmd[1024];
const char* p;
Size_t cnt;
if (ctx->unavail)
return;
/* Simple security measure: if there's any funny business with
* the object name (used as "-o '%s'" ), leave since at least
* partially the user controls it. */
for (p = ctx->fname; *p; p++) {
if (*p == '\'' || isCNTRL(*p)) {
ctx->unavail = TRUE;
return;
}
}
cnt = snprintf(cmd, sizeof(cmd), ctx->format,
ctx->fname, ctx->object_base_addr, raw_frame);
if (cnt < sizeof(cmd)) {
/* Undo nostdio.h #defines that disable stdio.
* This is somewhat naughty, but is used elsewhere
* in the core, and affects only OS X. */
#undef FILE
#undef popen
#undef fread
#undef pclose
FILE* fp = popen(cmd, "r");
/* At the moment we open a new pipe for each stack frame.
* This is naturally somewhat slow, but hopefully generating
* stack traces is never going to in a performance critical path.
*
* We could play tricks with atos by batching the stack
* addresses to be resolved: atos can either take multiple
* addresses from the command line, or read addresses from
* a file (though the mess of creating temporary files would
* probably negate much of any possible speedup).
*
* Normally there are only two objects present in the backtrace:
* perl itself, and the libdyld.dylib. (Note that the object
* filenames contain the full pathname, so perl may not always
* be in the same place.) Whenever the object in the
* backtrace changes, the base address also changes.
*
* The problem with batching the addresses, though, would be
* matching the results with the addresses: the parsing of
* the results is already painful enough with a single address. */
if (fp) {
char out[1024];
UV cnt = fread(out, 1, sizeof(out), fp);
if (cnt < sizeof(out)) {
const char* p = atos_parse(out + cnt - 1, out,
source_name_size,
source_line);
if (p) {
Newx(*source_name,
*source_name_size, char);
Copy(p, *source_name,
*source_name_size, char);
}
}
pclose(fp);
}
}
}
#endif /* #ifdef PERL_DARWIN */
/*
=for apidoc get_c_backtrace
Collects the backtrace (aka "stacktrace") into a single linear
malloced buffer, which the caller B<must> C<Perl_free_c_backtrace()>.
Scans the frames back by S<C<depth + skip>>, then drops the C<skip> innermost,
returning at most C<depth> frames.
=cut
*/
Perl_c_backtrace*
Perl_get_c_backtrace(pTHX_ int depth, int skip)
{
/* Note that here we must stay as low-level as possible: Newx(),
* Copy(), Safefree(); since we may be called from anywhere,
* so we should avoid higher level constructs like SVs or AVs.
*
* Since we are using safesysmalloc() via Newx(), don't try
* getting backtrace() there, unless you like deep recursion. */
/* Currently only implemented with backtrace() and dladdr(),
* for other platforms NULL is returned. */
#if defined(HAS_BACKTRACE) && defined(HAS_DLADDR)
/* backtrace() is available via <execinfo.h> in glibc and in most
* modern BSDs; dladdr() is available via <dlfcn.h>. */
/* We try fetching this many frames total, but then discard
* the |skip| first ones. For the remaining ones we will try
* retrieving more information with dladdr(). */
int try_depth = skip + depth;
/* The addresses (program counters) returned by backtrace(). */
void** raw_frames;
/* Retrieved with dladdr() from the addresses returned by backtrace(). */
Dl_info* dl_infos;
/* Sizes _including_ the terminating \0 of the object name
* and symbol name strings. */
STRLEN* object_name_sizes;
STRLEN* symbol_name_sizes;
#ifdef USE_BFD
/* The symbol names comes either from dli_sname,
* or if using BFD, they can come from BFD. */
char** symbol_names;
#endif
/* The source code location information. Dug out with e.g. BFD. */
char** source_names;
STRLEN* source_name_sizes;
STRLEN* source_lines;
Perl_c_backtrace* bt = NULL; /* This is what will be returned. */
int got_depth; /* How many frames were returned from backtrace(). */
UV frame_count = 0; /* How many frames we return. */
UV total_bytes = 0; /* The size of the whole returned backtrace. */
#ifdef USE_BFD
bfd_context bfd_ctx;
#endif
#ifdef PERL_DARWIN
atos_context atos_ctx;
#endif
/* Here are probably possibilities for optimizing. We could for
* example have a struct that contains most of these and then
* allocate |try_depth| of them, saving a bunch of malloc calls.
* Note, however, that |frames| could not be part of that struct
* because backtrace() will want an array of just them. Also be
* careful about the name strings. */
Newx(raw_frames, try_depth, void*);
Newx(dl_infos, try_depth, Dl_info);
Newx(object_name_sizes, try_depth, STRLEN);
Newx(symbol_name_sizes, try_depth, STRLEN);
Newx(source_names, try_depth, char*);
Newx(source_name_sizes, try_depth, STRLEN);
Newx(source_lines, try_depth, STRLEN);
#ifdef USE_BFD
Newx(symbol_names, try_depth, char*);
#endif
/* Get the raw frames. */
got_depth = (int)backtrace(raw_frames, try_depth);
/* We use dladdr() instead of backtrace_symbols() because we want
* the full details instead of opaque strings. This is useful for
* two reasons: () the details are needed for further symbolic
* digging, for example in OS X (2) by having the details we fully
* control the output, which in turn is useful when more platforms
* are added: we can keep out output "portable". */
/* We want a single linear allocation, which can then be freed
* with a single swoop. We will do the usual trick of first
* walking over the structure and seeing how much we need to
* allocate, then allocating, and then walking over the structure
* the second time and populating it. */
/* First we must compute the total size of the buffer. */
total_bytes = sizeof(Perl_c_backtrace_header);
if (got_depth > skip) {
int i;
#ifdef USE_BFD
bfd_init(); /* Is this safe to call multiple times? */
Zero(&bfd_ctx, 1, bfd_context);
#endif
#ifdef PERL_DARWIN
Zero(&atos_ctx, 1, atos_context);
#endif
for (i = skip; i < try_depth; i++) {
Dl_info* dl_info = &dl_infos[i];
object_name_sizes[i] = 0;
source_names[i] = NULL;
source_name_sizes[i] = 0;
source_lines[i] = 0;
/* Yes, zero from dladdr() is failure. */
if (dladdr(raw_frames[i], dl_info)) {
total_bytes += sizeof(Perl_c_backtrace_frame);
object_name_sizes[i] =
dl_info->dli_fname ? strlen(dl_info->dli_fname) : 0;
symbol_name_sizes[i] =
dl_info->dli_sname ? strlen(dl_info->dli_sname) : 0;
#ifdef USE_BFD
bfd_update(&bfd_ctx, dl_info);
bfd_symbolize(&bfd_ctx, raw_frames[i],
&symbol_names[i],
&symbol_name_sizes[i],
&source_names[i],
&source_name_sizes[i],
&source_lines[i]);
#endif
#if PERL_DARWIN
atos_update(&atos_ctx, dl_info);
atos_symbolize(&atos_ctx,
raw_frames[i],
&source_names[i],
&source_name_sizes[i],
&source_lines[i]);
#endif
/* Plus ones for the terminating \0. */
total_bytes += object_name_sizes[i] + 1;
total_bytes += symbol_name_sizes[i] + 1;
total_bytes += source_name_sizes[i] + 1;
frame_count++;
} else {
break;
}
}
#ifdef USE_BFD
Safefree(bfd_ctx.bfd_syms);
#endif
}
/* Now we can allocate and populate the result buffer. */
Newxc(bt, total_bytes, char, Perl_c_backtrace);
Zero(bt, total_bytes, char);
bt->header.frame_count = frame_count;
bt->header.total_bytes = total_bytes;
if (frame_count > 0) {
Perl_c_backtrace_frame* frame = bt->frame_info;
char* name_base = (char *)(frame + frame_count);
char* name_curr = name_base; /* Outputting the name strings here. */
UV i;
for (i = skip; i < skip + frame_count; i++) {
Dl_info* dl_info = &dl_infos[i];
frame->addr = raw_frames[i];
frame->object_base_addr = dl_info->dli_fbase;
frame->symbol_addr = dl_info->dli_saddr;
/* Copies a string, including the \0, and advances the name_curr.
* Also copies the start and the size to the frame. */
#define PERL_C_BACKTRACE_STRCPY(frame, doffset, src, dsize, size) \
if (size && src) \
Copy(src, name_curr, size, char); \
frame->doffset = name_curr - (char*)bt; \
frame->dsize = size; \
name_curr += size; \
*name_curr++ = 0;
PERL_C_BACKTRACE_STRCPY(frame, object_name_offset,
dl_info->dli_fname,
object_name_size, object_name_sizes[i]);
#ifdef USE_BFD
PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset,
symbol_names[i],
symbol_name_size, symbol_name_sizes[i]);
Safefree(symbol_names[i]);
#else
PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset,
dl_info->dli_sname,
symbol_name_size, symbol_name_sizes[i]);
#endif
PERL_C_BACKTRACE_STRCPY(frame, source_name_offset,
source_names[i],
source_name_size, source_name_sizes[i]);
Safefree(source_names[i]);
#undef PERL_C_BACKTRACE_STRCPY
frame->source_line_number = source_lines[i];
frame++;
}
assert(total_bytes ==
(UV)(sizeof(Perl_c_backtrace_header) +
frame_count * sizeof(Perl_c_backtrace_frame) +
name_curr - name_base));
}
#ifdef USE_BFD
Safefree(symbol_names);
if (bfd_ctx.abfd) {
bfd_close(bfd_ctx.abfd);
}
#endif
Safefree(source_lines);
Safefree(source_name_sizes);
Safefree(source_names);
Safefree(symbol_name_sizes);
Safefree(object_name_sizes);
/* Assuming the strings returned by dladdr() are pointers
* to read-only static memory (the object file), so that
* they do not need freeing (and cannot be). */
Safefree(dl_infos);
Safefree(raw_frames);
return bt;
#else
PERL_UNUSED_ARGV(depth);
PERL_UNUSED_ARGV(skip);
return NULL;
#endif
}
/*
=for apidoc free_c_backtrace
Deallocates a backtrace received from get_c_bracktrace.
=cut
*/
/*
=for apidoc get_c_backtrace_dump
Returns a SV containing a dump of C<depth> frames of the call stack, skipping
the C<skip> innermost ones. C<depth> of 20 is usually enough.
The appended output looks like:
...
1 10e004812:0082 Perl_croak util.c:1716 /usr/bin/perl
2 10df8d6d2:1d72 perl_parse perl.c:3975 /usr/bin/perl
...
The fields are tab-separated. The first column is the depth (zero
being the innermost non-skipped frame). In the hex:offset, the hex is
where the program counter was in C<S_parse_body>, and the :offset (might
be missing) tells how much inside the C<S_parse_body> the program counter was.
The C<util.c:1716> is the source code file and line number.
The F</usr/bin/perl> is obvious (hopefully).
Unknowns are C<"-">. Unknowns can happen unfortunately quite easily:
if the platform doesn't support retrieving the information;
if the binary is missing the debug information;
if the optimizer has transformed the code by for example inlining.
=cut
*/
SV*
Perl_get_c_backtrace_dump(pTHX_ int depth, int skip)
{
Perl_c_backtrace* bt;
bt = get_c_backtrace(depth, skip + 1 /* Hide ourselves. */);
if (bt) {
Perl_c_backtrace_frame* frame;
SV* dsv = newSVpvs("");
UV i;
for (i = 0, frame = bt->frame_info;
i < bt->header.frame_count; i++, frame++) {
Perl_sv_catpvf(aTHX_ dsv, "%d", (int)i);
Perl_sv_catpvf(aTHX_ dsv, "\t%p", frame->addr ? frame->addr : "-");
/* Symbol (function) names might disappear without debug info.
*
* The source code location might disappear in case of the
* optimizer inlining or otherwise rearranging the code. */
if (frame->symbol_addr) {
Perl_sv_catpvf(aTHX_ dsv, ":%04x",
(int)
((char*)frame->addr - (char*)frame->symbol_addr));
}
Perl_sv_catpvf(aTHX_ dsv, "\t%s",
frame->symbol_name_size &&
frame->symbol_name_offset ?
(char*)bt + frame->symbol_name_offset : "-");
if (frame->source_name_size &&
frame->source_name_offset &&
frame->source_line_number) {
Perl_sv_catpvf(aTHX_ dsv, "\t%s:%" UVuf,
(char*)bt + frame->source_name_offset,
(UV)frame->source_line_number);
} else {
Perl_sv_catpvf(aTHX_ dsv, "\t-");
}
Perl_sv_catpvf(aTHX_ dsv, "\t%s",
frame->object_name_size &&
frame->object_name_offset ?
(char*)bt + frame->object_name_offset : "-");
/* The frame->object_base_addr is not output,
* but it is used for symbolizing/symbolicating. */
sv_catpvs(dsv, "\n");
}
Perl_free_c_backtrace(bt);
return dsv;
}
return NULL;
}
/*
=for apidoc dump_c_backtrace
Dumps the C backtrace to the given C<fp>.
Returns true if a backtrace could be retrieved, false if not.
=cut
*/
bool
Perl_dump_c_backtrace(pTHX_ PerlIO* fp, int depth, int skip)
{
SV* sv;
PERL_ARGS_ASSERT_DUMP_C_BACKTRACE;
sv = Perl_get_c_backtrace_dump(aTHX_ depth, skip);
if (sv) {
sv_2mortal(sv);
PerlIO_printf(fp, "%s", SvPV_nolen(sv));
return TRUE;
}
return FALSE;
}
#endif /* #ifdef USE_C_BACKTRACE */
#ifdef PERL_TSA_ACTIVE
/* pthread_mutex_t and perl_mutex are typedef equivalent
* so casting the pointers is fine. */
int perl_tsa_mutex_lock(perl_mutex* mutex)
{
return pthread_mutex_lock((pthread_mutex_t *) mutex);
}
int perl_tsa_mutex_unlock(perl_mutex* mutex)
{
return pthread_mutex_unlock((pthread_mutex_t *) mutex);
}
int perl_tsa_mutex_destroy(perl_mutex* mutex)
{
return pthread_mutex_destroy((pthread_mutex_t *) mutex);
}
#endif
#ifdef USE_DTRACE
/* log a sub call or return */
void
Perl_dtrace_probe_call(pTHX_ CV *cv, bool is_call)
{
const char *func;
const char *file;
const char *stash;
const COP *start;
line_t line;
PERL_ARGS_ASSERT_DTRACE_PROBE_CALL;
if (CvNAMED(cv)) {
HEK *hek = CvNAME_HEK(cv);
func = HEK_KEY(hek);
}
else {
GV *gv = CvGV(cv);
func = GvENAME(gv);
}
start = (const COP *)CvSTART(cv);
file = CopFILE(start);
line = CopLINE(start);
stash = CopSTASHPV(start);
if (is_call) {
PERL_SUB_ENTRY(func, file, line, stash);
}
else {
PERL_SUB_RETURN(func, file, line, stash);
}
}
/* log a require file loading/loaded */
void
Perl_dtrace_probe_load(pTHX_ const char *name, bool is_loading)
{
PERL_ARGS_ASSERT_DTRACE_PROBE_LOAD;
if (is_loading) {
PERL_LOADING_FILE(name);
}
else {
PERL_LOADED_FILE(name);
}
}
/* log an op execution */
void
Perl_dtrace_probe_op(pTHX_ const OP *op)
{
PERL_ARGS_ASSERT_DTRACE_PROBE_OP;
PERL_OP_ENTRY(OP_NAME(op));
}
/* log a compile/run phase change */
void
Perl_dtrace_probe_phase(pTHX_ enum perl_phase phase)
{
const char *ph_old = PL_phase_names[PL_phase];
const char *ph_new = PL_phase_names[phase];
PERL_PHASE_CHANGE(ph_new, ph_old);
}
#endif
/*
* ex: set ts=8 sts=4 sw=4 et:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_410_0 |
crossvul-cpp_data_good_5127_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% IIIII M M AAA GGGG EEEEE %
% I MM MM A A G E %
% I M M M AAAAA G GG EEE %
% I M M A A G G E %
% IIIII M M A A GGGG EEEEE %
% %
% %
% MagickCore Image Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% 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 "MagickCore/studio.h"
#include "MagickCore/animate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/client.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/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/compress.h"
#include "MagickCore/constitute.h"
#include "MagickCore/display.h"
#include "MagickCore/draw.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/histogram.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magic.h"
#include "MagickCore/magick.h"
#include "MagickCore/magick-private.h"
#include "MagickCore/memory_.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/paint.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/quantize.h"
#include "MagickCore/random_.h"
#include "MagickCore/resource_.h"
#include "MagickCore/segment.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/signature-private.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/threshold.h"
#include "MagickCore/timer.h"
#include "MagickCore/token.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
#include "MagickCore/version.h"
#include "MagickCore/xwindow-private.h"
/*
Constant declaration.
*/
const char
AlphaColor[] = "#bdbdbd", /* gray */
BackgroundColor[] = "#ffffff", /* white */
BorderColor[] = "#dfdfdf", /* gray */
DefaultTileFrame[] = "15x15+3+3",
DefaultTileGeometry[] = "120x120+4+3>",
DefaultTileLabel[] = "%f\n%G\n%b",
ForegroundColor[] = "#000", /* black */
LoadImageTag[] = "Load/Image",
LoadImagesTag[] = "Load/Images",
PSDensityGeometry[] = "72.0x72.0",
PSPageGeometry[] = "612x792",
SaveImageTag[] = "Save/Image",
SaveImagesTag[] = "Save/Images",
TransparentColor[] = "#00000000"; /* transparent black */
const double
DefaultResolution = 72.0;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireImage() returns a pointer to an image structure initialized to
% default values.
%
% The format of the AcquireImage method is:
%
% Image *AcquireImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: Many of the image default values are set from this
% structure. For example, filename, compression, depth, background color,
% and others.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AcquireImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
Image
*image;
MagickStatusType
flags;
/*
Allocate image structure.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
image=(Image *) AcquireMagickMemory(sizeof(*image));
if (image == (Image *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(image,0,sizeof(*image));
/*
Initialize Image structure.
*/
(void) CopyMagickString(image->magick,"MIFF",MagickPathExtent);
image->storage_class=DirectClass;
image->depth=MAGICKCORE_QUANTUM_DEPTH;
image->colorspace=sRGBColorspace;
image->rendering_intent=PerceptualIntent;
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.red_primary.z=0.0300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.green_primary.z=0.1000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.blue_primary.z=0.7900f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
image->chromaticity.white_point.z=0.3583f;
image->interlace=NoInterlace;
image->ticks_per_second=UndefinedTicksPerSecond;
image->compose=OverCompositeOp;
(void) QueryColorCompliance(AlphaColor,AllCompliance,&image->alpha_color,
exception);
(void) QueryColorCompliance(BackgroundColor,AllCompliance,
&image->background_color,exception);
(void) QueryColorCompliance(BorderColor,AllCompliance,&image->border_color,
exception);
(void) QueryColorCompliance(TransparentColor,AllCompliance,
&image->transparent_color,exception);
GetTimerInfo(&image->timer);
image->cache=AcquirePixelCache(0);
image->channel_mask=DefaultChannels;
image->channel_map=AcquirePixelChannelMap();
image->blob=CloneBlobInfo((BlobInfo *) NULL);
image->timestamp=time((time_t *) NULL);
image->debug=IsEventLogging();
image->reference_count=1;
image->semaphore=AcquireSemaphoreInfo();
image->signature=MagickCoreSignature;
if (image_info == (ImageInfo *) NULL)
return(image);
/*
Transfer image info.
*/
SetBlobExempt(image,image_info->file != (FILE *) NULL ? MagickTrue :
MagickFalse);
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick,image_info->magick,MagickPathExtent);
if (image_info->size != (char *) NULL)
{
(void) ParseAbsoluteGeometry(image_info->size,&image->extract_info);
image->columns=image->extract_info.width;
image->rows=image->extract_info.height;
image->offset=image->extract_info.x;
image->extract_info.x=0;
image->extract_info.y=0;
}
if (image_info->extract != (char *) NULL)
{
RectangleInfo
geometry;
flags=ParseAbsoluteGeometry(image_info->extract,&geometry);
if (((flags & XValue) != 0) || ((flags & YValue) != 0))
{
image->extract_info=geometry;
Swap(image->columns,image->extract_info.width);
Swap(image->rows,image->extract_info.height);
}
}
image->compression=image_info->compression;
image->quality=image_info->quality;
image->endian=image_info->endian;
image->interlace=image_info->interlace;
image->units=image_info->units;
if (image_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
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;
}
if (image_info->page != (char *) NULL)
{
char
*geometry;
image->page=image->extract_info;
geometry=GetPageGeometry(image_info->page);
(void) ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
}
if (image_info->depth != 0)
image->depth=image_info->depth;
image->dither=image_info->dither;
image->alpha_color=image_info->alpha_color;
image->background_color=image_info->background_color;
image->border_color=image_info->border_color;
image->transparent_color=image_info->transparent_color;
image->ping=image_info->ping;
image->progress_monitor=image_info->progress_monitor;
image->client_data=image_info->client_data;
if (image_info->cache != (void *) NULL)
ClonePixelCacheMethods(image->cache,image_info->cache);
/*
Set all global options that map to per-image settings.
*/
(void) SyncImageSettings(image_info,image,exception);
/*
Global options that are only set for new images.
*/
option=GetImageOption(image_info,"delay");
if (option != (const char *) NULL)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(option,&geometry_info);
if ((flags & GreaterValue) != 0)
{
if (image->delay > (size_t) floor(geometry_info.rho+0.5))
image->delay=(size_t) floor(geometry_info.rho+0.5);
}
else
if ((flags & LessValue) != 0)
{
if (image->delay < (size_t) floor(geometry_info.rho+0.5))
image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5);
}
else
image->delay=(size_t) floor(geometry_info.rho+0.5);
if ((flags & SigmaValue) != 0)
image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5);
}
option=GetImageOption(image_info,"dispose");
if (option != (const char *) NULL)
image->dispose=(DisposeType) ParseCommandOption(MagickDisposeOptions,
MagickFalse,option);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireImageInfo() allocates the ImageInfo structure.
%
% The format of the AcquireImageInfo method is:
%
% ImageInfo *AcquireImageInfo(void)
%
*/
MagickExport ImageInfo *AcquireImageInfo(void)
{
ImageInfo
*image_info;
image_info=(ImageInfo *) AcquireMagickMemory(sizeof(*image_info));
if (image_info == (ImageInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
GetImageInfo(image_info);
return(image_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e N e x t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireNextImage() initializes the next image in a sequence to
% default values. The next member of image points to the newly allocated
% image. If there is a memory shortage, next is assigned NULL.
%
% The format of the AcquireNextImage method is:
%
% void AcquireNextImage(const ImageInfo *image_info,Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: Many of the image default values are set from this
% structure. For example, filename, compression, depth, background color,
% and others.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport void AcquireNextImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
/*
Allocate image structure.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
image->next=AcquireImage(image_info,exception);
if (GetNextImageInList(image) == (Image *) NULL)
return;
(void) CopyMagickString(GetNextImageInList(image)->filename,image->filename,
MagickPathExtent);
if (image_info != (ImageInfo *) NULL)
(void) CopyMagickString(GetNextImageInList(image)->filename,
image_info->filename,MagickPathExtent);
DestroyBlob(GetNextImageInList(image));
image->next->blob=ReferenceBlob(image->blob);
image->next->endian=image->endian;
image->next->scene=image->scene+1;
image->next->previous=image;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A p p e n d I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AppendImages() takes all images from the current image pointer to the end
% of the image list and appends them to each other top-to-bottom if the
% stack parameter is true, otherwise left-to-right.
%
% The current gravity setting effects how the image is justified in the
% final image.
%
% The format of the AppendImages method is:
%
% Image *AppendImages(const Image *images,const MagickBooleanType stack,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o stack: A value other than 0 stacks the images top-to-bottom.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AppendImages(const Image *images,
const MagickBooleanType stack,ExceptionInfo *exception)
{
#define AppendImageTag "Append/Image"
CacheView
*append_view;
Image
*append_image;
MagickBooleanType
status;
MagickOffsetType
n;
PixelTrait
alpha_trait;
RectangleInfo
geometry;
register const Image
*next;
size_t
depth,
height,
number_images,
width;
ssize_t
x_offset,
y,
y_offset;
/*
Compute maximum area of appended area.
*/
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
alpha_trait=images->alpha_trait;
number_images=1;
width=images->columns;
height=images->rows;
depth=images->depth;
next=GetNextImageInList(images);
for ( ; next != (Image *) NULL; next=GetNextImageInList(next))
{
if (next->depth > depth)
depth=next->depth;
if (next->alpha_trait != UndefinedPixelTrait)
alpha_trait=BlendPixelTrait;
number_images++;
if (stack != MagickFalse)
{
if (next->columns > width)
width=next->columns;
height+=next->rows;
continue;
}
width+=next->columns;
if (next->rows > height)
height=next->rows;
}
/*
Append images.
*/
append_image=CloneImage(images,width,height,MagickTrue,exception);
if (append_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(append_image,DirectClass,exception) == MagickFalse)
{
append_image=DestroyImage(append_image);
return((Image *) NULL);
}
append_image->depth=depth;
append_image->alpha_trait=alpha_trait;
(void) SetImageBackgroundColor(append_image,exception);
status=MagickTrue;
x_offset=0;
y_offset=0;
next=images;
append_view=AcquireAuthenticCacheView(append_image,exception);
for (n=0; n < (MagickOffsetType) number_images; n++)
{
CacheView
*image_view;
MagickBooleanType
proceed;
SetGeometry(append_image,&geometry);
GravityAdjustGeometry(next->columns,next->rows,next->gravity,&geometry);
if (stack != MagickFalse)
x_offset-=geometry.x;
else
y_offset-=geometry.y;
image_view=AcquireVirtualCacheView(next,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(next,next,next->rows,1)
#endif
for (y=0; y < (ssize_t) next->rows; y++)
{
MagickBooleanType
sync;
PixelInfo
pixel;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,next->columns,1,exception);
q=QueueCacheViewAuthenticPixels(append_view,x_offset,y+y_offset,
next->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
GetPixelInfo(next,&pixel);
for (x=0; x < (ssize_t) next->columns; x++)
{
if (GetPixelReadMask(next,p) == 0)
{
SetPixelBackgoundColor(append_image,q);
p+=GetPixelChannels(next);
q+=GetPixelChannels(append_image);
continue;
}
GetPixelInfoPixel(next,p,&pixel);
SetPixelViaPixelInfo(append_image,&pixel,q);
p+=GetPixelChannels(next);
q+=GetPixelChannels(append_image);
}
sync=SyncCacheViewAuthenticPixels(append_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (stack == MagickFalse)
{
x_offset+=(ssize_t) next->columns;
y_offset=0;
}
else
{
x_offset=0;
y_offset+=(ssize_t) next->rows;
}
proceed=SetImageProgress(append_image,AppendImageTag,n,number_images);
if (proceed == MagickFalse)
break;
next=GetNextImageInList(next);
}
append_view=DestroyCacheView(append_view);
if (status == MagickFalse)
append_image=DestroyImage(append_image);
return(append_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C a t c h I m a g e E x c e p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CatchImageException() returns if no exceptions are found in the image
% sequence, otherwise it determines the most severe exception and reports
% it as a warning or error depending on the severity.
%
% The format of the CatchImageException method is:
%
% ExceptionType CatchImageException(Image *image)
%
% A description of each parameter follows:
%
% o image: An image sequence.
%
*/
MagickExport ExceptionType CatchImageException(Image *image)
{
ExceptionInfo
*exception;
ExceptionType
severity;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
exception=AcquireExceptionInfo();
CatchException(exception);
severity=exception->severity;
exception=DestroyExceptionInfo(exception);
return(severity);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l i p I m a g e P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClipImagePath() sets the image clip mask based any clipping path information
% if it exists.
%
% The format of the ClipImagePath method is:
%
% MagickBooleanType ClipImagePath(Image *image,const char *pathname,
% const MagickBooleanType inside,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o pathname: name of clipping path resource. If name is preceded by #, use
% clipping path numbered by name.
%
% o inside: if non-zero, later operations take effect inside clipping path.
% Otherwise later operations take effect outside clipping path.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ClipImage(Image *image,ExceptionInfo *exception)
{
return(ClipImagePath(image,"#1",MagickTrue,exception));
}
MagickExport MagickBooleanType ClipImagePath(Image *image,const char *pathname,
const MagickBooleanType inside,ExceptionInfo *exception)
{
#define ClipImagePathTag "ClipPath/Image"
char
*property;
const char
*value;
Image
*clip_mask;
ImageInfo
*image_info;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pathname != NULL);
property=AcquireString(pathname);
(void) FormatLocaleString(property,MagickPathExtent,"8BIM:1999,2998:%s",
pathname);
value=GetImageProperty(image,property,exception);
property=DestroyString(property);
if (value == (const char *) NULL)
{
ThrowFileException(exception,OptionError,"NoClipPathDefined",
image->filename);
return(MagickFalse);
}
image_info=AcquireImageInfo();
(void) CopyMagickString(image_info->filename,image->filename,
MagickPathExtent);
(void) ConcatenateMagickString(image_info->filename,pathname,
MagickPathExtent);
clip_mask=BlobToImage(image_info,value,strlen(value),exception);
image_info=DestroyImageInfo(image_info);
if (clip_mask == (Image *) NULL)
return(MagickFalse);
if (clip_mask->storage_class == PseudoClass)
{
(void) SyncImage(clip_mask,exception);
if (SetImageStorageClass(clip_mask,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
if (inside == MagickFalse)
(void) NegateImage(clip_mask,MagickFalse,exception);
(void) FormatLocaleString(clip_mask->magick_filename,MagickPathExtent,
"8BIM:1999,2998:%s\nPS",pathname);
(void) SetImageMask(image,ReadPixelMask,clip_mask,exception);
clip_mask=DestroyImage(clip_mask);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneImage() copies an image and returns the copy as a new image object.
%
% If the specified columns and rows is 0, an exact copy of the image is
% returned, otherwise the pixel data is undefined and must be initialized
% with the QueueAuthenticPixels() and SyncAuthenticPixels() methods. On
% failure, a NULL image is returned and exception describes the reason for the
% failure.
%
% The format of the CloneImage method is:
%
% Image *CloneImage(const Image *image,const size_t columns,
% const size_t rows,const MagickBooleanType orphan,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the cloned image.
%
% o rows: the number of rows in the cloned image.
%
% o detach: With a value other than 0, the cloned image is detached from
% its parent I/O stream.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *CloneImage(const Image *image,const size_t columns,
const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception)
{
Image
*clone_image;
double
scale;
size_t
length;
/*
Clone the image.
*/
assert(image != (const 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);
if ((image->columns == 0) || (image->rows == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"NegativeOrZeroImageSize","`%s'",image->filename);
return((Image *) NULL);
}
clone_image=(Image *) AcquireMagickMemory(sizeof(*clone_image));
if (clone_image == (Image *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(clone_image,0,sizeof(*clone_image));
clone_image->signature=MagickCoreSignature;
clone_image->storage_class=image->storage_class;
clone_image->number_channels=image->number_channels;
clone_image->number_meta_channels=image->number_meta_channels;
clone_image->metacontent_extent=image->metacontent_extent;
clone_image->colorspace=image->colorspace;
clone_image->read_mask=image->read_mask;
clone_image->write_mask=image->write_mask;
clone_image->alpha_trait=image->alpha_trait;
clone_image->columns=image->columns;
clone_image->rows=image->rows;
clone_image->dither=image->dither;
if (image->colormap != (PixelInfo *) NULL)
{
/*
Allocate and copy the image colormap.
*/
clone_image->colors=image->colors;
length=(size_t) image->colors;
clone_image->colormap=(PixelInfo *) AcquireQuantumMemory(length,
sizeof(*clone_image->colormap));
if (clone_image->colormap == (PixelInfo *) NULL)
{
clone_image=DestroyImage(clone_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickMemory(clone_image->colormap,image->colormap,length*
sizeof(*clone_image->colormap));
}
clone_image->image_info=CloneImageInfo(image->image_info);
(void) CloneImageProfiles(clone_image,image);
(void) CloneImageProperties(clone_image,image);
(void) CloneImageArtifacts(clone_image,image);
GetTimerInfo(&clone_image->timer);
if (image->ascii85 != (void *) NULL)
Ascii85Initialize(clone_image);
clone_image->magick_columns=image->magick_columns;
clone_image->magick_rows=image->magick_rows;
clone_image->type=image->type;
clone_image->channel_mask=image->channel_mask;
clone_image->channel_map=ClonePixelChannelMap(image->channel_map);
(void) CopyMagickString(clone_image->magick_filename,image->magick_filename,
MagickPathExtent);
(void) CopyMagickString(clone_image->magick,image->magick,MagickPathExtent);
(void) CopyMagickString(clone_image->filename,image->filename,
MagickPathExtent);
clone_image->progress_monitor=image->progress_monitor;
clone_image->client_data=image->client_data;
clone_image->reference_count=1;
clone_image->next=image->next;
clone_image->previous=image->previous;
clone_image->list=NewImageList();
if (detach == MagickFalse)
clone_image->blob=ReferenceBlob(image->blob);
else
{
clone_image->next=NewImageList();
clone_image->previous=NewImageList();
clone_image->blob=CloneBlobInfo((BlobInfo *) NULL);
}
clone_image->ping=image->ping;
clone_image->debug=IsEventLogging();
clone_image->semaphore=AcquireSemaphoreInfo();
if ((columns == 0) || (rows == 0))
{
if (image->montage != (char *) NULL)
(void) CloneString(&clone_image->montage,image->montage);
if (image->directory != (char *) NULL)
(void) CloneString(&clone_image->directory,image->directory);
clone_image->cache=ReferencePixelCache(image->cache);
return(clone_image);
}
scale=1.0;
if (image->columns != 0)
scale=(double) columns/(double) image->columns;
clone_image->page.width=(size_t) floor(scale*image->page.width+0.5);
clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5);
clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5);
scale=1.0;
if (image->rows != 0)
scale=(double) rows/(double) image->rows;
clone_image->page.height=(size_t) floor(scale*image->page.height+0.5);
clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5);
clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5);
clone_image->columns=columns;
clone_image->rows=rows;
clone_image->cache=ClonePixelCache(image->cache);
return(clone_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneImageInfo() makes a copy of the given image info structure. If
% NULL is specified, a new image info structure is created initialized to
% default values.
%
% The format of the CloneImageInfo method is:
%
% ImageInfo *CloneImageInfo(const ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport ImageInfo *CloneImageInfo(const ImageInfo *image_info)
{
ImageInfo
*clone_info;
clone_info=AcquireImageInfo();
if (image_info == (ImageInfo *) NULL)
return(clone_info);
clone_info->compression=image_info->compression;
clone_info->temporary=image_info->temporary;
clone_info->adjoin=image_info->adjoin;
clone_info->antialias=image_info->antialias;
clone_info->scene=image_info->scene;
clone_info->number_scenes=image_info->number_scenes;
clone_info->depth=image_info->depth;
(void) CloneString(&clone_info->size,image_info->size);
(void) CloneString(&clone_info->extract,image_info->extract);
(void) CloneString(&clone_info->scenes,image_info->scenes);
(void) CloneString(&clone_info->page,image_info->page);
clone_info->interlace=image_info->interlace;
clone_info->endian=image_info->endian;
clone_info->units=image_info->units;
clone_info->quality=image_info->quality;
(void) CloneString(&clone_info->sampling_factor,image_info->sampling_factor);
(void) CloneString(&clone_info->server_name,image_info->server_name);
(void) CloneString(&clone_info->font,image_info->font);
(void) CloneString(&clone_info->texture,image_info->texture);
(void) CloneString(&clone_info->density,image_info->density);
clone_info->pointsize=image_info->pointsize;
clone_info->fuzz=image_info->fuzz;
clone_info->alpha_color=image_info->alpha_color;
clone_info->background_color=image_info->background_color;
clone_info->border_color=image_info->border_color;
clone_info->transparent_color=image_info->transparent_color;
clone_info->dither=image_info->dither;
clone_info->monochrome=image_info->monochrome;
clone_info->colorspace=image_info->colorspace;
clone_info->type=image_info->type;
clone_info->orientation=image_info->orientation;
clone_info->ping=image_info->ping;
clone_info->verbose=image_info->verbose;
clone_info->progress_monitor=image_info->progress_monitor;
clone_info->client_data=image_info->client_data;
clone_info->cache=image_info->cache;
if (image_info->cache != (void *) NULL)
clone_info->cache=ReferencePixelCache(image_info->cache);
if (image_info->profile != (void *) NULL)
clone_info->profile=(void *) CloneStringInfo((StringInfo *)
image_info->profile);
SetImageInfoFile(clone_info,image_info->file);
SetImageInfoBlob(clone_info,image_info->blob,image_info->length);
clone_info->stream=image_info->stream;
(void) CopyMagickString(clone_info->magick,image_info->magick,
MagickPathExtent);
(void) CopyMagickString(clone_info->unique,image_info->unique,
MagickPathExtent);
(void) CopyMagickString(clone_info->filename,image_info->filename,
MagickPathExtent);
clone_info->channel=image_info->channel;
(void) CloneImageOptions(clone_info,image_info);
clone_info->debug=IsEventLogging();
clone_info->signature=image_info->signature;
return(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o p y I m a g e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CopyImagePixels() copies pixels from the source image as defined by the
% geometry the destination image at the specified offset.
%
% The format of the CopyImagePixels method is:
%
% MagickBooleanType CopyImagePixels(Image *image,const Image *source_image,
% const RectangleInfo *geometry,const OffsetInfo *offset,
% ExceptionInfo *exception);
%
% A description of each parameter follows:
%
% o image: the destination image.
%
% o source_image: the source image.
%
% o geometry: define the dimensions of the source pixel rectangle.
%
% o offset: define the offset in the destination image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType CopyImagePixels(Image *image,
const Image *source_image,const RectangleInfo *geometry,
const OffsetInfo *offset,ExceptionInfo *exception)
{
#define CopyImageTag "Copy/Image"
CacheView
*image_view,
*source_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(source_image != (Image *) NULL);
assert(geometry != (RectangleInfo *) NULL);
assert(offset != (OffsetInfo *) NULL);
if ((offset->x < 0) || (offset->y < 0) ||
((ssize_t) (offset->x+geometry->width) > (ssize_t) image->columns) ||
((ssize_t) (offset->y+geometry->height) > (ssize_t) image->rows))
ThrowBinaryException(OptionError,"GeometryDoesNotContainImage",
image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
/*
Copy image pixels.
*/
status=MagickTrue;
progress=0;
source_view=AcquireVirtualCacheView(source_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,source_image,geometry->height,1)
#endif
for (y=0; y < (ssize_t) geometry->height; y++)
{
MagickBooleanType
sync;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(source_view,geometry->x,y+geometry->y,
geometry->width,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,offset->x,y+offset->y,
geometry->width,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) geometry->width; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait source_traits=GetPixelChannelTraits(source_image,channel);
if ((traits == UndefinedPixelTrait) ||
(source_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(image,channel,p[i],q);
}
p+=GetPixelChannels(source_image);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_CopyImage)
#endif
proceed=SetImageProgress(image,CopyImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImage() dereferences an image, deallocating memory associated with
% the image if the reference count becomes zero.
%
% The format of the DestroyImage method is:
%
% Image *DestroyImage(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport Image *DestroyImage(Image *image)
{
MagickBooleanType
destroy;
/*
Dereference image.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
destroy=MagickFalse;
LockSemaphoreInfo(image->semaphore);
image->reference_count--;
if (image->reference_count == 0)
destroy=MagickTrue;
UnlockSemaphoreInfo(image->semaphore);
if (destroy == MagickFalse)
return((Image *) NULL);
/*
Destroy image.
*/
DestroyImagePixels(image);
image->channel_map=DestroyPixelChannelMap(image->channel_map);
if (image->montage != (char *) NULL)
image->montage=DestroyString(image->montage);
if (image->directory != (char *) NULL)
image->directory=DestroyString(image->directory);
if (image->colormap != (PixelInfo *) NULL)
image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
if (image->geometry != (char *) NULL)
image->geometry=DestroyString(image->geometry);
DestroyImageProfiles(image);
DestroyImageProperties(image);
DestroyImageArtifacts(image);
if (image->ascii85 != (Ascii85Info *) NULL)
image->ascii85=(Ascii85Info *) RelinquishMagickMemory(image->ascii85);
if (image->image_info != (ImageInfo *) NULL)
image->image_info=DestroyImageInfo(image->image_info);
DestroyBlob(image);
if (image->semaphore != (SemaphoreInfo *) NULL)
RelinquishSemaphoreInfo(&image->semaphore);
image->signature=(~MagickCoreSignature);
image=(Image *) RelinquishMagickMemory(image);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImageInfo() deallocates memory associated with an ImageInfo
% structure.
%
% The format of the DestroyImageInfo method is:
%
% ImageInfo *DestroyImageInfo(ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport ImageInfo *DestroyImageInfo(ImageInfo *image_info)
{
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
if (image_info->size != (char *) NULL)
image_info->size=DestroyString(image_info->size);
if (image_info->extract != (char *) NULL)
image_info->extract=DestroyString(image_info->extract);
if (image_info->scenes != (char *) NULL)
image_info->scenes=DestroyString(image_info->scenes);
if (image_info->page != (char *) NULL)
image_info->page=DestroyString(image_info->page);
if (image_info->sampling_factor != (char *) NULL)
image_info->sampling_factor=DestroyString(
image_info->sampling_factor);
if (image_info->server_name != (char *) NULL)
image_info->server_name=DestroyString(
image_info->server_name);
if (image_info->font != (char *) NULL)
image_info->font=DestroyString(image_info->font);
if (image_info->texture != (char *) NULL)
image_info->texture=DestroyString(image_info->texture);
if (image_info->density != (char *) NULL)
image_info->density=DestroyString(image_info->density);
if (image_info->cache != (void *) NULL)
image_info->cache=DestroyPixelCache(image_info->cache);
if (image_info->profile != (StringInfo *) NULL)
image_info->profile=(void *) DestroyStringInfo((StringInfo *)
image_info->profile);
DestroyImageOptions(image_info);
image_info->signature=(~MagickCoreSignature);
image_info=(ImageInfo *) RelinquishMagickMemory(image_info);
return(image_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D i s a s s o c i a t e I m a g e S t r e a m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DisassociateImageStream() disassociates the image stream. It checks if the
% blob of the specified image is referenced by other images. If the reference
% count is higher then 1 a new blob is assigned to the specified image.
%
% The format of the DisassociateImageStream method is:
%
% void DisassociateImageStream(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void DisassociateImageStream(Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
DisassociateBlob(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageInfo() initializes image_info to default values.
%
% The format of the GetImageInfo method is:
%
% void GetImageInfo(ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport void GetImageInfo(ImageInfo *image_info)
{
char
*synchronize;
ExceptionInfo
*exception;
/*
File and image dimension members.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image_info != (ImageInfo *) NULL);
(void) ResetMagickMemory(image_info,0,sizeof(*image_info));
image_info->adjoin=MagickTrue;
image_info->interlace=NoInterlace;
image_info->channel=DefaultChannels;
image_info->quality=UndefinedCompressionQuality;
image_info->antialias=MagickTrue;
image_info->dither=MagickTrue;
synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE");
if (synchronize != (const char *) NULL)
{
image_info->synchronize=IsStringTrue(synchronize);
synchronize=DestroyString(synchronize);
}
exception=AcquireExceptionInfo();
(void) QueryColorCompliance(AlphaColor,AllCompliance,&image_info->alpha_color,
exception);
(void) QueryColorCompliance(BackgroundColor,AllCompliance,
&image_info->background_color,exception);
(void) QueryColorCompliance(BorderColor,AllCompliance,
&image_info->border_color,exception);
(void) QueryColorCompliance(TransparentColor,AllCompliance,
&image_info->transparent_color,exception);
exception=DestroyExceptionInfo(exception);
image_info->debug=IsEventLogging();
image_info->signature=MagickCoreSignature;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e I n f o F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageInfoFile() returns the image info file member.
%
% The format of the GetImageInfoFile method is:
%
% FILE *GetImageInfoFile(const ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport FILE *GetImageInfoFile(const ImageInfo *image_info)
{
return(image_info->file);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageMask() returns the mask associated with the image.
%
% The format of the GetImageMask method is:
%
% Image *GetImageMask(const Image *image,const PixelMask type,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o type: the mask type, ReadPixelMask or WritePixelMask.
%
*/
MagickExport Image *GetImageMask(const Image *image,const PixelMask type,
ExceptionInfo *exception)
{
CacheView
*mask_view,
*image_view;
Image
*mask_image;
MagickBooleanType
status;
ssize_t
y;
/*
Get image mask.
*/
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
mask_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (mask_image == (Image *) NULL)
return((Image *) NULL);
status=MagickTrue;
mask_image->alpha_trait=UndefinedPixelTrait;
(void) SetImageColorspace(mask_image,GRAYColorspace,exception);
mask_image->read_mask=MagickFalse;
image_view=AcquireVirtualCacheView(image,exception);
mask_view=AcquireAuthenticCacheView(mask_image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(mask_view,0,y,mask_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
switch (type)
{
case WritePixelMask:
{
SetPixelGray(mask_image,GetPixelWriteMask(image,p),q);
break;
}
default:
{
SetPixelGray(mask_image,GetPixelReadMask(image,p),q);
break;
}
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(mask_image);
}
if (SyncCacheViewAuthenticPixels(mask_view,exception) == MagickFalse)
status=MagickFalse;
}
mask_view=DestroyCacheView(mask_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
mask_image=DestroyImage(mask_image);
return(mask_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e R e f e r e n c e C o u n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageReferenceCount() returns the image reference count.
%
% The format of the GetReferenceCount method is:
%
% ssize_t GetImageReferenceCount(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport ssize_t GetImageReferenceCount(Image *image)
{
ssize_t
reference_count;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
LockSemaphoreInfo(image->semaphore);
reference_count=image->reference_count;
UnlockSemaphoreInfo(image->semaphore);
return(reference_count);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e V i r t u a l P i x e l M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageVirtualPixelMethod() gets the "virtual pixels" method for the
% image. A virtual pixel is any pixel access that is outside the boundaries
% of the image cache.
%
% The format of the GetImageVirtualPixelMethod() method is:
%
% VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
return(GetPixelCacheVirtualMethod(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n t e r p r e t I m a g e F i l e n a m e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InterpretImageFilename() interprets embedded characters in an image filename.
% The filename length is returned.
%
% The format of the InterpretImageFilename method is:
%
% size_t InterpretImageFilename(const ImageInfo *image_info,Image *image,
% const char *format,int value,char *filename,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info..
%
% o image: the image.
%
% o format: A filename describing the format to use to write the numeric
% argument. Only the first numeric format identifier is replaced.
%
% o value: Numeric value to substitute into format filename.
%
% o filename: return the formatted filename in this character buffer.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport size_t InterpretImageFilename(const ImageInfo *image_info,
Image *image,const char *format,int value,char *filename,
ExceptionInfo *exception)
{
char
*q;
int
c;
MagickBooleanType
canonical;
register const char
*p;
size_t
length;
canonical=MagickFalse;
length=0;
(void) CopyMagickString(filename,format,MagickPathExtent);
for (p=strchr(format,'%'); p != (char *) NULL; p=strchr(p+1,'%'))
{
q=(char *) p+1;
if (*q == '%')
{
p=q+1;
continue;
}
if (*q == '0')
{
ssize_t
foo;
foo=(ssize_t) strtol(q,&q,10);
(void) foo;
}
switch (*q)
{
case 'd':
case 'o':
case 'x':
{
q++;
c=(*q);
*q='\0';
(void) FormatLocaleString(filename+(p-format),(size_t)
(MagickPathExtent-(p-format)),p,value);
*q=c;
(void) ConcatenateMagickString(filename,q,MagickPathExtent);
canonical=MagickTrue;
if (*(q-1) != '%')
break;
p++;
break;
}
case '[':
{
char
pattern[MagickPathExtent];
const char
*option;
register char
*r;
register ssize_t
i;
ssize_t
depth;
/*
Image option.
*/
/* FUTURE: Compare update with code from InterpretImageProperties()
Note that a 'filename:' property should not need depth recursion.
*/
if (strchr(p,']') == (char *) NULL)
break;
depth=1;
r=q+1;
for (i=0; (i < (MagickPathExtent-1L)) && (*r != '\0'); i++)
{
if (*r == '[')
depth++;
if (*r == ']')
depth--;
if (depth <= 0)
break;
pattern[i]=(*r++);
}
pattern[i]='\0';
if (LocaleNCompare(pattern,"filename:",9) != 0)
break;
option=(const char *) NULL;
if (image != (Image *) NULL)
option=GetImageProperty(image,pattern,exception);
if ((option == (const char *) NULL) && (image != (Image *) NULL))
option=GetImageArtifact(image,pattern);
if ((option == (const char *) NULL) &&
(image_info != (ImageInfo *) NULL))
option=GetImageOption(image_info,pattern);
if (option == (const char *) NULL)
break;
q--;
c=(*q);
*q='\0';
(void) CopyMagickString(filename+(p-format-length),option,(size_t)
(MagickPathExtent-(p-format-length)));
length+=strlen(pattern)-1;
*q=c;
(void) ConcatenateMagickString(filename,r+1,MagickPathExtent);
canonical=MagickTrue;
if (*(q-1) != '%')
break;
p++;
break;
}
default:
break;
}
}
for (q=filename; *q != '\0'; q++)
if ((*q == '%') && (*(q+1) == '%'))
{
(void) CopyMagickString(q,q+1,(size_t) (MagickPathExtent-(q-filename)));
canonical=MagickTrue;
}
if (canonical == MagickFalse)
(void) CopyMagickString(filename,format,MagickPathExtent);
return(strlen(filename));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s H i g h D y n a m i c R a n g e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsHighDynamicRangeImage() returns MagickTrue if any pixel component is
% non-integer or exceeds the bounds of the quantum depth (e.g. for Q16
% 0..65535.
%
% The format of the IsHighDynamicRangeImage method is:
%
% MagickBooleanType IsHighDynamicRangeImage(const 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 IsHighDynamicRangeImage(const Image *image,
ExceptionInfo *exception)
{
#if !defined(MAGICKCORE_HDRI_SUPPORT)
(void) image;
(void) exception;
return(MagickFalse);
#else
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=MagickTrue;
image_view=AcquireVirtualCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
p+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
pixel;
PixelTrait
traits;
traits=GetPixelChannelTraits(image,(PixelChannel) i);
if (traits == UndefinedPixelTrait)
continue;
pixel=(double) p[i];
if ((pixel < 0.0) || (pixel > QuantumRange) ||
(pixel != (double) ((QuantumAny) pixel)))
break;
}
p+=GetPixelChannels(image);
if (i < (ssize_t) GetPixelChannels(image))
status=MagickFalse;
}
if (x < (ssize_t) image->columns)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status != MagickFalse ? MagickFalse : MagickTrue);
#endif
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s I m a g e O b j e c t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsImageObject() returns MagickTrue if the image sequence contains a valid
% set of image objects.
%
% The format of the IsImageObject method is:
%
% MagickBooleanType IsImageObject(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport MagickBooleanType IsImageObject(const Image *image)
{
register const Image
*p;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
for (p=image; p != (Image *) NULL; p=GetNextImageInList(p))
if (p->signature != MagickCoreSignature)
return(MagickFalse);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTaintImage() returns MagickTrue any pixel in the image has been altered
% since it was first constituted.
%
% The format of the IsTaintImage method is:
%
% MagickBooleanType IsTaintImage(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport MagickBooleanType IsTaintImage(const Image *image)
{
char
magick[MagickPathExtent],
filename[MagickPathExtent];
register const Image
*p;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
(void) CopyMagickString(magick,image->magick,MagickPathExtent);
(void) CopyMagickString(filename,image->filename,MagickPathExtent);
for (p=image; p != (Image *) NULL; p=GetNextImageInList(p))
{
if (p->taint != MagickFalse)
return(MagickTrue);
if (LocaleCompare(p->magick,magick) != 0)
return(MagickTrue);
if (LocaleCompare(p->filename,filename) != 0)
return(MagickTrue);
}
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M o d i f y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ModifyImage() ensures that there is only a single reference to the image
% to be modified, updating the provided image pointer to point to a clone of
% the original image if necessary.
%
% The format of the ModifyImage method is:
%
% MagickBooleanType ModifyImage(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 ModifyImage(Image **image,
ExceptionInfo *exception)
{
Image
*clone_image;
assert(image != (Image **) NULL);
assert(*image != (Image *) NULL);
assert((*image)->signature == MagickCoreSignature);
if ((*image)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename);
if (GetImageReferenceCount(*image) <= 1)
return(MagickTrue);
clone_image=CloneImage(*image,0,0,MagickTrue,exception);
LockSemaphoreInfo((*image)->semaphore);
(*image)->reference_count--;
UnlockSemaphoreInfo((*image)->semaphore);
*image=clone_image;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% N e w M a g i c k I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% NewMagickImage() creates a blank image canvas of the specified size and
% background color.
%
% The format of the NewMagickImage method is:
%
% Image *NewMagickImage(const ImageInfo *image_info,const size_t width,
% const size_t height,const PixelInfo *background,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width: the image width.
%
% o height: the image height.
%
% o background: the image color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *NewMagickImage(const ImageInfo *image_info,
const size_t width,const size_t height,const PixelInfo *background,
ExceptionInfo *exception)
{
CacheView
*image_view;
Image
*image;
MagickBooleanType
status;
ssize_t
y;
assert(image_info != (const ImageInfo *) NULL);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image_info->signature == MagickCoreSignature);
assert(background != (const PixelInfo *) NULL);
image=AcquireImage(image_info,exception);
image->columns=width;
image->rows=height;
image->colorspace=background->colorspace;
image->alpha_trait=background->alpha_trait;
image->fuzz=background->fuzz;
image->depth=background->depth;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelViaPixelInfo(image,background,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e f e r e n c e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReferenceImage() increments the reference count associated with an image
% returning a pointer to the image.
%
% The format of the ReferenceImage method is:
%
% Image *ReferenceImage(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport Image *ReferenceImage(Image *image)
{
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
LockSemaphoreInfo(image->semaphore);
image->reference_count++;
UnlockSemaphoreInfo(image->semaphore);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t I m a g e P a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetImagePage() resets the image page canvas and position.
%
% The format of the ResetImagePage method is:
%
% MagickBooleanType ResetImagePage(Image *image,const char *page)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o page: the relative page specification.
%
*/
MagickExport MagickBooleanType ResetImagePage(Image *image,const char *page)
{
MagickStatusType
flags;
RectangleInfo
geometry;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
flags=ParseAbsoluteGeometry(page,&geometry);
if ((flags & WidthValue) != 0)
{
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
image->page.width=geometry.width;
image->page.height=geometry.height;
}
if ((flags & AspectValue) != 0)
{
if ((flags & XValue) != 0)
image->page.x+=geometry.x;
if ((flags & YValue) != 0)
image->page.y+=geometry.y;
}
else
{
if ((flags & XValue) != 0)
{
image->page.x=geometry.x;
if ((image->page.width == 0) && (geometry.x > 0))
image->page.width=image->columns+geometry.x;
}
if ((flags & YValue) != 0)
{
image->page.y=geometry.y;
if ((image->page.height == 0) && (geometry.y > 0))
image->page.height=image->rows+geometry.y;
}
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e B a c k g r o u n d C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageBackgroundColor() initializes the image pixels to the image
% background color. The background color is defined by the background_color
% member of the image structure.
%
% The format of the SetImage method is:
%
% MagickBooleanType SetImageBackgroundColor(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 SetImageBackgroundColor(Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
PixelInfo
background;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
ConformPixelInfo(image,&image->background_color,&background,exception);
/*
Set image background color.
*/
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelViaPixelInfo(image,&background,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e C h a n n e l M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageChannelMask() sets the image channel mask from the specified channel
% mask.
%
% The format of the SetImageChannelMask method is:
%
% ChannelType SetImageChannelMask(Image *image,
% const ChannelType channel_mask)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel_mask: the channel mask.
%
*/
MagickExport ChannelType SetImageChannelMask(Image *image,
const ChannelType channel_mask)
{
return(SetPixelChannelMask(image,channel_mask));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageColor() set the entire image canvas to the specified color.
%
% The format of the SetImageColor method is:
%
% MagickBooleanType SetImageColor(Image *image,const PixelInfo *color,
% ExeptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o background: the image color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageColor(Image *image,
const PixelInfo *color,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
assert(color != (const PixelInfo *) NULL);
image->colorspace=color->colorspace;
image->alpha_trait=color->alpha_trait;
image->fuzz=color->fuzz;
image->depth=color->depth;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelViaPixelInfo(image,color,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e S t o r a g e C l a s s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageStorageClass() sets the image class: DirectClass for true color
% images or PseudoClass for colormapped images.
%
% The format of the SetImageStorageClass method is:
%
% MagickBooleanType SetImageStorageClass(Image *image,
% const ClassType storage_class,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o storage_class: The image class.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageStorageClass(Image *image,
const ClassType storage_class,ExceptionInfo *exception)
{
image->storage_class=storage_class;
return(SyncImagePixelCache(image,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e E x t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageExtent() sets the image size (i.e. columns & rows).
%
% The format of the SetImageExtent method is:
%
% MagickBooleanType SetImageExtent(Image *image,const size_t columns,
% const size_t rows,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: The image width in pixels.
%
% o rows: The image height in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageExtent(Image *image,const size_t columns,
const size_t rows,ExceptionInfo *exception)
{
if ((columns == 0) || (rows == 0))
return(MagickFalse);
image->columns=columns;
image->rows=rows;
if (image->depth > (8*sizeof(MagickSizeType)))
ThrowBinaryException(ImageError,"ImageDepthNotSupported",image->filename);
return(SyncImagePixelCache(image,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S e t I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageInfo() initializes the 'magick' field of the ImageInfo structure.
% It is set to a type of image format based on the prefix or suffix of the
% filename. For example, 'ps:image' returns PS indicating a Postscript image.
% JPEG is returned for this filename: 'image.jpg'. The filename prefix has
% precendence over the suffix. Use an optional index enclosed in brackets
% after a file name to specify a desired scene of a multi-resolution image
% format like Photo CD (e.g. img0001.pcd[4]). A True (non-zero) return value
% indicates success.
%
% The format of the SetImageInfo method is:
%
% MagickBooleanType SetImageInfo(ImageInfo *image_info,
% const unsigned int frames,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o frames: the number of images you intend to write.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageInfo(ImageInfo *image_info,
const unsigned int frames,ExceptionInfo *exception)
{
char
component[MagickPathExtent],
magic[MagickPathExtent],
*q;
const MagicInfo
*magic_info;
const MagickInfo
*magick_info;
ExceptionInfo
*sans_exception;
Image
*image;
MagickBooleanType
status;
register const char
*p;
ssize_t
count;
/*
Look for 'image.format' in filename.
*/
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
*component='\0';
GetPathComponent(image_info->filename,SubimagePath,component);
if (*component != '\0')
{
/*
Look for scene specification (e.g. img0001.pcd[4]).
*/
if (IsSceneGeometry(component,MagickFalse) == MagickFalse)
{
if (IsGeometry(component) != MagickFalse)
(void) CloneString(&image_info->extract,component);
}
else
{
size_t
first,
last;
(void) CloneString(&image_info->scenes,component);
image_info->scene=StringToUnsignedLong(image_info->scenes);
image_info->number_scenes=image_info->scene;
p=image_info->scenes;
for (q=(char *) image_info->scenes; *q != '\0'; p++)
{
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
first=(size_t) strtol(p,&q,10);
last=first;
while (isspace((int) ((unsigned char) *q)) != 0)
q++;
if (*q == '-')
last=(size_t) strtol(q+1,&q,10);
if (first > last)
Swap(first,last);
if (first < image_info->scene)
image_info->scene=first;
if (last > image_info->number_scenes)
image_info->number_scenes=last;
p=q;
}
image_info->number_scenes-=image_info->scene-1;
}
}
*component='\0';
if (*image_info->magick == '\0')
GetPathComponent(image_info->filename,ExtensionPath,component);
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (*component != '\0')
if ((LocaleCompare(component,"gz") == 0) ||
(LocaleCompare(component,"Z") == 0) ||
(LocaleCompare(component,"svgz") == 0) ||
(LocaleCompare(component,"wmz") == 0))
{
char
path[MagickPathExtent];
(void) CopyMagickString(path,image_info->filename,MagickPathExtent);
path[strlen(path)-strlen(component)-1]='\0';
GetPathComponent(path,ExtensionPath,component);
}
#endif
#if defined(MAGICKCORE_BZLIB_DELEGATE)
if (*component != '\0')
if (LocaleCompare(component,"bz2") == 0)
{
char
path[MagickPathExtent];
(void) CopyMagickString(path,image_info->filename,MagickPathExtent);
path[strlen(path)-strlen(component)-1]='\0';
GetPathComponent(path,ExtensionPath,component);
}
#endif
image_info->affirm=MagickFalse;
sans_exception=AcquireExceptionInfo();
if (*component != '\0')
{
MagickFormatType
format_type;
register ssize_t
i;
static const char
*format_type_formats[] =
{
"AUTOTRACE",
"BROWSE",
"DCRAW",
"EDIT",
"LAUNCH",
"MPEG:DECODE",
"MPEG:ENCODE",
"PRINT",
"PS:ALPHA",
"PS:CMYK",
"PS:COLOR",
"PS:GRAY",
"PS:MONO",
"SCAN",
"SHOW",
"WIN",
(char *) NULL
};
/*
User specified image format.
*/
(void) CopyMagickString(magic,component,MagickPathExtent);
LocaleUpper(magic);
/*
Look for explicit image formats.
*/
format_type=UndefinedFormatType;
magick_info=GetMagickInfo(magic,sans_exception);
if ((magick_info != (const MagickInfo *) NULL) &&
(magick_info->format_type != UndefinedFormatType))
format_type=magick_info->format_type;
i=0;
while ((format_type == UndefinedFormatType) &&
(format_type_formats[i] != (char *) NULL))
{
if ((*magic == *format_type_formats[i]) &&
(LocaleCompare(magic,format_type_formats[i]) == 0))
format_type=ExplicitFormatType;
i++;
}
if (format_type == UndefinedFormatType)
(void) CopyMagickString(image_info->magick,magic,MagickPathExtent);
else
if (format_type == ExplicitFormatType)
{
image_info->affirm=MagickTrue;
(void) CopyMagickString(image_info->magick,magic,MagickPathExtent);
}
if (LocaleCompare(magic,"RGB") == 0)
image_info->affirm=MagickFalse; /* maybe SGI disguised as RGB */
}
/*
Look for explicit 'format:image' in filename.
*/
*magic='\0';
GetPathComponent(image_info->filename,MagickPath,magic);
if (*magic == '\0')
(void) CopyMagickString(magic,image_info->magick,MagickPathExtent);
else
{
/*
User specified image format.
*/
LocaleUpper(magic);
if (IsMagickConflict(magic) == MagickFalse)
{
(void) CopyMagickString(image_info->magick,magic,MagickPathExtent);
image_info->affirm=MagickTrue;
}
}
magick_info=GetMagickInfo(magic,sans_exception);
sans_exception=DestroyExceptionInfo(sans_exception);
if ((magick_info == (const MagickInfo *) NULL) ||
(GetMagickEndianSupport(magick_info) == MagickFalse))
image_info->endian=UndefinedEndian;
GetPathComponent(image_info->filename,CanonicalPath,component);
(void) CopyMagickString(image_info->filename,component,MagickPathExtent);
if ((image_info->adjoin != MagickFalse) && (frames > 1))
{
/*
Test for multiple image support (e.g. image%02d.png).
*/
(void) InterpretImageFilename(image_info,(Image *) NULL,
image_info->filename,(int) image_info->scene,component,exception);
if ((LocaleCompare(component,image_info->filename) != 0) &&
(strchr(component,'%') == (char *) NULL))
image_info->adjoin=MagickFalse;
}
if ((image_info->adjoin != MagickFalse) && (frames > 0))
{
/*
Some image formats do not support multiple frames per file.
*/
magick_info=GetMagickInfo(magic,exception);
if (magick_info != (const MagickInfo *) NULL)
if (GetMagickAdjoin(magick_info) == MagickFalse)
image_info->adjoin=MagickFalse;
}
if (image_info->affirm != MagickFalse)
return(MagickTrue);
if (frames == 0)
{
unsigned char
*magick;
size_t
magick_size;
/*
Determine the image format from the first few bytes of the file.
*/
magick_size=GetMagicPatternExtent(exception);
if (magick_size == 0)
return(MagickFalse);
image=AcquireImage(image_info,exception);
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImage(image);
return(MagickFalse);
}
if ((IsBlobSeekable(image) == MagickFalse) ||
(IsBlobExempt(image) != MagickFalse))
{
/*
Copy standard input or pipe to temporary file.
*/
*component='\0';
status=ImageToFile(image,component,exception);
(void) CloseBlob(image);
if (status == MagickFalse)
{
image=DestroyImage(image);
return(MagickFalse);
}
SetImageInfoFile(image_info,(FILE *) NULL);
(void) CopyMagickString(image->filename,component,MagickPathExtent);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImage(image);
return(MagickFalse);
}
(void) CopyMagickString(image_info->filename,component,
MagickPathExtent);
image_info->temporary=MagickTrue;
}
magick=(unsigned char *) AcquireMagickMemory(magick_size);
if (magick == (unsigned char *) NULL)
{
(void) CloseBlob(image);
image=DestroyImage(image);
return(MagickFalse);
}
(void) ResetMagickMemory(magick,0,magick_size);
count=ReadBlob(image,magick_size,magick);
(void) SeekBlob(image,-((MagickOffsetType) count),SEEK_CUR);
(void) CloseBlob(image);
image=DestroyImage(image);
/*
Check magic.xml configuration file.
*/
sans_exception=AcquireExceptionInfo();
magic_info=GetMagicInfo(magick,(size_t) count,sans_exception);
magick=(unsigned char *) RelinquishMagickMemory(magick);
if ((magic_info != (const MagicInfo *) NULL) &&
(GetMagicName(magic_info) != (char *) NULL))
{
/*
Try to use magick_info that was determined earlier by the extension
*/
if ((magick_info != (const MagickInfo *) NULL) &&
(GetMagickUseExtension(magick_info) != MagickFalse) &&
(LocaleCompare(magick_info->module,GetMagicName(
magic_info)) == 0))
(void) CopyMagickString(image_info->magick,magick_info->name,
MagickPathExtent);
else
{
(void) CopyMagickString(image_info->magick,GetMagicName(
magic_info),MagickPathExtent);
magick_info=GetMagickInfo(image_info->magick,sans_exception);
}
if ((magick_info == (const MagickInfo *) NULL) ||
(GetMagickEndianSupport(magick_info) == MagickFalse))
image_info->endian=UndefinedEndian;
sans_exception=DestroyExceptionInfo(sans_exception);
return(MagickTrue);
}
magick_info=GetMagickInfo(image_info->magick,sans_exception);
if ((magick_info == (const MagickInfo *) NULL) ||
(GetMagickEndianSupport(magick_info) == MagickFalse))
image_info->endian=UndefinedEndian;
sans_exception=DestroyExceptionInfo(sans_exception);
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e I n f o B l o b %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageInfoBlob() sets the image info blob member.
%
% The format of the SetImageInfoBlob method is:
%
% void SetImageInfoBlob(ImageInfo *image_info,const void *blob,
% const size_t length)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o blob: the blob.
%
% o length: the blob length.
%
*/
MagickExport void SetImageInfoBlob(ImageInfo *image_info,const void *blob,
const size_t length)
{
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
image_info->blob=(void *) blob;
image_info->length=length;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e I n f o F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageInfoFile() sets the image info file member.
%
% The format of the SetImageInfoFile method is:
%
% void SetImageInfoFile(ImageInfo *image_info,FILE *file)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o file: the file.
%
*/
MagickExport void SetImageInfoFile(ImageInfo *image_info,FILE *file)
{
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
image_info->file=file;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageMask() associates a mask with the image. The mask must be the same
% dimensions as the image.
%
% The format of the SetImageMask method is:
%
% MagickBooleanType SetImageMask(Image *image,const PixelMask type,
% const Image *mask,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o type: the mask type, ReadPixelMask or WritePixelMask.
%
% o mask: the image mask.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageMask(Image *image,const PixelMask type,
const Image *mask,ExceptionInfo *exception)
{
CacheView
*mask_view,
*image_view;
MagickBooleanType
status;
ssize_t
y;
/*
Set image mask.
*/
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (mask == (const Image *) NULL)
{
switch (type)
{
case WritePixelMask: image->write_mask=MagickFalse; break;
default: image->read_mask=MagickFalse; break;
}
return(SyncImagePixelCache(image,exception));
}
switch (type)
{
case WritePixelMask: image->write_mask=MagickTrue; break;
default: image->read_mask=MagickTrue; break;
}
if (SyncImagePixelCache(image,exception) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
mask_view=AcquireVirtualCacheView(mask,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(mask,image,1,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(mask_view,0,y,mask->columns,1,exception);
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
intensity;
intensity=GetPixelIntensity(mask,p);
switch (type)
{
case WritePixelMask:
{
SetPixelWriteMask(image,ClampToQuantum(QuantumRange-intensity),q);
break;
}
default:
{
SetPixelReadMask(image,ClampToQuantum(QuantumRange-intensity),q);
break;
}
}
p+=GetPixelChannels(mask);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
mask_view=DestroyCacheView(mask_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e A l p h a %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageAlpha() sets the alpha levels of the image.
%
% The format of the SetImageAlpha method is:
%
% MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o Alpha: the level of transparency: 0 is fully opaque and QuantumRange is
% fully transparent.
%
*/
MagickExport MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
image->alpha_trait=BlendPixelTrait;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelReadMask(image,q) != 0)
SetPixelAlpha(image,alpha,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e V i r t u a l P i x e l M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageVirtualPixelMethod() sets the "virtual pixels" method for the
% image 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 SetImageVirtualPixelMethod() method is:
%
% VirtualPixelMethod SetImageVirtualPixelMethod(Image *image,
% const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o virtual_pixel_method: choose the type of virtual pixel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport VirtualPixelMethod SetImageVirtualPixelMethod(Image *image,
const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception)
{
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
return(SetPixelCacheVirtualMethod(image,virtual_pixel_method,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S m u s h I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SmushImages() takes all images from the current image pointer to the end
% of the image list and smushes them to each other top-to-bottom if the
% stack parameter is true, otherwise left-to-right.
%
% The current gravity setting now effects how the image is justified in the
% final image.
%
% The format of the SmushImages method is:
%
% Image *SmushImages(const Image *images,const MagickBooleanType stack,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o stack: A value other than 0 stacks the images top-to-bottom.
%
% o offset: minimum distance in pixels between images.
%
% o exception: return any errors or warnings in this structure.
%
*/
static ssize_t SmushXGap(const Image *smush_image,const Image *images,
const ssize_t offset,ExceptionInfo *exception)
{
CacheView
*left_view,
*right_view;
const Image
*left_image,
*right_image;
RectangleInfo
left_geometry,
right_geometry;
register const Quantum
*p;
register ssize_t
i,
y;
size_t
gap;
ssize_t
x;
if (images->previous == (Image *) NULL)
return(0);
right_image=images;
SetGeometry(smush_image,&right_geometry);
GravityAdjustGeometry(right_image->columns,right_image->rows,
right_image->gravity,&right_geometry);
left_image=images->previous;
SetGeometry(smush_image,&left_geometry);
GravityAdjustGeometry(left_image->columns,left_image->rows,
left_image->gravity,&left_geometry);
gap=right_image->columns;
left_view=AcquireVirtualCacheView(left_image,exception);
right_view=AcquireVirtualCacheView(right_image,exception);
for (y=0; y < (ssize_t) smush_image->rows; y++)
{
for (x=(ssize_t) left_image->columns-1; x > 0; x--)
{
p=GetCacheViewVirtualPixels(left_view,x,left_geometry.y+y,1,1,exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(left_image,p) != TransparentAlpha) ||
((left_image->columns-x-1) >= gap))
break;
}
i=(ssize_t) left_image->columns-x-1;
for (x=0; x < (ssize_t) right_image->columns; x++)
{
p=GetCacheViewVirtualPixels(right_view,x,right_geometry.y+y,1,1,
exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(right_image,p) != TransparentAlpha) ||
((x+i) >= (ssize_t) gap))
break;
}
if ((x+i) < (ssize_t) gap)
gap=(size_t) (x+i);
}
right_view=DestroyCacheView(right_view);
left_view=DestroyCacheView(left_view);
if (y < (ssize_t) smush_image->rows)
return(offset);
return((ssize_t) gap-offset);
}
static ssize_t SmushYGap(const Image *smush_image,const Image *images,
const ssize_t offset,ExceptionInfo *exception)
{
CacheView
*bottom_view,
*top_view;
const Image
*bottom_image,
*top_image;
RectangleInfo
bottom_geometry,
top_geometry;
register const Quantum
*p;
register ssize_t
i,
x;
size_t
gap;
ssize_t
y;
if (images->previous == (Image *) NULL)
return(0);
bottom_image=images;
SetGeometry(smush_image,&bottom_geometry);
GravityAdjustGeometry(bottom_image->columns,bottom_image->rows,
bottom_image->gravity,&bottom_geometry);
top_image=images->previous;
SetGeometry(smush_image,&top_geometry);
GravityAdjustGeometry(top_image->columns,top_image->rows,top_image->gravity,
&top_geometry);
gap=bottom_image->rows;
top_view=AcquireVirtualCacheView(top_image,exception);
bottom_view=AcquireVirtualCacheView(bottom_image,exception);
for (x=0; x < (ssize_t) smush_image->columns; x++)
{
for (y=(ssize_t) top_image->rows-1; y > 0; y--)
{
p=GetCacheViewVirtualPixels(top_view,top_geometry.x+x,y,1,1,exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(top_image,p) != TransparentAlpha) ||
((top_image->rows-y-1) >= gap))
break;
}
i=(ssize_t) top_image->rows-y-1;
for (y=0; y < (ssize_t) bottom_image->rows; y++)
{
p=GetCacheViewVirtualPixels(bottom_view,bottom_geometry.x+x,y,1,1,
exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(bottom_image,p) != TransparentAlpha) ||
((y+i) >= (ssize_t) gap))
break;
}
if ((y+i) < (ssize_t) gap)
gap=(size_t) (y+i);
}
bottom_view=DestroyCacheView(bottom_view);
top_view=DestroyCacheView(top_view);
if (x < (ssize_t) smush_image->columns)
return(offset);
return((ssize_t) gap-offset);
}
MagickExport Image *SmushImages(const Image *images,
const MagickBooleanType stack,const ssize_t offset,ExceptionInfo *exception)
{
#define SmushImageTag "Smush/Image"
const Image
*image;
Image
*smush_image;
MagickBooleanType
proceed,
status;
MagickOffsetType
n;
PixelTrait
alpha_trait;
RectangleInfo
geometry;
register const Image
*next;
size_t
height,
number_images,
width;
ssize_t
x_offset,
y_offset;
/*
Compute maximum area of smushed area.
*/
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=images;
alpha_trait=image->alpha_trait;
number_images=1;
width=image->columns;
height=image->rows;
next=GetNextImageInList(image);
for ( ; next != (Image *) NULL; next=GetNextImageInList(next))
{
if (next->alpha_trait != UndefinedPixelTrait)
alpha_trait=BlendPixelTrait;
number_images++;
if (stack != MagickFalse)
{
if (next->columns > width)
width=next->columns;
height+=next->rows;
if (next->previous != (Image *) NULL)
height+=offset;
continue;
}
width+=next->columns;
if (next->previous != (Image *) NULL)
width+=offset;
if (next->rows > height)
height=next->rows;
}
/*
Smush images.
*/
smush_image=CloneImage(image,width,height,MagickTrue,exception);
if (smush_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(smush_image,DirectClass,exception) == MagickFalse)
{
smush_image=DestroyImage(smush_image);
return((Image *) NULL);
}
smush_image->alpha_trait=alpha_trait;
(void) SetImageBackgroundColor(smush_image,exception);
status=MagickTrue;
x_offset=0;
y_offset=0;
for (n=0; n < (MagickOffsetType) number_images; n++)
{
SetGeometry(smush_image,&geometry);
GravityAdjustGeometry(image->columns,image->rows,image->gravity,&geometry);
if (stack != MagickFalse)
{
x_offset-=geometry.x;
y_offset-=SmushYGap(smush_image,image,offset,exception);
}
else
{
x_offset-=SmushXGap(smush_image,image,offset,exception);
y_offset-=geometry.y;
}
status=CompositeImage(smush_image,image,OverCompositeOp,MagickTrue,x_offset,
y_offset,exception);
proceed=SetImageProgress(image,SmushImageTag,n,number_images);
if (proceed == MagickFalse)
break;
if (stack == MagickFalse)
{
x_offset+=(ssize_t) image->columns;
y_offset=0;
}
else
{
x_offset=0;
y_offset+=(ssize_t) image->rows;
}
image=GetNextImageInList(image);
}
if (stack == MagickFalse)
smush_image->columns=(size_t) x_offset;
else
smush_image->rows=(size_t) y_offset;
if (status == MagickFalse)
smush_image=DestroyImage(smush_image);
return(smush_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t r i p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% StripImage() strips an image of all profiles and comments.
%
% The format of the StripImage method is:
%
% MagickBooleanType StripImage(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 StripImage(Image *image,ExceptionInfo *exception)
{
MagickBooleanType
status;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
(void) exception;
DestroyImageProfiles(image);
(void) DeleteImageProperty(image,"comment");
(void) DeleteImageProperty(image,"date:create");
(void) DeleteImageProperty(image,"date:modify");
status=SetImageArtifact(image,"png:exclude-chunk",
"bKGD,cHRM,EXIF,gAMA,iCCP,iTXt,sRGB,tEXt,zCCP,zTXt,date");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S y n c I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncImage() initializes the red, green, and blue intensities of each pixel
% as defined by the colormap index.
%
% The format of the SyncImage method is:
%
% MagickBooleanType SyncImage(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 inline Quantum PushColormapIndex(Image *image,const Quantum index,
MagickBooleanType *range_exception)
{
if ((size_t) index < image->colors)
return(index);
*range_exception=MagickTrue;
return((Quantum) 0);
}
MagickExport MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
range_exception,
status,
taint;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (image->storage_class == DirectClass)
return(MagickFalse);
range_exception=MagickFalse;
status=MagickTrue;
taint=image->taint;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(range_exception,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
Quantum
index;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
index=PushColormapIndex(image,GetPixelIndex(image,q),&range_exception);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
image->taint=taint;
if ((image->ping == MagickFalse) && (range_exception != MagickFalse))
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageWarning,"InvalidColormapIndex","`%s'",image->filename);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S y n c I m a g e S e t t i n g s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncImageSettings() syncs any image_info global options into per-image
% attributes.
%
% Note: in IMv6 free form 'options' were always mapped into 'artifacts', so
% that operations and coders can find such settings. In IMv7 if a desired
% per-image artifact is not set, then it will directly look for a global
% option as a fallback, as such this copy is no longer needed, only the
% link set up.
%
% The format of the SyncImageSettings method is:
%
% MagickBooleanType SyncImageSettings(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
% MagickBooleanType SyncImagesSettings(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.
%
*/
MagickExport MagickBooleanType SyncImagesSettings(ImageInfo *image_info,
Image *images,ExceptionInfo *exception)
{
Image
*image;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
image=images;
for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
(void) SyncImageSettings(image_info,image,exception);
(void) DeleteImageOption(image_info,"page");
return(MagickTrue);
}
MagickExport MagickBooleanType SyncImageSettings(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
const char
*option;
GeometryInfo
geometry_info;
MagickStatusType
flags;
ResolutionType
units;
/*
Sync image options.
*/
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);
option=GetImageOption(image_info,"alpha-color");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->alpha_color,
exception);
option=GetImageOption(image_info,"background");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->background_color,
exception);
option=GetImageOption(image_info,"black-point-compensation");
if (option != (const char *) NULL)
image->black_point_compensation=(MagickBooleanType) ParseCommandOption(
MagickBooleanOptions,MagickFalse,option);
option=GetImageOption(image_info,"blue-primary");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.blue_primary.x=geometry_info.rho;
image->chromaticity.blue_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.blue_primary.y=image->chromaticity.blue_primary.x;
}
option=GetImageOption(image_info,"bordercolor");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->border_color,
exception);
/* FUTURE: do not sync compose to per-image compose setting here */
option=GetImageOption(image_info,"compose");
if (option != (const char *) NULL)
image->compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions,
MagickFalse,option);
/* -- */
option=GetImageOption(image_info,"compress");
if (option != (const char *) NULL)
image->compression=(CompressionType) ParseCommandOption(
MagickCompressOptions,MagickFalse,option);
option=GetImageOption(image_info,"debug");
if (option != (const char *) NULL)
image->debug=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions,
MagickFalse,option);
option=GetImageOption(image_info,"density");
if (option != (const char *) NULL)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(option,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
}
option=GetImageOption(image_info,"depth");
if (option != (const char *) NULL)
image->depth=StringToUnsignedLong(option);
option=GetImageOption(image_info,"endian");
if (option != (const char *) NULL)
image->endian=(EndianType) ParseCommandOption(MagickEndianOptions,
MagickFalse,option);
option=GetImageOption(image_info,"filter");
if (option != (const char *) NULL)
image->filter=(FilterType) ParseCommandOption(MagickFilterOptions,
MagickFalse,option);
option=GetImageOption(image_info,"fuzz");
if (option != (const char *) NULL)
image->fuzz=StringToDoubleInterval(option,(double) QuantumRange+1.0);
option=GetImageOption(image_info,"gravity");
if (option != (const char *) NULL)
image->gravity=(GravityType) ParseCommandOption(MagickGravityOptions,
MagickFalse,option);
option=GetImageOption(image_info,"green-primary");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.green_primary.x=geometry_info.rho;
image->chromaticity.green_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.green_primary.y=image->chromaticity.green_primary.x;
}
option=GetImageOption(image_info,"intent");
if (option != (const char *) NULL)
image->rendering_intent=(RenderingIntent) ParseCommandOption(
MagickIntentOptions,MagickFalse,option);
option=GetImageOption(image_info,"intensity");
if (option != (const char *) NULL)
image->intensity=(PixelIntensityMethod) ParseCommandOption(
MagickPixelIntensityOptions,MagickFalse,option);
option=GetImageOption(image_info,"interlace");
if (option != (const char *) NULL)
image->interlace=(InterlaceType) ParseCommandOption(MagickInterlaceOptions,
MagickFalse,option);
option=GetImageOption(image_info,"interpolate");
if (option != (const char *) NULL)
image->interpolate=(PixelInterpolateMethod) ParseCommandOption(
MagickInterpolateOptions,MagickFalse,option);
option=GetImageOption(image_info,"loop");
if (option != (const char *) NULL)
image->iterations=StringToUnsignedLong(option);
option=GetImageOption(image_info,"orient");
if (option != (const char *) NULL)
image->orientation=(OrientationType) ParseCommandOption(
MagickOrientationOptions,MagickFalse,option);
option=GetImageOption(image_info,"page");
if (option != (const char *) NULL)
{
char
*geometry;
geometry=GetPageGeometry(option);
flags=ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
}
option=GetImageOption(image_info,"quality");
if (option != (const char *) NULL)
image->quality=StringToUnsignedLong(option);
option=GetImageOption(image_info,"red-primary");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.red_primary.x=geometry_info.rho;
image->chromaticity.red_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.red_primary.y=image->chromaticity.red_primary.x;
}
if (image_info->quality != UndefinedCompressionQuality)
image->quality=image_info->quality;
option=GetImageOption(image_info,"scene");
if (option != (const char *) NULL)
image->scene=StringToUnsignedLong(option);
option=GetImageOption(image_info,"taint");
if (option != (const char *) NULL)
image->taint=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions,
MagickFalse,option);
option=GetImageOption(image_info,"tile-offset");
if (option != (const char *) NULL)
{
char
*geometry;
geometry=GetPageGeometry(option);
flags=ParseAbsoluteGeometry(geometry,&image->tile_offset);
geometry=DestroyString(geometry);
}
option=GetImageOption(image_info,"transparent-color");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->transparent_color,
exception);
option=GetImageOption(image_info,"type");
if (option != (const char *) NULL)
image->type=(ImageType) ParseCommandOption(MagickTypeOptions,MagickFalse,
option);
option=GetImageOption(image_info,"units");
units=image_info->units;
if (option != (const char *) NULL)
units=(ResolutionType) ParseCommandOption(MagickResolutionOptions,
MagickFalse,option);
if (units != UndefinedResolution)
{
if (image->units != units)
switch (image->units)
{
case PixelsPerInchResolution:
{
if (units == PixelsPerCentimeterResolution)
{
image->resolution.x/=2.54;
image->resolution.y/=2.54;
}
break;
}
case PixelsPerCentimeterResolution:
{
if (units == PixelsPerInchResolution)
{
image->resolution.x=(double) ((size_t) (100.0*2.54*
image->resolution.x+0.5))/100.0;
image->resolution.y=(double) ((size_t) (100.0*2.54*
image->resolution.y+0.5))/100.0;
}
break;
}
default:
break;
}
image->units=units;
}
option=GetImageOption(image_info,"virtual-pixel");
if (option != (const char *) NULL)
(void) SetImageVirtualPixelMethod(image,(VirtualPixelMethod)
ParseCommandOption(MagickVirtualPixelOptions,MagickFalse,option),
exception);
option=GetImageOption(image_info,"white-point");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.white_point.x=geometry_info.rho;
image->chromaticity.white_point.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.white_point.y=image->chromaticity.white_point.x;
}
/*
Pointer to allow the lookup of pre-image artifact will fallback to a global
option setting/define. This saves a lot of duplication of global options
into per-image artifacts, while ensuring only specifically set per-image
artifacts are preserved when parenthesis ends.
*/
if (image->image_info != (ImageInfo *) NULL)
image->image_info=DestroyImageInfo(image->image_info);
image->image_info=CloneImageInfo(image_info);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5127_1 |
crossvul-cpp_data_good_2045_0 | /*
* OpenPBS (Portable Batch System) v2.3 Software License
*
* Copyright (c) 1999-2000 Veridian Information Solutions, Inc.
* All rights reserved.
*
* ---------------------------------------------------------------------------
* For a license to use or redistribute the OpenPBS software under conditions
* other than those described below, or to purchase support for this software,
* please contact Veridian Systems, PBS Products Department ("Licensor") at:
*
* www.OpenPBS.org +1 650 967-4675 sales@OpenPBS.org
* 877 902-4PBS (US toll-free)
* ---------------------------------------------------------------------------
*
* This license covers use of the OpenPBS v2.3 software (the "Software") at
* your site or location, and, for certain users, redistribution of the
* Software to other sites and locations. Use and redistribution of
* OpenPBS v2.3 in source and binary forms, with or without modification,
* are permitted provided that all of the following conditions are met.
* After December 31, 2001, only conditions 3-6 must be met:
*
* 1. Commercial and/or non-commercial use of the Software is permitted
* provided a current software registration is on file at www.OpenPBS.org.
* If use of this software contributes to a publication, product, or
* service, proper attribution must be given; see www.OpenPBS.org/credit.html
*
* 2. Redistribution in any form is only permitted for non-commercial,
* non-profit purposes. There can be no charge for the Software or any
* software incorporating the Software. Further, there can be no
* expectation of revenue generated as a consequence of redistributing
* the Software.
*
* 3. Any Redistribution of source code must retain the above copyright notice
* and the acknowledgment contained in paragraph 6, this list of conditions
* and the disclaimer contained in paragraph 7.
*
* 4. Any Redistribution in binary form must reproduce the above copyright
* notice and the acknowledgment contained in paragraph 6, this list of
* conditions and the disclaimer contained in paragraph 7 in the
* documentation and/or other materials provided with the distribution.
*
* 5. Redistributions in any form must be accompanied by information on how to
* obtain complete source code for the OpenPBS software and any
* modifications and/or additions to the OpenPBS software. The source code
* must either be included in the distribution or be available for no more
* than the cost of distribution plus a nominal fee, and all modifications
* and additions to the Software must be freely redistributable by any party
* (including Licensor) without restriction.
*
* 6. All advertising materials mentioning features or use of the Software must
* display the following acknowledgment:
*
* "This product includes software developed by NASA Ames Research Center,
* Lawrence Livermore National Laboratory, and Veridian Information
* Solutions, Inc.
* Visit www.OpenPBS.org for OpenPBS software support,
* products, and information."
*
* 7. DISCLAIMER OF WARRANTY
*
* THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT
* ARE EXPRESSLY DISCLAIMED.
*
* IN NO EVENT SHALL VERIDIAN CORPORATION, ITS AFFILIATED COMPANIES, OR THE
* U.S. GOVERNMENT OR ANY OF ITS AGENCIES BE LIABLE FOR ANY DIRECT OR INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This license will be governed by the laws of the Commonwealth of Virginia,
* without reference to its choice of law rules.
*/
#include <pbs_config.h> /* the master config generated by configure */
#include <assert.h>
#include <stddef.h>
#include "dis.h"
#include "dis_.h"
int disrsi_(
int stream,
int *negate,
unsigned *value,
unsigned count)
{
int c;
unsigned locval;
unsigned ndigs;
char *cp;
char scratch[DIS_BUFSIZ+1];
assert(negate != NULL);
assert(value != NULL);
assert(count);
assert(stream >= 0);
assert(dis_getc != NULL);
assert(dis_gets != NULL);
memset(scratch, 0, DIS_BUFSIZ+1);
if (dis_umaxd == 0)
disiui_();
if (count >= dis_umaxd)
{
if (count > dis_umaxd)
goto overflow;
if (memcmp(scratch, dis_umax, dis_umaxd) > 0)
goto overflow;
}
switch (c = (*dis_getc)(stream))
{
case '-':
case '+':
*negate = c == '-';
if ((*dis_gets)(stream, scratch, count) != (int)count)
{
return(DIS_EOD);
}
if (count >= dis_umaxd)
{
if (count > dis_umaxd)
goto overflow;
if (memcmp(scratch, dis_umax, dis_umaxd) > 0)
goto overflow;
}
cp = scratch;
locval = 0;
do
{
if (((c = *cp++) < '0') || (c > '9'))
{
return(DIS_NONDIGIT);
}
locval = 10 * locval + c - '0';
}
while (--count);
*value = locval;
return (DIS_SUCCESS);
break;
case '0':
return (DIS_LEADZRO);
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
ndigs = c - '0';
if (count > 1)
{
if ((*dis_gets)(stream, scratch + 1, count - 1) != (int)count - 1)
{
return(DIS_EOD);
}
cp = scratch;
if (count >= dis_umaxd)
{
if (count > dis_umaxd)
break;
*cp = c;
if (memcmp(scratch, dis_umax, dis_umaxd) > 0)
break;
}
while (--count)
{
if (((c = *++cp) < '0') || (c > '9'))
{
return(DIS_NONDIGIT);
}
ndigs = 10 * ndigs + c - '0';
}
} /* END if (count > 1) */
return(disrsi_(stream, negate, value, ndigs));
/*NOTREACHED*/
break;
case - 1:
return(DIS_EOD);
/*NOTREACHED*/
break;
case -2:
return(DIS_EOF);
/*NOTREACHED*/
break;
default:
return(DIS_NONDIGIT);
/*NOTREACHED*/
break;
}
*negate = FALSE;
overflow:
*value = UINT_MAX;
return(DIS_OVERFLOW);
} /* END disrsi_() */
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2045_0 |
crossvul-cpp_data_good_3413_0 | /*
* XPM image format
*
* Copyright (c) 2012 Paul B Mahol
* Copyright (c) 2017 Paras Chadha
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/parseutils.h"
#include "libavutil/avstring.h"
#include "avcodec.h"
#include "internal.h"
typedef struct XPMContext {
uint32_t *pixels;
int pixels_size;
uint8_t *buf;
int buf_size;
} XPMDecContext;
typedef struct ColorEntry {
const char *name; ///< a string representing the name of the color
uint32_t rgb_color; ///< RGB values for the color
} ColorEntry;
static int color_table_compare(const void *lhs, const void *rhs)
{
return av_strcasecmp(lhs, ((const ColorEntry *)rhs)->name);
}
static const ColorEntry color_table[] = {
{ "AliceBlue", 0xFFF0F8FF },
{ "AntiqueWhite", 0xFFFAEBD7 },
{ "Aqua", 0xFF00FFFF },
{ "Aquamarine", 0xFF7FFFD4 },
{ "Azure", 0xFFF0FFFF },
{ "Beige", 0xFFF5F5DC },
{ "Bisque", 0xFFFFE4C4 },
{ "Black", 0xFF000000 },
{ "BlanchedAlmond", 0xFFFFEBCD },
{ "Blue", 0xFF0000FF },
{ "BlueViolet", 0xFF8A2BE2 },
{ "Brown", 0xFFA52A2A },
{ "BurlyWood", 0xFFDEB887 },
{ "CadetBlue", 0xFF5F9EA0 },
{ "Chartreuse", 0xFF7FFF00 },
{ "Chocolate", 0xFFD2691E },
{ "Coral", 0xFFFF7F50 },
{ "CornflowerBlue", 0xFF6495ED },
{ "Cornsilk", 0xFFFFF8DC },
{ "Crimson", 0xFFDC143C },
{ "Cyan", 0xFF00FFFF },
{ "DarkBlue", 0xFF00008B },
{ "DarkCyan", 0xFF008B8B },
{ "DarkGoldenRod", 0xFFB8860B },
{ "DarkGray", 0xFFA9A9A9 },
{ "DarkGreen", 0xFF006400 },
{ "DarkKhaki", 0xFFBDB76B },
{ "DarkMagenta", 0xFF8B008B },
{ "DarkOliveGreen", 0xFF556B2F },
{ "Darkorange", 0xFFFF8C00 },
{ "DarkOrchid", 0xFF9932CC },
{ "DarkRed", 0xFF8B0000 },
{ "DarkSalmon", 0xFFE9967A },
{ "DarkSeaGreen", 0xFF8FBC8F },
{ "DarkSlateBlue", 0xFF483D8B },
{ "DarkSlateGray", 0xFF2F4F4F },
{ "DarkTurquoise", 0xFF00CED1 },
{ "DarkViolet", 0xFF9400D3 },
{ "DeepPink", 0xFFFF1493 },
{ "DeepSkyBlue", 0xFF00BFFF },
{ "DimGray", 0xFF696969 },
{ "DodgerBlue", 0xFF1E90FF },
{ "FireBrick", 0xFFB22222 },
{ "FloralWhite", 0xFFFFFAF0 },
{ "ForestGreen", 0xFF228B22 },
{ "Fuchsia", 0xFFFF00FF },
{ "Gainsboro", 0xFFDCDCDC },
{ "GhostWhite", 0xFFF8F8FF },
{ "Gold", 0xFFFFD700 },
{ "GoldenRod", 0xFFDAA520 },
{ "Gray", 0xFFBEBEBE },
{ "Green", 0xFF00FF00 },
{ "GreenYellow", 0xFFADFF2F },
{ "HoneyDew", 0xFFF0FFF0 },
{ "HotPink", 0xFFFF69B4 },
{ "IndianRed", 0xFFCD5C5C },
{ "Indigo", 0xFF4B0082 },
{ "Ivory", 0xFFFFFFF0 },
{ "Khaki", 0xFFF0E68C },
{ "Lavender", 0xFFE6E6FA },
{ "LavenderBlush", 0xFFFFF0F5 },
{ "LawnGreen", 0xFF7CFC00 },
{ "LemonChiffon", 0xFFFFFACD },
{ "LightBlue", 0xFFADD8E6 },
{ "LightCoral", 0xFFF08080 },
{ "LightCyan", 0xFFE0FFFF },
{ "LightGoldenRodYellow", 0xFFFAFAD2 },
{ "LightGreen", 0xFF90EE90 },
{ "LightGrey", 0xFFD3D3D3 },
{ "LightPink", 0xFFFFB6C1 },
{ "LightSalmon", 0xFFFFA07A },
{ "LightSeaGreen", 0xFF20B2AA },
{ "LightSkyBlue", 0xFF87CEFA },
{ "LightSlateGray", 0xFF778899 },
{ "LightSteelBlue", 0xFFB0C4DE },
{ "LightYellow", 0xFFFFFFE0 },
{ "Lime", 0xFF00FF00 },
{ "LimeGreen", 0xFF32CD32 },
{ "Linen", 0xFFFAF0E6 },
{ "Magenta", 0xFFFF00FF },
{ "Maroon", 0xFFB03060 },
{ "MediumAquaMarine", 0xFF66CDAA },
{ "MediumBlue", 0xFF0000CD },
{ "MediumOrchid", 0xFFBA55D3 },
{ "MediumPurple", 0xFF9370D8 },
{ "MediumSeaGreen", 0xFF3CB371 },
{ "MediumSlateBlue", 0xFF7B68EE },
{ "MediumSpringGreen", 0xFF00FA9A },
{ "MediumTurquoise", 0xFF48D1CC },
{ "MediumVioletRed", 0xFFC71585 },
{ "MidnightBlue", 0xFF191970 },
{ "MintCream", 0xFFF5FFFA },
{ "MistyRose", 0xFFFFE4E1 },
{ "Moccasin", 0xFFFFE4B5 },
{ "NavajoWhite", 0xFFFFDEAD },
{ "Navy", 0xFF000080 },
{ "None", 0x00000000 },
{ "OldLace", 0xFFFDF5E6 },
{ "Olive", 0xFF808000 },
{ "OliveDrab", 0xFF6B8E23 },
{ "Orange", 0xFFFFA500 },
{ "OrangeRed", 0xFFFF4500 },
{ "Orchid", 0xFFDA70D6 },
{ "PaleGoldenRod", 0xFFEEE8AA },
{ "PaleGreen", 0xFF98FB98 },
{ "PaleTurquoise", 0xFFAFEEEE },
{ "PaleVioletRed", 0xFFD87093 },
{ "PapayaWhip", 0xFFFFEFD5 },
{ "PeachPuff", 0xFFFFDAB9 },
{ "Peru", 0xFFCD853F },
{ "Pink", 0xFFFFC0CB },
{ "Plum", 0xFFDDA0DD },
{ "PowderBlue", 0xFFB0E0E6 },
{ "Purple", 0xFFA020F0 },
{ "Red", 0xFFFF0000 },
{ "RosyBrown", 0xFFBC8F8F },
{ "RoyalBlue", 0xFF4169E1 },
{ "SaddleBrown", 0xFF8B4513 },
{ "Salmon", 0xFFFA8072 },
{ "SandyBrown", 0xFFF4A460 },
{ "SeaGreen", 0xFF2E8B57 },
{ "SeaShell", 0xFFFFF5EE },
{ "Sienna", 0xFFA0522D },
{ "Silver", 0xFFC0C0C0 },
{ "SkyBlue", 0xFF87CEEB },
{ "SlateBlue", 0xFF6A5ACD },
{ "SlateGray", 0xFF708090 },
{ "Snow", 0xFFFFFAFA },
{ "SpringGreen", 0xFF00FF7F },
{ "SteelBlue", 0xFF4682B4 },
{ "Tan", 0xFFD2B48C },
{ "Teal", 0xFF008080 },
{ "Thistle", 0xFFD8BFD8 },
{ "Tomato", 0xFFFF6347 },
{ "Turquoise", 0xFF40E0D0 },
{ "Violet", 0xFFEE82EE },
{ "Wheat", 0xFFF5DEB3 },
{ "White", 0xFFFFFFFF },
{ "WhiteSmoke", 0xFFF5F5F5 },
{ "Yellow", 0xFFFFFF00 },
{ "YellowGreen", 0xFF9ACD32 }
};
static unsigned hex_char_to_number(uint8_t x)
{
if (x >= 'a' && x <= 'f')
x -= 'a' - 10;
else if (x >= 'A' && x <= 'F')
x -= 'A' - 10;
else if (x >= '0' && x <= '9')
x -= '0';
else
x = 0;
return x;
}
/*
* Function same as strcspn but ignores characters if they are inside a C style comments
*/
static size_t mod_strcspn(const char *string, const char *reject)
{
int i, j;
for (i = 0; string && string[i]; i++) {
if (string[i] == '/' && string[i+1] == '*') {
i += 2;
while ( string && string[i] && (string[i] != '*' || string[i+1] != '/') )
i++;
i++;
} else if (string[i] == '/' && string[i+1] == '/') {
i += 2;
while ( string && string[i] && string[i] != '\n' )
i++;
} else {
for (j = 0; reject && reject[j]; j++) {
if (string[i] == reject[j])
break;
}
if (reject && reject[j])
break;
}
}
return i;
}
static uint32_t color_string_to_rgba(const char *p, int len)
{
uint32_t ret = 0xFF000000;
const ColorEntry *entry;
char color_name[100];
len = FFMIN(FFMAX(len, 0), sizeof(color_name) - 1);
if (*p == '#') {
p++;
len--;
if (len == 3) {
ret |= (hex_char_to_number(p[2]) << 4) |
(hex_char_to_number(p[1]) << 12) |
(hex_char_to_number(p[0]) << 20);
} else if (len == 4) {
ret = (hex_char_to_number(p[3]) << 4) |
(hex_char_to_number(p[2]) << 12) |
(hex_char_to_number(p[1]) << 20) |
(hex_char_to_number(p[0]) << 28);
} else if (len == 6) {
ret |= hex_char_to_number(p[5]) |
(hex_char_to_number(p[4]) << 4) |
(hex_char_to_number(p[3]) << 8) |
(hex_char_to_number(p[2]) << 12) |
(hex_char_to_number(p[1]) << 16) |
(hex_char_to_number(p[0]) << 20);
} else if (len == 8) {
ret = hex_char_to_number(p[7]) |
(hex_char_to_number(p[6]) << 4) |
(hex_char_to_number(p[5]) << 8) |
(hex_char_to_number(p[4]) << 12) |
(hex_char_to_number(p[3]) << 16) |
(hex_char_to_number(p[2]) << 20) |
(hex_char_to_number(p[1]) << 24) |
(hex_char_to_number(p[0]) << 28);
}
} else {
strncpy(color_name, p, len);
color_name[len] = '\0';
entry = bsearch(color_name,
color_table,
FF_ARRAY_ELEMS(color_table),
sizeof(ColorEntry),
color_table_compare);
if (!entry)
return ret;
ret = entry->rgb_color;
}
return ret;
}
static int ascii2index(const uint8_t *cpixel, int cpp)
{
const uint8_t *p = cpixel;
int n = 0, m = 1, i;
for (i = 0; i < cpp; i++) {
if (*p < ' ' || *p > '~')
return AVERROR_INVALIDDATA;
n += (*p++ - ' ') * m;
m *= 95;
}
return n;
}
static int xpm_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame, AVPacket *avpkt)
{
XPMDecContext *x = avctx->priv_data;
AVFrame *p=data;
const uint8_t *end, *ptr;
int ncolors, cpp, ret, i, j;
int64_t size;
uint32_t *dst;
avctx->pix_fmt = AV_PIX_FMT_BGRA;
av_fast_padded_malloc(&x->buf, &x->buf_size, avpkt->size);
if (!x->buf)
return AVERROR(ENOMEM);
memcpy(x->buf, avpkt->data, avpkt->size);
x->buf[avpkt->size] = 0;
ptr = x->buf;
end = x->buf + avpkt->size;
while (end - ptr > 9 && memcmp(ptr, "/* XPM */", 9))
ptr++;
if (end - ptr <= 9) {
av_log(avctx, AV_LOG_ERROR, "missing signature\n");
return AVERROR_INVALIDDATA;
}
ptr += mod_strcspn(ptr, "\"");
if (sscanf(ptr, "\"%u %u %u %u\",",
&avctx->width, &avctx->height, &ncolors, &cpp) != 4) {
av_log(avctx, AV_LOG_ERROR, "missing image parameters\n");
return AVERROR_INVALIDDATA;
}
if ((ret = ff_set_dimensions(avctx, avctx->width, avctx->height)) < 0)
return ret;
if ((ret = ff_get_buffer(avctx, p, 0)) < 0)
return ret;
if (cpp <= 0 || cpp >= 5) {
av_log(avctx, AV_LOG_ERROR, "unsupported/invalid number of chars per pixel: %d\n", cpp);
return AVERROR_INVALIDDATA;
}
size = 1;
for (i = 0; i < cpp; i++)
size *= 95;
if (ncolors <= 0 || ncolors > size) {
av_log(avctx, AV_LOG_ERROR, "invalid number of colors: %d\n", ncolors);
return AVERROR_INVALIDDATA;
}
size *= 4;
av_fast_padded_malloc(&x->pixels, &x->pixels_size, size);
if (!x->pixels)
return AVERROR(ENOMEM);
ptr += mod_strcspn(ptr, ",") + 1;
if (end - ptr < 1)
return AVERROR_INVALIDDATA;
for (i = 0; i < ncolors; i++) {
const uint8_t *index;
int len;
ptr += mod_strcspn(ptr, "\"") + 1;
if (end - ptr < cpp)
return AVERROR_INVALIDDATA;
index = ptr;
ptr += cpp;
ptr = strstr(ptr, "c ");
if (ptr) {
ptr += 2;
} else {
return AVERROR_INVALIDDATA;
}
len = strcspn(ptr, "\" ");
if ((ret = ascii2index(index, cpp)) < 0)
return ret;
x->pixels[ret] = color_string_to_rgba(ptr, len);
ptr += mod_strcspn(ptr, ",") + 1;
if (end - ptr < 1)
return AVERROR_INVALIDDATA;
}
for (i = 0; i < avctx->height; i++) {
dst = (uint32_t *)(p->data[0] + i * p->linesize[0]);
if (end - ptr < 1)
return AVERROR_INVALIDDATA;
ptr += mod_strcspn(ptr, "\"") + 1;
if (end - ptr < 1)
return AVERROR_INVALIDDATA;
for (j = 0; j < avctx->width; j++) {
if (end - ptr < cpp)
return AVERROR_INVALIDDATA;
if ((ret = ascii2index(ptr, cpp)) < 0)
return ret;
*dst++ = x->pixels[ret];
ptr += cpp;
}
ptr += mod_strcspn(ptr, ",") + 1;
}
p->key_frame = 1;
p->pict_type = AV_PICTURE_TYPE_I;
*got_frame = 1;
return avpkt->size;
}
static av_cold int xpm_decode_close(AVCodecContext *avctx)
{
XPMDecContext *x = avctx->priv_data;
av_freep(&x->pixels);
av_freep(&x->buf);
x->buf_size = 0;
return 0;
}
AVCodec ff_xpm_decoder = {
.name = "xpm",
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_XPM,
.priv_data_size = sizeof(XPMDecContext),
.close = xpm_decode_close,
.decode = xpm_decode_frame,
.capabilities = AV_CODEC_CAP_DR1,
.long_name = NULL_IF_CONFIG_SMALL("XPM (X PixMap) image")
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3413_0 |
crossvul-cpp_data_bad_1063_0 | /*
* asn1.c: ASN.1 decoding functions (DER)
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <assert.h>
#include <ctype.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "internal.h"
#include "asn1.h"
static int asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1,
const u8 *in, size_t len, const u8 **newp, size_t *len_left,
int choice, int depth);
static int asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1,
u8 **ptr, size_t *size, int depth);
static int asn1_write_element(sc_context_t *ctx, unsigned int tag,
const u8 * data, size_t datalen, u8 ** out, size_t * outlen);
static const char *tag2str(unsigned int tag)
{
static const char *tags[] = {
"EOC", "BOOLEAN", "INTEGER", "BIT STRING", "OCTET STRING", /* 0-4 */
"NULL", "OBJECT IDENTIFIER", "OBJECT DESCRIPTOR", "EXTERNAL", "REAL", /* 5-9 */
"ENUMERATED", "Universal 11", "UTF8String", "Universal 13", /* 10-13 */
"Universal 14", "Universal 15", "SEQUENCE", "SET", /* 15-17 */
"NumericString", "PrintableString", "T61String", /* 18-20 */
"VideotexString", "IA5String", "UTCTIME", "GENERALIZEDTIME", /* 21-24 */
"GraphicString", "VisibleString", "GeneralString", /* 25-27 */
"UniversalString", "Universal 29", "BMPString" /* 28-30 */
};
if (tag > 30)
return "(unknown)";
return tags[tag];
}
int sc_asn1_read_tag(const u8 ** buf, size_t buflen, unsigned int *cla_out,
unsigned int *tag_out, size_t *taglen)
{
const u8 *p = *buf;
size_t left = buflen, len;
unsigned int cla, tag, i;
*buf = NULL;
if (left == 0)
return SC_ERROR_INVALID_ASN1_OBJECT;
if (*p == 0xff || *p == 0) {
/* end of data reached */
*taglen = 0;
*tag_out = SC_ASN1_TAG_EOC;
return SC_SUCCESS;
}
/* parse tag byte(s)
* Resulted tag is presented by integer that has not to be
* confused with the 'tag number' part of ASN.1 tag.
*/
cla = (*p & SC_ASN1_TAG_CLASS) | (*p & SC_ASN1_TAG_CONSTRUCTED);
tag = *p & SC_ASN1_TAG_PRIMITIVE;
p++;
left--;
if (tag == SC_ASN1_TAG_PRIMITIVE) {
/* high tag number */
size_t n = SC_ASN1_TAGNUM_SIZE - 1;
/* search the last tag octet */
do {
if (left == 0 || n == 0)
/* either an invalid tag or it doesn't fit in
* unsigned int */
return SC_ERROR_INVALID_ASN1_OBJECT;
tag <<= 8;
tag |= *p;
p++;
left--;
n--;
} while (tag & 0x80);
}
/* parse length byte(s) */
if (left == 0)
return SC_ERROR_INVALID_ASN1_OBJECT;
len = *p;
p++;
left--;
if (len & 0x80) {
len &= 0x7f;
unsigned int a = 0;
if (len > sizeof a || len > left)
return SC_ERROR_INVALID_ASN1_OBJECT;
for (i = 0; i < len; i++) {
a <<= 8;
a |= *p;
p++;
left--;
}
len = a;
}
*cla_out = cla;
*tag_out = tag;
*taglen = len;
*buf = p;
if (len > left)
return SC_ERROR_ASN1_END_OF_CONTENTS;
return SC_SUCCESS;
}
void sc_format_asn1_entry(struct sc_asn1_entry *entry, void *parm, void *arg,
int set_present)
{
entry->parm = parm;
entry->arg = arg;
if (set_present)
entry->flags |= SC_ASN1_PRESENT;
}
void sc_copy_asn1_entry(const struct sc_asn1_entry *src,
struct sc_asn1_entry *dest)
{
while (src->name != NULL) {
*dest = *src;
dest++;
src++;
}
dest->name = NULL;
}
static void print_indent(size_t depth)
{
for (; depth > 0; depth--) {
putchar(' ');
}
}
static void print_hex(const u8 * buf, size_t buflen, size_t depth)
{
size_t lines_len = buflen * 5 + 128;
char *lines = malloc(lines_len);
char *line = lines;
if (buf == NULL || buflen == 0 || lines == NULL) {
free(lines);
return;
}
sc_hex_dump(buf, buflen, lines, lines_len);
while (*line != '\0') {
char *line_end = strchr(line, '\n');
ptrdiff_t width = line_end - line;
if (!line_end || width <= 1) {
/* don't print empty lines */
break;
}
if (buflen > 8) {
putchar('\n');
print_indent(depth);
} else {
printf(": ");
}
printf("%.*s", (int) width, line);
line = line_end + 1;
}
free(lines);
}
static void print_ascii(const u8 * buf, size_t buflen)
{
for (; 0 < buflen; buflen--, buf++) {
if (isprint(*buf))
printf("%c", *buf);
else
putchar('.');
}
}
static void sc_asn1_print_octet_string(const u8 * buf, size_t buflen, size_t depth)
{
print_hex(buf, buflen, depth);
}
static void sc_asn1_print_utf8string(const u8 * buf, size_t buflen)
{
/* FIXME UTF-8 is not ASCII */
print_ascii(buf, buflen);
}
static void sc_asn1_print_integer(const u8 * buf, size_t buflen)
{
size_t a = 0;
if (buflen > sizeof(a)) {
printf("0x%s", sc_dump_hex(buf, buflen));
} else {
size_t i;
for (i = 0; i < buflen; i++) {
a <<= 8;
a |= buf[i];
}
printf("%"SC_FORMAT_LEN_SIZE_T"u", a);
}
}
static void sc_asn1_print_boolean(const u8 * buf, size_t buflen)
{
if (!buflen)
return;
if (buf[0])
printf("true");
else
printf("false");
}
static void sc_asn1_print_bit_string(const u8 * buf, size_t buflen, size_t depth)
{
#ifndef _WIN32
long long a = 0;
#else
__int64 a = 0;
#endif
int r, i;
if (buflen > sizeof(a) + 1) {
print_hex(buf, buflen, depth);
} else {
r = sc_asn1_decode_bit_string(buf, buflen, &a, sizeof(a));
if (r < 0) {
printf("decode error");
return;
}
for (i = r - 1; i >= 0; i--) {
printf("%c", ((a >> i) & 1) ? '1' : '0');
}
}
}
#ifdef ENABLE_OPENSSL
#include <openssl/objects.h>
static void openssl_print_object_sn(const char *s)
{
ASN1_OBJECT *obj = OBJ_txt2obj(s, 0);
if (obj) {
int nid = OBJ_obj2nid(obj);
if (nid != NID_undef) {
printf(", %s", OBJ_nid2sn(nid));
}
ASN1_OBJECT_free(obj);
}
}
#else
static void openssl_print_object_sn(const char *s)
{
}
#endif
static void sc_asn1_print_object_id(const u8 * buf, size_t buflen)
{
struct sc_object_id oid;
const char *sbuf;
if (sc_asn1_decode_object_id(buf, buflen, &oid)) {
printf("decode error");
return;
}
sbuf = sc_dump_oid(&oid);
printf(" %s", sbuf);
openssl_print_object_sn(sbuf);
}
static void sc_asn1_print_utctime(const u8 * buf, size_t buflen)
{
if (buflen < 8) {
printf("Error in decoding.\n");
return;
}
print_ascii(buf, 2); /* YY */
putchar('-');
print_ascii(buf+2, 2); /* MM */
putchar('-');
print_ascii(buf+4, 2); /* DD */
putchar(' ');
print_ascii(buf+6, 2); /* hh */
buf += 8;
buflen -= 8;
if (buflen >= 2 && isdigit(buf[0]) && isdigit(buf[1])) {
putchar(':');
print_ascii(buf, 2); /* mm */
buf += 2;
buflen -= 2;
}
if (buflen >= 2 && isdigit(buf[0]) && isdigit(buf[1])) {
putchar(':');
print_ascii(buf, 2); /* ss */
buf += 2;
buflen -= 2;
}
if (buflen >= 4 && '.' == buf[0]) {
print_ascii(buf, 4); /* fff */
buf += 4;
buflen -= 4;
}
if (buflen >= 1 && 'Z' == buf[0]) {
printf(" UTC");
} else if (buflen >= 5 && ('-' == buf[0] || '+' == buf[0])) {
putchar(' ');
print_ascii(buf, 3); /* +/-hh */
putchar(':');
print_ascii(buf+3, 2); /* mm */
}
}
static void sc_asn1_print_generalizedtime(const u8 * buf, size_t buflen)
{
if (buflen < 8) {
printf("Error in decoding.\n");
return;
}
print_ascii(buf, 2);
sc_asn1_print_utctime(buf + 2, buflen - 2);
}
static void print_tags_recursive(const u8 * buf0, const u8 * buf,
size_t buflen, size_t depth)
{
int r;
size_t i;
size_t bytesleft = buflen;
const char *classes[4] = {
"Universal",
"Application",
"Context",
"Private"
};
const u8 *p = buf;
while (bytesleft >= 2) {
unsigned int cla = 0, tag = 0, hlen;
const u8 *tagp = p;
size_t len;
r = sc_asn1_read_tag(&tagp, bytesleft, &cla, &tag, &len);
if (r != SC_SUCCESS || tagp == NULL) {
printf("Error in decoding.\n");
return;
}
hlen = tagp - p;
if (cla == 0 && tag == 0) {
printf("Zero tag, finishing\n");
break;
}
print_indent(depth);
/* let i be the length of the tag in bytes */
for (i = 1; i < sizeof tag - 1; i++) {
if (!(tag >> 8*i))
break;
}
printf("%02X", cla<<(i-1)*8 | tag);
if ((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_UNIVERSAL) {
printf(" %s", tag2str(tag));
} else {
printf(" %s %-2u",
classes[cla >> 6],
i == 1 ? tag & SC_ASN1_TAG_PRIMITIVE : tag & (((unsigned int) ~0) >> (i-1)*8));
}
if (!((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_UNIVERSAL
&& tag == SC_ASN1_TAG_NULL && len == 0)) {
printf(" (%"SC_FORMAT_LEN_SIZE_T"u byte%s)",
len,
len != 1 ? "s" : "");
}
if (len + hlen > bytesleft) {
printf(" Illegal length!\n");
return;
}
p += hlen + len;
bytesleft -= hlen + len;
if (cla & SC_ASN1_TAG_CONSTRUCTED) {
putchar('\n');
print_tags_recursive(buf0, tagp, len, depth + 2*i + 1);
continue;
}
switch (tag) {
case SC_ASN1_TAG_BIT_STRING:
printf(": ");
sc_asn1_print_bit_string(tagp, len, depth + 2*i + 1);
break;
case SC_ASN1_TAG_OCTET_STRING:
sc_asn1_print_octet_string(tagp, len, depth + 2*i + 1);
break;
case SC_ASN1_TAG_OBJECT:
printf(": ");
sc_asn1_print_object_id(tagp, len);
break;
case SC_ASN1_TAG_INTEGER:
case SC_ASN1_TAG_ENUMERATED:
printf(": ");
sc_asn1_print_integer(tagp, len);
break;
case SC_ASN1_TAG_IA5STRING:
case SC_ASN1_TAG_PRINTABLESTRING:
case SC_ASN1_TAG_T61STRING:
case SC_ASN1_TAG_UTF8STRING:
printf(": ");
sc_asn1_print_utf8string(tagp, len);
break;
case SC_ASN1_TAG_BOOLEAN:
printf(": ");
sc_asn1_print_boolean(tagp, len);
break;
case SC_ASN1_GENERALIZEDTIME:
printf(": ");
sc_asn1_print_generalizedtime(tagp, len);
break;
case SC_ASN1_UTCTIME:
printf(": ");
sc_asn1_print_utctime(tagp, len);
break;
}
if ((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_APPLICATION) {
print_hex(tagp, len, depth + 2*i + 1);
}
if ((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_CONTEXT) {
print_hex(tagp, len, depth + 2*i + 1);
}
putchar('\n');
}
}
void sc_asn1_print_tags(const u8 * buf, size_t buflen)
{
print_tags_recursive(buf, buf, buflen, 0);
}
const u8 *sc_asn1_find_tag(sc_context_t *ctx, const u8 * buf,
size_t buflen, unsigned int tag_in, size_t *taglen_in)
{
size_t left = buflen, taglen;
const u8 *p = buf;
*taglen_in = 0;
while (left >= 2) {
unsigned int cla = 0, tag, mask = 0xff00;
buf = p;
/* read a tag */
if (sc_asn1_read_tag(&p, left, &cla, &tag, &taglen) != SC_SUCCESS
|| p == NULL)
return NULL;
left -= (p - buf);
/* we need to shift the class byte to the leftmost
* byte of the tag */
while ((tag & mask) != 0) {
cla <<= 8;
mask <<= 8;
}
/* compare the read tag with the given tag */
if ((tag | cla) == tag_in) {
/* we have a match => return length and value part */
if (taglen > left)
return NULL;
*taglen_in = taglen;
return p;
}
/* otherwise continue reading tags */
left -= taglen;
p += taglen;
}
return NULL;
}
const u8 *sc_asn1_skip_tag(sc_context_t *ctx, const u8 ** buf, size_t *buflen,
unsigned int tag_in, size_t *taglen_out)
{
const u8 *p = *buf;
size_t len = *buflen, taglen;
unsigned int cla = 0, tag;
if (sc_asn1_read_tag((const u8 **) &p, len, &cla, &tag, &taglen) != SC_SUCCESS
|| p == NULL)
return NULL;
switch (cla & 0xC0) {
case SC_ASN1_TAG_UNIVERSAL:
if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_UNI)
return NULL;
break;
case SC_ASN1_TAG_APPLICATION:
if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_APP)
return NULL;
break;
case SC_ASN1_TAG_CONTEXT:
if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_CTX)
return NULL;
break;
case SC_ASN1_TAG_PRIVATE:
if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_PRV)
return NULL;
break;
}
if (cla & SC_ASN1_TAG_CONSTRUCTED) {
if ((tag_in & SC_ASN1_CONS) == 0)
return NULL;
} else
if (tag_in & SC_ASN1_CONS)
return NULL;
if ((tag_in & SC_ASN1_TAG_MASK) != tag)
return NULL;
len -= (p - *buf); /* header size */
if (taglen > len) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"too long ASN.1 object (size %"SC_FORMAT_LEN_SIZE_T"u while only %"SC_FORMAT_LEN_SIZE_T"u available)\n",
taglen, len);
return NULL;
}
*buflen -= (p - *buf) + taglen;
*buf = p + taglen; /* point to next tag */
*taglen_out = taglen;
return p;
}
const u8 *sc_asn1_verify_tag(sc_context_t *ctx, const u8 * buf, size_t buflen,
unsigned int tag_in, size_t *taglen_out)
{
return sc_asn1_skip_tag(ctx, &buf, &buflen, tag_in, taglen_out);
}
static int decode_bit_string(const u8 * inbuf, size_t inlen, void *outbuf,
size_t outlen, int invert)
{
const u8 *in = inbuf;
u8 *out = (u8 *) outbuf;
int zero_bits = *in & 0x07;
size_t octets_left = inlen - 1;
int i, count = 0;
memset(outbuf, 0, outlen);
in++;
if (outlen < octets_left)
return SC_ERROR_BUFFER_TOO_SMALL;
if (inlen < 1)
return SC_ERROR_INVALID_ASN1_OBJECT;
while (octets_left) {
/* 1st octet of input: ABCDEFGH, where A is the MSB */
/* 1st octet of output: HGFEDCBA, where A is the LSB */
/* first bit in bit string is the LSB in first resulting octet */
int bits_to_go;
*out = 0;
if (octets_left == 1)
bits_to_go = 8 - zero_bits;
else
bits_to_go = 8;
if (invert)
for (i = 0; i < bits_to_go; i++) {
*out |= ((*in >> (7 - i)) & 1) << i;
}
else {
*out = *in;
}
out++;
in++;
octets_left--;
count++;
}
return (count * 8) - zero_bits;
}
int sc_asn1_decode_bit_string(const u8 * inbuf, size_t inlen,
void *outbuf, size_t outlen)
{
return decode_bit_string(inbuf, inlen, outbuf, outlen, 1);
}
int sc_asn1_decode_bit_string_ni(const u8 * inbuf, size_t inlen,
void *outbuf, size_t outlen)
{
return decode_bit_string(inbuf, inlen, outbuf, outlen, 0);
}
static int encode_bit_string(const u8 * inbuf, size_t bits_left, u8 **outbuf,
size_t *outlen, int invert)
{
const u8 *in = inbuf;
u8 *out;
size_t bytes;
int skipped = 0;
bytes = (bits_left + 7)/8 + 1;
*outbuf = out = malloc(bytes);
if (out == NULL)
return SC_ERROR_OUT_OF_MEMORY;
*outlen = bytes;
out += 1;
while (bits_left) {
int i, bits_to_go = 8;
*out = 0;
if (bits_left < 8) {
bits_to_go = bits_left;
skipped = 8 - bits_left;
}
if (invert) {
for (i = 0; i < bits_to_go; i++)
*out |= ((*in >> i) & 1) << (7 - i);
} else {
*out = *in;
if (bits_left < 8)
return SC_ERROR_NOT_SUPPORTED; /* FIXME */
}
bits_left -= bits_to_go;
out++, in++;
}
out = *outbuf;
out[0] = skipped;
return 0;
}
/*
* Bitfields are just bit strings, stored in an unsigned int
* (taking endianness into account)
*/
static int decode_bit_field(const u8 * inbuf, size_t inlen, void *outbuf, size_t outlen)
{
u8 data[sizeof(unsigned int)];
unsigned int field = 0;
int i, n;
if (outlen != sizeof(data))
return SC_ERROR_BUFFER_TOO_SMALL;
n = decode_bit_string(inbuf, inlen, data, sizeof(data), 1);
if (n < 0)
return n;
for (i = 0; i < n; i += 8) {
field |= (data[i/8] << i);
}
memcpy(outbuf, &field, outlen);
return 0;
}
static int encode_bit_field(const u8 *inbuf, size_t inlen,
u8 **outbuf, size_t *outlen)
{
u8 data[sizeof(unsigned int)];
unsigned int field = 0;
size_t i, bits;
if (inlen != sizeof(data))
return SC_ERROR_BUFFER_TOO_SMALL;
/* count the bits */
memcpy(&field, inbuf, inlen);
for (bits = 0; field; bits++)
field >>= 1;
memcpy(&field, inbuf, inlen);
for (i = 0; i < bits; i += 8)
data[i/8] = field >> i;
return encode_bit_string(data, bits, outbuf, outlen, 1);
}
int sc_asn1_decode_integer(const u8 * inbuf, size_t inlen, int *out)
{
int a = 0;
size_t i;
if (inlen > sizeof(int) || inlen == 0)
return SC_ERROR_INVALID_ASN1_OBJECT;
if (inbuf[0] & 0x80)
a = -1;
for (i = 0; i < inlen; i++) {
a <<= 8;
a |= *inbuf++;
}
*out = a;
return 0;
}
static int asn1_encode_integer(int in, u8 ** obj, size_t * objsize)
{
int i = sizeof(in) * 8, skip_zero, skip_sign;
u8 *p, b;
if (in < 0)
{
skip_sign = 1;
skip_zero= 0;
}
else
{
skip_sign = 0;
skip_zero= 1;
}
*obj = p = malloc(sizeof(in)+1);
if (*obj == NULL)
return SC_ERROR_OUT_OF_MEMORY;
do {
i -= 8;
b = in >> i;
if (skip_sign)
{
if (b != 0xff)
skip_sign = 0;
if (b & 0x80)
{
*p = b;
if (0xff == b)
continue;
}
else
{
p++;
skip_sign = 0;
}
}
if (b == 0 && skip_zero)
continue;
if (skip_zero) {
skip_zero = 0;
/* prepend 0x00 if MSb is 1 and integer positive */
if ((b & 0x80) != 0 && in > 0)
*p++ = 0;
}
*p++ = b;
} while (i > 0);
if (skip_sign)
p++;
*objsize = p - *obj;
if (*objsize == 0) {
*objsize = 1;
(*obj)[0] = 0;
}
return 0;
}
int
sc_asn1_decode_object_id(const u8 *inbuf, size_t inlen, struct sc_object_id *id)
{
int a;
const u8 *p = inbuf;
int *octet;
if (inlen == 0 || inbuf == NULL || id == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
sc_init_oid(id);
octet = id->value;
a = *p;
*octet++ = a / 40;
*octet++ = a % 40;
inlen--;
while (inlen) {
p++;
a = *p & 0x7F;
inlen--;
while (inlen && *p & 0x80) {
p++;
a <<= 7;
a |= *p & 0x7F;
inlen--;
}
*octet++ = a;
if (octet - id->value >= SC_MAX_OBJECT_ID_OCTETS) {
sc_init_oid(id);
return SC_ERROR_INVALID_ASN1_OBJECT;
}
};
return 0;
}
int
sc_asn1_encode_object_id(u8 **buf, size_t *buflen, const struct sc_object_id *id)
{
u8 temp[SC_MAX_OBJECT_ID_OCTETS*5], *p = temp;
int i;
if (!buflen || !id)
return SC_ERROR_INVALID_ARGUMENTS;
/* an OID must have at least two components */
if (id->value[0] == -1 || id->value[1] == -1)
return SC_ERROR_INVALID_ARGUMENTS;
for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) {
unsigned int k, shift;
if (id->value[i] == -1)
break;
k = id->value[i];
switch (i) {
case 0:
if (k > 2)
return SC_ERROR_INVALID_ARGUMENTS;
*p = k * 40;
break;
case 1:
if (k > 39)
return SC_ERROR_INVALID_ARGUMENTS;
*p++ += k;
break;
default:
shift = 28;
while (shift && (k >> shift) == 0)
shift -= 7;
while (shift) {
*p++ = 0x80 | ((k >> shift) & 0x7f);
shift -= 7;
}
*p++ = k & 0x7F;
break;
}
}
*buflen = p - temp;
if (buf) {
*buf = malloc(*buflen);
if (!*buf)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(*buf, temp, *buflen);
}
return 0;
}
static int sc_asn1_decode_utf8string(const u8 *inbuf, size_t inlen,
u8 *out, size_t *outlen)
{
if (inlen+1 > *outlen)
return SC_ERROR_BUFFER_TOO_SMALL;
*outlen = inlen+1;
memcpy(out, inbuf, inlen);
out[inlen] = 0;
return 0;
}
int sc_asn1_put_tag(unsigned int tag, const u8 * data, size_t datalen, u8 * out, size_t outlen, u8 **ptr)
{
size_t c = 0;
size_t tag_len;
size_t ii;
u8 *p = out;
u8 tag_char[4] = {0, 0, 0, 0};
/* Check tag */
if (tag == 0 || tag > 0xFFFFFFFF) {
/* A tag of 0x00 is not valid and at most 4-byte tag names are supported. */
return SC_ERROR_INVALID_DATA;
}
for (tag_len = 0; tag; tag >>= 8) {
/* Note: tag char will be reversed order. */
tag_char[tag_len++] = tag & 0xFF;
}
if (tag_len > 1) {
if ((tag_char[tag_len - 1] & SC_ASN1_TAG_PRIMITIVE) != SC_ASN1_TAG_ESCAPE_MARKER) {
/* First byte is not escape marker. */
return SC_ERROR_INVALID_DATA;
}
for (ii = 1; ii < tag_len - 1; ii++) {
if ((tag_char[ii] & 0x80) != 0x80) {
/* MS bit is not 'one'. */
return SC_ERROR_INVALID_DATA;
}
}
if ((tag_char[0] & 0x80) != 0x00) {
/* MS bit of the last byte is not 'zero'. */
return SC_ERROR_INVALID_DATA;
}
}
/* Calculate the number of additional bytes necessary to encode the length. */
/* c+1 is the size of the length field. */
if (datalen > 127) {
c = 1;
while (datalen >> (c << 3))
c++;
}
if (outlen == 0 || out == NULL) {
/* Caller only asks for the length that would be written. */
return tag_len + (c+1) + datalen;
}
/* We will write the tag, so check the length. */
if (outlen < tag_len + (c+1) + datalen)
return SC_ERROR_BUFFER_TOO_SMALL;
for (ii=0;ii<tag_len;ii++)
*p++ = tag_char[tag_len - ii - 1];
if (c > 0) {
*p++ = 0x80 | c;
while (c--)
*p++ = (datalen >> (c << 3)) & 0xFF;
}
else {
*p++ = datalen & 0x7F;
}
if(data && datalen > 0) {
memcpy(p, data, datalen);
p += datalen;
}
if (ptr != NULL)
*ptr = p;
return 0;
}
int sc_asn1_write_element(sc_context_t *ctx, unsigned int tag,
const u8 * data, size_t datalen, u8 ** out, size_t * outlen)
{
return asn1_write_element(ctx, tag, data, datalen, out, outlen);
}
static int asn1_write_element(sc_context_t *ctx, unsigned int tag,
const u8 * data, size_t datalen, u8 ** out, size_t * outlen)
{
unsigned char t;
unsigned char *buf, *p;
int c = 0;
unsigned short_tag;
unsigned char tag_char[3] = {0, 0, 0};
size_t tag_len, ii;
short_tag = tag & SC_ASN1_TAG_MASK;
for (tag_len = 0; short_tag >> (8 * tag_len); tag_len++)
tag_char[tag_len] = (short_tag >> (8 * tag_len)) & 0xFF;
if (!tag_len)
tag_len = 1;
if (tag_len > 1) {
if ((tag_char[tag_len - 1] & SC_ASN1_TAG_PRIMITIVE) != SC_ASN1_TAG_ESCAPE_MARKER)
SC_TEST_RET(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_INVALID_DATA, "First byte of the long tag is not 'escape marker'");
for (ii = 1; ii < tag_len - 1; ii++)
if (!(tag_char[ii] & 0x80))
SC_TEST_RET(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_INVALID_DATA, "MS bit expected to be 'one'");
if (tag_char[0] & 0x80)
SC_TEST_RET(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_INVALID_DATA, "MS bit of the last byte expected to be 'zero'");
}
t = tag_char[tag_len - 1] & 0x1F;
switch (tag & SC_ASN1_CLASS_MASK) {
case SC_ASN1_UNI:
break;
case SC_ASN1_APP:
t |= SC_ASN1_TAG_APPLICATION;
break;
case SC_ASN1_CTX:
t |= SC_ASN1_TAG_CONTEXT;
break;
case SC_ASN1_PRV:
t |= SC_ASN1_TAG_PRIVATE;
break;
}
if (tag & SC_ASN1_CONS)
t |= SC_ASN1_TAG_CONSTRUCTED;
if (datalen > 127) {
c = 1;
while (datalen >> (c << 3))
c++;
}
*outlen = tag_len + 1 + c + datalen;
buf = malloc(*outlen);
if (buf == NULL)
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_OUT_OF_MEMORY);
*out = p = buf;
*p++ = t;
for (ii=1;ii<tag_len;ii++)
*p++ = tag_char[tag_len - ii - 1];
if (c) {
*p++ = 0x80 | c;
while (c--)
*p++ = (datalen >> (c << 3)) & 0xFF;
}
else {
*p++ = datalen & 0x7F;
}
memcpy(p, data, datalen);
return SC_SUCCESS;
}
static const struct sc_asn1_entry c_asn1_path_ext[3] = {
{ "aid", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x0F, 0, NULL, NULL },
{ "path", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_OCTET_STRING, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static const struct sc_asn1_entry c_asn1_path[5] = {
{ "path", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "index", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "length", SC_ASN1_INTEGER, SC_ASN1_CTX | 0, SC_ASN1_OPTIONAL, NULL, NULL },
/* For some multi-applications PKCS#15 card the ODF records can hold the references to
* the xDF files and objects placed elsewhere then under the application DF of the ODF itself.
* In such a case the 'path' ASN1 data includes also the ID of the target application (AID).
* This path extension do not make a part of PKCS#15 standard.
*/
{ "pathExtended", SC_ASN1_STRUCT, SC_ASN1_CTX | 1 | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static int asn1_decode_path(sc_context_t *ctx, const u8 *in, size_t len,
sc_path_t *path, int depth)
{
int idx, count, r;
struct sc_asn1_entry asn1_path_ext[3], asn1_path[5];
unsigned char path_value[SC_MAX_PATH_SIZE], aid_value[SC_MAX_AID_SIZE];
size_t path_len = sizeof(path_value), aid_len = sizeof(aid_value);
memset(path, 0, sizeof(struct sc_path));
sc_copy_asn1_entry(c_asn1_path_ext, asn1_path_ext);
sc_copy_asn1_entry(c_asn1_path, asn1_path);
sc_format_asn1_entry(asn1_path_ext + 0, aid_value, &aid_len, 0);
sc_format_asn1_entry(asn1_path_ext + 1, path_value, &path_len, 0);
sc_format_asn1_entry(asn1_path + 0, path_value, &path_len, 0);
sc_format_asn1_entry(asn1_path + 1, &idx, NULL, 0);
sc_format_asn1_entry(asn1_path + 2, &count, NULL, 0);
sc_format_asn1_entry(asn1_path + 3, asn1_path_ext, NULL, 0);
r = asn1_decode(ctx, asn1_path, in, len, NULL, NULL, 0, depth + 1);
if (r)
return r;
if (asn1_path[3].flags & SC_ASN1_PRESENT) {
/* extended path present: set 'path' and 'aid' */
memcpy(path->aid.value, aid_value, aid_len);
path->aid.len = aid_len;
memcpy(path->value, path_value, path_len);
path->len = path_len;
}
else if (asn1_path[0].flags & SC_ASN1_PRESENT) {
/* path present: set 'path' */
memcpy(path->value, path_value, path_len);
path->len = path_len;
}
else {
/* failed if both 'path' and 'pathExtended' are absent */
return SC_ERROR_ASN1_OBJECT_NOT_FOUND;
}
if (path->len == 2)
path->type = SC_PATH_TYPE_FILE_ID;
else if (path->aid.len && path->len > 2)
path->type = SC_PATH_TYPE_FROM_CURRENT;
else
path->type = SC_PATH_TYPE_PATH;
if ((asn1_path[1].flags & SC_ASN1_PRESENT) && (asn1_path[2].flags & SC_ASN1_PRESENT)) {
path->index = idx;
path->count = count;
}
else {
path->index = 0;
path->count = -1;
}
return SC_SUCCESS;
}
static int asn1_encode_path(sc_context_t *ctx, const sc_path_t *path,
u8 **buf, size_t *bufsize, int depth, unsigned int parent_flags)
{
int r;
struct sc_asn1_entry asn1_path[5];
sc_path_t tpath = *path;
sc_copy_asn1_entry(c_asn1_path, asn1_path);
sc_format_asn1_entry(asn1_path + 0, (void *) &tpath.value, (void *) &tpath.len, 1);
asn1_path[0].flags |= parent_flags;
if (path->count > 0) {
sc_format_asn1_entry(asn1_path + 1, (void *) &tpath.index, NULL, 1);
sc_format_asn1_entry(asn1_path + 2, (void *) &tpath.count, NULL, 1);
}
r = asn1_encode(ctx, asn1_path, buf, bufsize, depth + 1);
return r;
}
static const struct sc_asn1_entry c_asn1_se[2] = {
{ "seInfo", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static const struct sc_asn1_entry c_asn1_se_info[4] = {
{ "se", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, 0, NULL, NULL },
{ "owner",SC_ASN1_OBJECT, SC_ASN1_TAG_OBJECT, SC_ASN1_OPTIONAL, NULL, NULL },
{ "aid", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static int asn1_decode_se_info(sc_context_t *ctx, const u8 *obj, size_t objlen,
sc_pkcs15_sec_env_info_t ***se, size_t *num, int depth)
{
struct sc_pkcs15_sec_env_info **ses;
const unsigned char *ptr = obj;
size_t idx, ptrlen = objlen;
int ret;
ses = calloc(SC_MAX_SE_NUM, sizeof(sc_pkcs15_sec_env_info_t *));
if (ses == NULL)
return SC_ERROR_OUT_OF_MEMORY;
for (idx=0; idx < SC_MAX_SE_NUM && ptrlen; ) {
struct sc_asn1_entry asn1_se[2];
struct sc_asn1_entry asn1_se_info[4];
struct sc_pkcs15_sec_env_info si;
sc_copy_asn1_entry(c_asn1_se, asn1_se);
sc_copy_asn1_entry(c_asn1_se_info, asn1_se_info);
si.aid.len = sizeof(si.aid.value);
sc_format_asn1_entry(asn1_se_info + 0, &si.se, NULL, 0);
sc_format_asn1_entry(asn1_se_info + 1, &si.owner, NULL, 0);
sc_format_asn1_entry(asn1_se_info + 2, &si.aid.value, &si.aid.len, 0);
sc_format_asn1_entry(asn1_se + 0, asn1_se_info, NULL, 0);
ret = asn1_decode(ctx, asn1_se, ptr, ptrlen, &ptr, &ptrlen, 0, depth+1);
if (ret != SC_SUCCESS)
goto err;
if (!(asn1_se_info[1].flags & SC_ASN1_PRESENT))
sc_init_oid(&si.owner);
ses[idx] = calloc(1, sizeof(sc_pkcs15_sec_env_info_t));
if (ses[idx] == NULL) {
ret = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
memcpy(ses[idx], &si, sizeof(struct sc_pkcs15_sec_env_info));
idx++;
}
*se = ses;
*num = idx;
ret = SC_SUCCESS;
err:
if (ret != SC_SUCCESS) {
size_t i;
for (i = 0; i < idx; i++)
if (ses[i])
free(ses[i]);
free(ses);
}
return ret;
}
static int asn1_encode_se_info(sc_context_t *ctx,
struct sc_pkcs15_sec_env_info **se, size_t se_num,
unsigned char **buf, size_t *bufsize, int depth)
{
unsigned char *ptr = NULL, *out = NULL, *p;
size_t ptrlen = 0, outlen = 0, idx;
int ret;
for (idx=0; idx < se_num; idx++) {
struct sc_asn1_entry asn1_se[2];
struct sc_asn1_entry asn1_se_info[4];
sc_copy_asn1_entry(c_asn1_se, asn1_se);
sc_copy_asn1_entry(c_asn1_se_info, asn1_se_info);
sc_format_asn1_entry(asn1_se_info + 0, &se[idx]->se, NULL, 1);
if (sc_valid_oid(&se[idx]->owner))
sc_format_asn1_entry(asn1_se_info + 1, &se[idx]->owner, NULL, 1);
if (se[idx]->aid.len)
sc_format_asn1_entry(asn1_se_info + 2, &se[idx]->aid.value, &se[idx]->aid.len, 1);
sc_format_asn1_entry(asn1_se + 0, asn1_se_info, NULL, 1);
ret = sc_asn1_encode(ctx, asn1_se, &ptr, &ptrlen);
if (ret != SC_SUCCESS)
goto err;
if (!ptrlen)
continue;
p = (unsigned char *) realloc(out, outlen + ptrlen);
if (!p) {
ret = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
out = p;
memcpy(out + outlen, ptr, ptrlen);
outlen += ptrlen;
free(ptr);
ptr = NULL;
ptrlen = 0;
}
*buf = out;
*bufsize = outlen;
ret = SC_SUCCESS;
err:
if (ret != SC_SUCCESS && out != NULL)
free(out);
return ret;
}
/* TODO: According to specification type of 'SecurityCondition' is 'CHOICE'.
* Do it at least for SC_ASN1_PKCS15_ID(authId), SC_ASN1_STRUCT(authReference) and NULL(always). */
static const struct sc_asn1_entry c_asn1_access_control_rule[3] = {
{ "accessMode", SC_ASN1_BIT_FIELD, SC_ASN1_TAG_BIT_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "securityCondition", SC_ASN1_PKCS15_ID, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
/*
* in src/libopensc/pkcs15.h SC_PKCS15_MAX_ACCESS_RULES defined as 8
*/
static const struct sc_asn1_entry c_asn1_access_control_rules[SC_PKCS15_MAX_ACCESS_RULES + 1] = {
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static const struct sc_asn1_entry c_asn1_com_obj_attr[6] = {
{ "label", SC_ASN1_UTF8STRING, SC_ASN1_TAG_UTF8STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "flags", SC_ASN1_BIT_FIELD, SC_ASN1_TAG_BIT_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "authId", SC_ASN1_PKCS15_ID, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "userConsent", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessControlRules", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static const struct sc_asn1_entry c_asn1_p15_obj[5] = {
{ "commonObjectAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ "classAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ "subClassAttributes", SC_ASN1_STRUCT, SC_ASN1_CTX | 0 | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "typeAttributes", SC_ASN1_STRUCT, SC_ASN1_CTX | 1 | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static int asn1_decode_p15_object(sc_context_t *ctx, const u8 *in,
size_t len, struct sc_asn1_pkcs15_object *obj,
int depth)
{
struct sc_pkcs15_object *p15_obj = obj->p15_obj;
struct sc_asn1_entry asn1_c_attr[6], asn1_p15_obj[5];
struct sc_asn1_entry asn1_ac_rules[SC_PKCS15_MAX_ACCESS_RULES + 1], asn1_ac_rule[SC_PKCS15_MAX_ACCESS_RULES][3];
size_t flags_len = sizeof(p15_obj->flags);
size_t label_len = sizeof(p15_obj->label);
size_t access_mode_len = sizeof(p15_obj->access_rules[0].access_mode);
int r, ii;
for (ii=0; ii<SC_PKCS15_MAX_ACCESS_RULES; ii++)
sc_copy_asn1_entry(c_asn1_access_control_rule, asn1_ac_rule[ii]);
sc_copy_asn1_entry(c_asn1_access_control_rules, asn1_ac_rules);
sc_copy_asn1_entry(c_asn1_com_obj_attr, asn1_c_attr);
sc_copy_asn1_entry(c_asn1_p15_obj, asn1_p15_obj);
sc_format_asn1_entry(asn1_c_attr + 0, p15_obj->label, &label_len, 0);
sc_format_asn1_entry(asn1_c_attr + 1, &p15_obj->flags, &flags_len, 0);
sc_format_asn1_entry(asn1_c_attr + 2, &p15_obj->auth_id, NULL, 0);
sc_format_asn1_entry(asn1_c_attr + 3, &p15_obj->user_consent, NULL, 0);
for (ii=0; ii<SC_PKCS15_MAX_ACCESS_RULES; ii++) {
sc_format_asn1_entry(asn1_ac_rule[ii] + 0, &p15_obj->access_rules[ii].access_mode, &access_mode_len, 0);
sc_format_asn1_entry(asn1_ac_rule[ii] + 1, &p15_obj->access_rules[ii].auth_id, NULL, 0);
sc_format_asn1_entry(asn1_ac_rules + ii, asn1_ac_rule[ii], NULL, 0);
}
sc_format_asn1_entry(asn1_c_attr + 4, asn1_ac_rules, NULL, 0);
sc_format_asn1_entry(asn1_p15_obj + 0, asn1_c_attr, NULL, 0);
sc_format_asn1_entry(asn1_p15_obj + 1, obj->asn1_class_attr, NULL, 0);
sc_format_asn1_entry(asn1_p15_obj + 2, obj->asn1_subclass_attr, NULL, 0);
sc_format_asn1_entry(asn1_p15_obj + 3, obj->asn1_type_attr, NULL, 0);
r = asn1_decode(ctx, asn1_p15_obj, in, len, NULL, NULL, 0, depth + 1);
return r;
}
static int asn1_encode_p15_object(sc_context_t *ctx, const struct sc_asn1_pkcs15_object *obj,
u8 **buf, size_t *bufsize, int depth)
{
struct sc_pkcs15_object p15_obj = *obj->p15_obj;
struct sc_asn1_entry asn1_c_attr[6], asn1_p15_obj[5];
struct sc_asn1_entry asn1_ac_rules[SC_PKCS15_MAX_ACCESS_RULES + 1], asn1_ac_rule[SC_PKCS15_MAX_ACCESS_RULES][3];
size_t label_len = strlen(p15_obj.label);
size_t flags_len;
size_t access_mode_len;
int r, ii;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "encode p15 obj(type:0x%X,access_mode:0x%X)", p15_obj.type, p15_obj.access_rules[0].access_mode);
if (p15_obj.access_rules[0].access_mode) {
for (ii=0; ii<SC_PKCS15_MAX_ACCESS_RULES; ii++) {
sc_copy_asn1_entry(c_asn1_access_control_rule, asn1_ac_rule[ii]);
if (p15_obj.access_rules[ii].auth_id.len == 0) {
asn1_ac_rule[ii][1].type = SC_ASN1_NULL;
asn1_ac_rule[ii][1].tag = SC_ASN1_TAG_NULL;
}
}
sc_copy_asn1_entry(c_asn1_access_control_rules, asn1_ac_rules);
}
sc_copy_asn1_entry(c_asn1_com_obj_attr, asn1_c_attr);
sc_copy_asn1_entry(c_asn1_p15_obj, asn1_p15_obj);
if (label_len != 0)
sc_format_asn1_entry(asn1_c_attr + 0, (void *) p15_obj.label, &label_len, 1);
if (p15_obj.flags) {
flags_len = sizeof(p15_obj.flags);
sc_format_asn1_entry(asn1_c_attr + 1, (void *) &p15_obj.flags, &flags_len, 1);
}
if (p15_obj.auth_id.len)
sc_format_asn1_entry(asn1_c_attr + 2, (void *) &p15_obj.auth_id, NULL, 1);
if (p15_obj.user_consent)
sc_format_asn1_entry(asn1_c_attr + 3, (void *) &p15_obj.user_consent, NULL, 1);
if (p15_obj.access_rules[0].access_mode) {
for (ii=0; p15_obj.access_rules[ii].access_mode; ii++) {
access_mode_len = sizeof(p15_obj.access_rules[ii].access_mode);
sc_format_asn1_entry(asn1_ac_rule[ii] + 0, (void *) &p15_obj.access_rules[ii].access_mode, &access_mode_len, 1);
sc_format_asn1_entry(asn1_ac_rule[ii] + 1, (void *) &p15_obj.access_rules[ii].auth_id, NULL, 1);
sc_format_asn1_entry(asn1_ac_rules + ii, asn1_ac_rule[ii], NULL, 1);
}
sc_format_asn1_entry(asn1_c_attr + 4, asn1_ac_rules, NULL, 1);
}
sc_format_asn1_entry(asn1_p15_obj + 0, asn1_c_attr, NULL, 1);
sc_format_asn1_entry(asn1_p15_obj + 1, obj->asn1_class_attr, NULL, 1);
if (obj->asn1_subclass_attr != NULL && obj->asn1_subclass_attr->name)
sc_format_asn1_entry(asn1_p15_obj + 2, obj->asn1_subclass_attr, NULL, 1);
sc_format_asn1_entry(asn1_p15_obj + 3, obj->asn1_type_attr, NULL, 1);
r = asn1_encode(ctx, asn1_p15_obj, buf, bufsize, depth + 1);
return r;
}
static int asn1_decode_entry(sc_context_t *ctx,struct sc_asn1_entry *entry,
const u8 *obj, size_t objlen, int depth)
{
void *parm = entry->parm;
int (*callback_func)(sc_context_t *nctx, void *arg, const u8 *nobj,
size_t nobjlen, int ndepth);
size_t *len = (size_t *) entry->arg;
int r = 0;
callback_func = parm;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s', raw data:%s%s\n",
depth, depth, "", entry->name,
sc_dump_hex(obj, objlen > 16 ? 16 : objlen),
objlen > 16 ? "..." : "");
switch (entry->type) {
case SC_ASN1_STRUCT:
if (parm != NULL)
r = asn1_decode(ctx, (struct sc_asn1_entry *) parm, obj,
objlen, NULL, NULL, 0, depth + 1);
break;
case SC_ASN1_NULL:
break;
case SC_ASN1_BOOLEAN:
if (parm != NULL) {
if (objlen != 1) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"invalid ASN.1 object length: %"SC_FORMAT_LEN_SIZE_T"u\n",
objlen);
r = SC_ERROR_INVALID_ASN1_OBJECT;
} else
*((int *) parm) = obj[0] ? 1 : 0;
}
break;
case SC_ASN1_INTEGER:
case SC_ASN1_ENUMERATED:
if (parm != NULL) {
r = sc_asn1_decode_integer(obj, objlen, (int *) entry->parm);
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s' returned %d\n", depth, depth, "",
entry->name, *((int *) entry->parm));
}
break;
case SC_ASN1_BIT_STRING_NI:
case SC_ASN1_BIT_STRING:
if (parm != NULL) {
int invert = entry->type == SC_ASN1_BIT_STRING ? 1 : 0;
assert(len != NULL);
if (objlen < 1) {
r = SC_ERROR_INVALID_ASN1_OBJECT;
break;
}
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen-1);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
*len = objlen-1;
parm = *buf;
}
r = decode_bit_string(obj, objlen, (u8 *) parm, *len, invert);
if (r >= 0) {
*len = r;
r = 0;
}
}
break;
case SC_ASN1_BIT_FIELD:
if (parm != NULL)
r = decode_bit_field(obj, objlen, (u8 *) parm, *len);
break;
case SC_ASN1_OCTET_STRING:
if (parm != NULL) {
size_t c;
assert(len != NULL);
/* Strip off padding zero */
if ((entry->flags & SC_ASN1_UNSIGNED)
&& obj[0] == 0x00 && objlen > 1) {
objlen--;
obj++;
}
/* Allocate buffer if needed */
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
c = *len = objlen;
parm = *buf;
} else
c = objlen > *len ? *len : objlen;
memcpy(parm, obj, c);
*len = c;
}
break;
case SC_ASN1_GENERALIZEDTIME:
if (parm != NULL) {
size_t c;
assert(len != NULL);
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
c = *len = objlen;
parm = *buf;
} else
c = objlen > *len ? *len : objlen;
memcpy(parm, obj, c);
*len = c;
}
break;
case SC_ASN1_OBJECT:
if (parm != NULL)
r = sc_asn1_decode_object_id(obj, objlen, (struct sc_object_id *) parm);
break;
case SC_ASN1_PRINTABLESTRING:
case SC_ASN1_UTF8STRING:
if (parm != NULL) {
assert(len != NULL);
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen+1);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
*len = objlen+1;
parm = *buf;
}
r = sc_asn1_decode_utf8string(obj, objlen, (u8 *) parm, len);
if (entry->flags & SC_ASN1_ALLOC) {
*len -= 1;
}
}
break;
case SC_ASN1_PATH:
if (entry->parm != NULL)
r = asn1_decode_path(ctx, obj, objlen, (sc_path_t *) parm, depth);
break;
case SC_ASN1_PKCS15_ID:
if (entry->parm != NULL) {
struct sc_pkcs15_id *id = (struct sc_pkcs15_id *) parm;
size_t c = objlen > sizeof(id->value) ? sizeof(id->value) : objlen;
memcpy(id->value, obj, c);
id->len = c;
}
break;
case SC_ASN1_PKCS15_OBJECT:
if (entry->parm != NULL)
r = asn1_decode_p15_object(ctx, obj, objlen, (struct sc_asn1_pkcs15_object *) parm, depth);
break;
case SC_ASN1_ALGORITHM_ID:
if (entry->parm != NULL)
r = sc_asn1_decode_algorithm_id(ctx, obj, objlen, (struct sc_algorithm_id *) parm, depth);
break;
case SC_ASN1_SE_INFO:
if (entry->parm != NULL)
r = asn1_decode_se_info(ctx, obj, objlen, (sc_pkcs15_sec_env_info_t ***)entry->parm, len, depth);
break;
case SC_ASN1_CALLBACK:
if (entry->parm != NULL)
r = callback_func(ctx, entry->arg, obj, objlen, depth);
break;
default:
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 type: %d\n", entry->type);
return SC_ERROR_INVALID_ASN1_OBJECT;
}
if (r) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "decoding of ASN.1 object '%s' failed: %s\n", entry->name,
sc_strerror(r));
return r;
}
entry->flags |= SC_ASN1_PRESENT;
return 0;
}
static int asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1,
const u8 *in, size_t len, const u8 **newp, size_t *len_left,
int choice, int depth)
{
int r, idx = 0;
const u8 *p = in, *obj;
struct sc_asn1_entry *entry = asn1;
size_t left = len, objlen;
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"%*.*scalled, left=%"SC_FORMAT_LEN_SIZE_T"u, depth %d%s\n",
depth, depth, "", left, depth, choice ? ", choice" : "");
if (!p)
return SC_ERROR_ASN1_OBJECT_NOT_FOUND;
if (left < 2) {
while (asn1->name && (asn1->flags & SC_ASN1_OPTIONAL))
asn1++;
/* If all elements were optional, there's nothing
* to complain about */
if (asn1->name == NULL)
return 0;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "End of ASN.1 stream, "
"non-optional field \"%s\" not found\n",
asn1->name);
return SC_ERROR_ASN1_OBJECT_NOT_FOUND;
}
if (p[0] == 0 || p[0] == 0xFF || len == 0)
return SC_ERROR_ASN1_END_OF_CONTENTS;
for (idx = 0; asn1[idx].name != NULL; idx++) {
entry = &asn1[idx];
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "Looking for '%s', tag 0x%x%s%s\n",
entry->name, entry->tag, choice? ", CHOICE" : "",
(entry->flags & SC_ASN1_OPTIONAL)? ", OPTIONAL": "");
/* Special case CHOICE has no tag */
if (entry->type == SC_ASN1_CHOICE) {
r = asn1_decode(ctx,
(struct sc_asn1_entry *) entry->parm,
p, left, &p, &left, 1, depth + 1);
if (r >= 0)
r = 0;
goto decode_ok;
}
obj = sc_asn1_skip_tag(ctx, &p, &left, entry->tag, &objlen);
if (obj == NULL) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "'%s' not present\n", entry->name);
if (choice)
continue;
if (entry->flags & SC_ASN1_OPTIONAL)
continue;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "mandatory ASN.1 object '%s' not found\n", entry->name);
if (left) {
u8 line[128], *linep = line;
size_t i;
line[0] = 0;
for (i = 0; i < 10 && i < left; i++) {
sprintf((char *) linep, "%02X ", p[i]);
linep += 3;
}
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "next tag: %s\n", line);
}
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_ASN1_OBJECT_NOT_FOUND);
}
r = asn1_decode_entry(ctx, entry, obj, objlen, depth);
decode_ok:
if (r)
return r;
if (choice)
break;
}
if (choice && asn1[idx].name == NULL) /* No match */
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_ASN1_OBJECT_NOT_FOUND);
if (newp != NULL)
*newp = p;
if (len_left != NULL)
*len_left = left;
if (choice)
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, idx);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, 0);
}
int sc_asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1,
const u8 *in, size_t len, const u8 **newp, size_t *len_left)
{
return asn1_decode(ctx, asn1, in, len, newp, len_left, 0, 0);
}
int sc_asn1_decode_choice(sc_context_t *ctx, struct sc_asn1_entry *asn1,
const u8 *in, size_t len, const u8 **newp, size_t *len_left)
{
return asn1_decode(ctx, asn1, in, len, newp, len_left, 1, 0);
}
static int asn1_encode_entry(sc_context_t *ctx, const struct sc_asn1_entry *entry,
u8 **obj, size_t *objlen, int depth)
{
void *parm = entry->parm;
int (*callback_func)(sc_context_t *nctx, void *arg, u8 **nobj,
size_t *nobjlen, int ndepth);
const size_t *len = (const size_t *) entry->arg;
int r = 0;
u8 * buf = NULL;
size_t buflen = 0;
callback_func = parm;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sencoding '%s'%s\n",
depth, depth, "", entry->name,
(entry->flags & SC_ASN1_PRESENT)? "" : " (not present)");
if (!(entry->flags & SC_ASN1_PRESENT))
goto no_object;
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"%*.*stype=%d, tag=0x%02x, parm=%p, len=%"SC_FORMAT_LEN_SIZE_T"u\n",
depth, depth, "", entry->type, entry->tag, parm,
len ? *len : 0);
if (entry->type == SC_ASN1_CHOICE) {
const struct sc_asn1_entry *list, *choice = NULL;
list = (const struct sc_asn1_entry *) parm;
while (list->name != NULL) {
if (list->flags & SC_ASN1_PRESENT) {
if (choice) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"ASN.1 problem: more than "
"one CHOICE when encoding %s: "
"%s and %s both present\n",
entry->name,
choice->name,
list->name);
return SC_ERROR_INVALID_ASN1_OBJECT;
}
choice = list;
}
list++;
}
if (choice == NULL)
goto no_object;
return asn1_encode_entry(ctx, choice, obj, objlen, depth + 1);
}
if (entry->type != SC_ASN1_NULL && parm == NULL) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "unexpected parm == NULL\n");
return SC_ERROR_INVALID_ASN1_OBJECT;
}
switch (entry->type) {
case SC_ASN1_STRUCT:
r = asn1_encode(ctx, (const struct sc_asn1_entry *) parm, &buf,
&buflen, depth + 1);
break;
case SC_ASN1_NULL:
buf = NULL;
buflen = 0;
break;
case SC_ASN1_BOOLEAN:
buf = malloc(1);
if (buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
buf[0] = *((int *) parm) ? 0xFF : 0;
buflen = 1;
break;
case SC_ASN1_INTEGER:
case SC_ASN1_ENUMERATED:
r = asn1_encode_integer(*((int *) entry->parm), &buf, &buflen);
break;
case SC_ASN1_BIT_STRING_NI:
case SC_ASN1_BIT_STRING:
if (len != NULL) {
if (entry->type == SC_ASN1_BIT_STRING)
r = encode_bit_string((const u8 *) parm, *len, &buf, &buflen, 1);
else
r = encode_bit_string((const u8 *) parm, *len, &buf, &buflen, 0);
} else {
r = SC_ERROR_INVALID_ARGUMENTS;
}
break;
case SC_ASN1_BIT_FIELD:
if (len != NULL) {
r = encode_bit_field((const u8 *) parm, *len, &buf, &buflen);
} else {
r = SC_ERROR_INVALID_ARGUMENTS;
}
break;
case SC_ASN1_PRINTABLESTRING:
case SC_ASN1_OCTET_STRING:
case SC_ASN1_UTF8STRING:
if (len != NULL) {
buf = malloc(*len + 1);
if (buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
buflen = 0;
/* If the integer is supposed to be unsigned, insert
* a padding byte if the MSB is one */
if ((entry->flags & SC_ASN1_UNSIGNED)
&& (((u8 *) parm)[0] & 0x80)) {
buf[buflen++] = 0x00;
}
memcpy(buf + buflen, parm, *len);
buflen += *len;
} else {
r = SC_ERROR_INVALID_ARGUMENTS;
}
break;
case SC_ASN1_GENERALIZEDTIME:
if (len != NULL) {
buf = malloc(*len);
if (buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
memcpy(buf, parm, *len);
buflen = *len;
} else {
r = SC_ERROR_INVALID_ARGUMENTS;
}
break;
case SC_ASN1_OBJECT:
r = sc_asn1_encode_object_id(&buf, &buflen, (struct sc_object_id *) parm);
break;
case SC_ASN1_PATH:
r = asn1_encode_path(ctx, (const sc_path_t *) parm, &buf, &buflen, depth, entry->flags);
break;
case SC_ASN1_PKCS15_ID:
{
const struct sc_pkcs15_id *id = (const struct sc_pkcs15_id *) parm;
buf = malloc(id->len);
if (buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
memcpy(buf, id->value, id->len);
buflen = id->len;
}
break;
case SC_ASN1_PKCS15_OBJECT:
r = asn1_encode_p15_object(ctx, (const struct sc_asn1_pkcs15_object *) parm, &buf, &buflen, depth);
break;
case SC_ASN1_ALGORITHM_ID:
r = sc_asn1_encode_algorithm_id(ctx, &buf, &buflen, (const struct sc_algorithm_id *) parm, depth);
break;
case SC_ASN1_SE_INFO:
if (!len)
return SC_ERROR_INVALID_ASN1_OBJECT;
r = asn1_encode_se_info(ctx, (struct sc_pkcs15_sec_env_info **)parm, *len, &buf, &buflen, depth);
break;
case SC_ASN1_CALLBACK:
r = callback_func(ctx, entry->arg, &buf, &buflen, depth);
break;
default:
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 type: %d\n", entry->type);
return SC_ERROR_INVALID_ASN1_OBJECT;
}
if (r) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "encoding of ASN.1 object '%s' failed: %s\n", entry->name,
sc_strerror(r));
if (buf)
free(buf);
return r;
}
/* Treatment of OPTIONAL elements:
* - if the encoding has 0 length, and the element is OPTIONAL,
* we don't write anything (unless it's an ASN1 NULL and the
* SC_ASN1_PRESENT flag is set).
* - if the encoding has 0 length, but the element is non-OPTIONAL,
* constructed, we write a empty element (e.g. a SEQUENCE of
* length 0). In case of an ASN1 NULL just write the tag and
* length (i.e. 0x05,0x00).
* - any other empty objects are considered bogus
*/
no_object:
if (!buflen && entry->flags & SC_ASN1_OPTIONAL && !(entry->flags & SC_ASN1_PRESENT)) {
/* This happens when we try to encode e.g. the
* subClassAttributes, which may be empty */
*obj = NULL;
*objlen = 0;
r = 0;
} else if (!buflen && (entry->flags & SC_ASN1_EMPTY_ALLOWED)) {
*obj = NULL;
*objlen = 0;
r = asn1_write_element(ctx, entry->tag, buf, buflen, obj, objlen);
if (r)
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "error writing ASN.1 tag and length: %s\n", sc_strerror(r));
} else if (buflen || entry->type == SC_ASN1_NULL || entry->tag & SC_ASN1_CONS) {
r = asn1_write_element(ctx, entry->tag, buf, buflen, obj, objlen);
if (r)
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "error writing ASN.1 tag and length: %s\n",
sc_strerror(r));
} else if (!(entry->flags & SC_ASN1_PRESENT)) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "cannot encode non-optional ASN.1 object: not given by caller\n");
r = SC_ERROR_INVALID_ASN1_OBJECT;
} else {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "cannot encode empty non-optional ASN.1 object\n");
r = SC_ERROR_INVALID_ASN1_OBJECT;
}
if (buf)
free(buf);
if (r >= 0)
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"%*.*slength of encoded item=%"SC_FORMAT_LEN_SIZE_T"u\n",
depth, depth, "", *objlen);
return r;
}
static int asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1,
u8 **ptr, size_t *size, int depth)
{
int r, idx = 0;
u8 *obj = NULL, *buf = NULL, *tmp;
size_t total = 0, objsize;
for (idx = 0; asn1[idx].name != NULL; idx++) {
r = asn1_encode_entry(ctx, &asn1[idx], &obj, &objsize, depth);
if (r) {
if (obj)
free(obj);
if (buf)
free(buf);
return r;
}
/* in case of an empty (optional) element continue with
* the next asn1 element */
if (!objsize)
continue;
tmp = (u8 *) realloc(buf, total + objsize);
if (!tmp) {
if (obj)
free(obj);
if (buf)
free(buf);
return SC_ERROR_OUT_OF_MEMORY;
}
buf = tmp;
memcpy(buf + total, obj, objsize);
free(obj);
obj = NULL;
total += objsize;
}
*ptr = buf;
*size = total;
return 0;
}
int sc_asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1,
u8 **ptr, size_t *size)
{
return asn1_encode(ctx, asn1, ptr, size, 0);
}
int _sc_asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1,
u8 **ptr, size_t *size, int depth)
{
return asn1_encode(ctx, asn1, ptr, size, depth);
}
int
_sc_asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1,
const u8 *in, size_t len, const u8 **newp, size_t *left,
int choice, int depth)
{
return asn1_decode(ctx, asn1, in, len, newp, left, choice, depth);
}
int
sc_der_copy(sc_pkcs15_der_t *dst, const sc_pkcs15_der_t *src)
{
if (!dst)
return SC_ERROR_INVALID_ARGUMENTS;
memset(dst, 0, sizeof(*dst));
if (src->len) {
dst->value = malloc(src->len);
if (!dst->value)
return SC_ERROR_OUT_OF_MEMORY;
dst->len = src->len;
memcpy(dst->value, src->value, src->len);
}
return SC_SUCCESS;
}
int
sc_encode_oid (struct sc_context *ctx, struct sc_object_id *id,
unsigned char **out, size_t *size)
{
static const struct sc_asn1_entry c_asn1_object_id[2] = {
{ "oid", SC_ASN1_OBJECT, SC_ASN1_TAG_OBJECT, SC_ASN1_ALLOC, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
struct sc_asn1_entry asn1_object_id[2];
int rv;
sc_copy_asn1_entry(c_asn1_object_id, asn1_object_id);
sc_format_asn1_entry(asn1_object_id + 0, id, NULL, 1);
rv = _sc_asn1_encode(ctx, asn1_object_id, out, size, 1);
LOG_TEST_RET(ctx, rv, "Cannot encode object ID");
return SC_SUCCESS;
}
#define C_ASN1_SIG_VALUE_SIZE 2
static struct sc_asn1_entry c_asn1_sig_value[C_ASN1_SIG_VALUE_SIZE] = {
{ "ECDSA-Sig-Value", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE 3
static struct sc_asn1_entry c_asn1_sig_value_coefficients[C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE] = {
{ "r", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_INTEGER, SC_ASN1_ALLOC|SC_ASN1_UNSIGNED, NULL, NULL },
{ "s", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_INTEGER, SC_ASN1_ALLOC|SC_ASN1_UNSIGNED, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
int
sc_asn1_sig_value_rs_to_sequence(struct sc_context *ctx, unsigned char *in, size_t inlen,
unsigned char **buf, size_t *buflen)
{
struct sc_asn1_entry asn1_sig_value[C_ASN1_SIG_VALUE_SIZE];
struct sc_asn1_entry asn1_sig_value_coefficients[C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE];
unsigned char *r = in, *s = in + inlen/2;
size_t r_len = inlen/2, s_len = inlen/2;
int rv;
LOG_FUNC_CALLED(ctx);
/* R/S are filled up with zeroes, we do not want that in sequence format */
while(r_len > 1 && *r == 0x00) {
r++;
r_len--;
}
while(s_len > 1 && *s == 0x00) {
s++;
s_len--;
}
sc_copy_asn1_entry(c_asn1_sig_value, asn1_sig_value);
sc_format_asn1_entry(asn1_sig_value + 0, asn1_sig_value_coefficients, NULL, 1);
sc_copy_asn1_entry(c_asn1_sig_value_coefficients, asn1_sig_value_coefficients);
sc_format_asn1_entry(asn1_sig_value_coefficients + 0, r, &r_len, 1);
sc_format_asn1_entry(asn1_sig_value_coefficients + 1, s, &s_len, 1);
rv = sc_asn1_encode(ctx, asn1_sig_value, buf, buflen);
LOG_TEST_RET(ctx, rv, "ASN.1 encoding ECDSA-SIg-Value failed");
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
int
sc_asn1_sig_value_sequence_to_rs(struct sc_context *ctx, const unsigned char *in, size_t inlen,
unsigned char *buf, size_t buflen)
{
struct sc_asn1_entry asn1_sig_value[C_ASN1_SIG_VALUE_SIZE];
struct sc_asn1_entry asn1_sig_value_coefficients[C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE];
unsigned char *r = NULL, *s = NULL;
size_t r_len, s_len, halflen = buflen/2;
int rv;
LOG_FUNC_CALLED(ctx);
if (!buf || !buflen)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
sc_copy_asn1_entry(c_asn1_sig_value, asn1_sig_value);
sc_format_asn1_entry(asn1_sig_value + 0, asn1_sig_value_coefficients, NULL, 0);
sc_copy_asn1_entry(c_asn1_sig_value_coefficients, asn1_sig_value_coefficients);
sc_format_asn1_entry(asn1_sig_value_coefficients + 0, &r, &r_len, 0);
sc_format_asn1_entry(asn1_sig_value_coefficients + 1, &s, &s_len, 0);
rv = sc_asn1_decode(ctx, asn1_sig_value, in, inlen, NULL, NULL);
LOG_TEST_GOTO_ERR(ctx, rv, "ASN.1 decoding ECDSA-Sig-Value failed");
if (halflen < r_len || halflen < s_len) {
rv = SC_ERROR_BUFFER_TOO_SMALL;
goto err;
}
memset(buf, 0, buflen);
memcpy(buf + (halflen - r_len), r, r_len);
memcpy(buf + (buflen - s_len), s, s_len);
sc_log(ctx, "r(%"SC_FORMAT_LEN_SIZE_T"u): %s", halflen,
sc_dump_hex(buf, halflen));
sc_log(ctx, "s(%"SC_FORMAT_LEN_SIZE_T"u): %s", halflen,
sc_dump_hex(buf + halflen, halflen));
rv = SC_SUCCESS;
err:
free(r);
free(s);
LOG_FUNC_RETURN(ctx, rv);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1063_0 |
crossvul-cpp_data_good_2918_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% W W PPPP GGGG %
% W W P P G %
% W W W PPPP G GGG %
% WW WW P G G %
% W W P GGG %
% %
% %
% Read WordPerfect Image Format %
% %
% Software Design %
% Jaroslav Fojtik %
% June 2000 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/distort.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magic.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/resource_.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
#include "MagickCore/transform.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
typedef struct
{
unsigned char Red;
unsigned char Blue;
unsigned char Green;
} RGB_Record;
/* Default palette for WPG level 1 */
static const RGB_Record WPG1_Palette[256]={
{ 0, 0, 0}, { 0, 0,168},
{ 0,168, 0}, { 0,168,168},
{168, 0, 0}, {168, 0,168},
{168, 84, 0}, {168,168,168},
{ 84, 84, 84}, { 84, 84,252},
{ 84,252, 84}, { 84,252,252},
{252, 84, 84}, {252, 84,252},
{252,252, 84}, {252,252,252}, /*16*/
{ 0, 0, 0}, { 20, 20, 20},
{ 32, 32, 32}, { 44, 44, 44},
{ 56, 56, 56}, { 68, 68, 68},
{ 80, 80, 80}, { 96, 96, 96},
{112,112,112}, {128,128,128},
{144,144,144}, {160,160,160},
{180,180,180}, {200,200,200},
{224,224,224}, {252,252,252}, /*32*/
{ 0, 0,252}, { 64, 0,252},
{124, 0,252}, {188, 0,252},
{252, 0,252}, {252, 0,188},
{252, 0,124}, {252, 0, 64},
{252, 0, 0}, {252, 64, 0},
{252,124, 0}, {252,188, 0},
{252,252, 0}, {188,252, 0},
{124,252, 0}, { 64,252, 0}, /*48*/
{ 0,252, 0}, { 0,252, 64},
{ 0,252,124}, { 0,252,188},
{ 0,252,252}, { 0,188,252},
{ 0,124,252}, { 0, 64,252},
{124,124,252}, {156,124,252},
{188,124,252}, {220,124,252},
{252,124,252}, {252,124,220},
{252,124,188}, {252,124,156}, /*64*/
{252,124,124}, {252,156,124},
{252,188,124}, {252,220,124},
{252,252,124}, {220,252,124},
{188,252,124}, {156,252,124},
{124,252,124}, {124,252,156},
{124,252,188}, {124,252,220},
{124,252,252}, {124,220,252},
{124,188,252}, {124,156,252}, /*80*/
{180,180,252}, {196,180,252},
{216,180,252}, {232,180,252},
{252,180,252}, {252,180,232},
{252,180,216}, {252,180,196},
{252,180,180}, {252,196,180},
{252,216,180}, {252,232,180},
{252,252,180}, {232,252,180},
{216,252,180}, {196,252,180}, /*96*/
{180,220,180}, {180,252,196},
{180,252,216}, {180,252,232},
{180,252,252}, {180,232,252},
{180,216,252}, {180,196,252},
{0,0,112}, {28,0,112},
{56,0,112}, {84,0,112},
{112,0,112}, {112,0,84},
{112,0,56}, {112,0,28}, /*112*/
{112,0,0}, {112,28,0},
{112,56,0}, {112,84,0},
{112,112,0}, {84,112,0},
{56,112,0}, {28,112,0},
{0,112,0}, {0,112,28},
{0,112,56}, {0,112,84},
{0,112,112}, {0,84,112},
{0,56,112}, {0,28,112}, /*128*/
{56,56,112}, {68,56,112},
{84,56,112}, {96,56,112},
{112,56,112}, {112,56,96},
{112,56,84}, {112,56,68},
{112,56,56}, {112,68,56},
{112,84,56}, {112,96,56},
{112,112,56}, {96,112,56},
{84,112,56}, {68,112,56}, /*144*/
{56,112,56}, {56,112,69},
{56,112,84}, {56,112,96},
{56,112,112}, {56,96,112},
{56,84,112}, {56,68,112},
{80,80,112}, {88,80,112},
{96,80,112}, {104,80,112},
{112,80,112}, {112,80,104},
{112,80,96}, {112,80,88}, /*160*/
{112,80,80}, {112,88,80},
{112,96,80}, {112,104,80},
{112,112,80}, {104,112,80},
{96,112,80}, {88,112,80},
{80,112,80}, {80,112,88},
{80,112,96}, {80,112,104},
{80,112,112}, {80,114,112},
{80,96,112}, {80,88,112}, /*176*/
{0,0,64}, {16,0,64},
{32,0,64}, {48,0,64},
{64,0,64}, {64,0,48},
{64,0,32}, {64,0,16},
{64,0,0}, {64,16,0},
{64,32,0}, {64,48,0},
{64,64,0}, {48,64,0},
{32,64,0}, {16,64,0}, /*192*/
{0,64,0}, {0,64,16},
{0,64,32}, {0,64,48},
{0,64,64}, {0,48,64},
{0,32,64}, {0,16,64},
{32,32,64}, {40,32,64},
{48,32,64}, {56,32,64},
{64,32,64}, {64,32,56},
{64,32,48}, {64,32,40}, /*208*/
{64,32,32}, {64,40,32},
{64,48,32}, {64,56,32},
{64,64,32}, {56,64,32},
{48,64,32}, {40,64,32},
{32,64,32}, {32,64,40},
{32,64,48}, {32,64,56},
{32,64,64}, {32,56,64},
{32,48,64}, {32,40,64}, /*224*/
{44,44,64}, {48,44,64},
{52,44,64}, {60,44,64},
{64,44,64}, {64,44,60},
{64,44,52}, {64,44,48},
{64,44,44}, {64,48,44},
{64,52,44}, {64,60,44},
{64,64,44}, {60,64,44},
{52,64,44}, {48,64,44}, /*240*/
{44,64,44}, {44,64,48},
{44,64,52}, {44,64,60},
{44,64,64}, {44,60,64},
{44,55,64}, {44,48,64},
{0,0,0}, {0,0,0},
{0,0,0}, {0,0,0},
{0,0,0}, {0,0,0},
{0,0,0}, {0,0,0} /*256*/
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s W P G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsWPG() returns True if the image format type, identified by the magick
% string, is WPG.
%
% The format of the IsWPG method is:
%
% unsigned int IsWPG(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o status: Method IsWPG returns True if the image format type is WPG.
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static unsigned int IsWPG(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\377WPC",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
static void Rd_WP_DWORD(Image *image,size_t *d)
{
unsigned char
b;
b=ReadBlobByte(image);
*d=b;
if (b < 0xFFU)
return;
b=ReadBlobByte(image);
*d=(size_t) b;
b=ReadBlobByte(image);
*d+=(size_t) b*256l;
if (*d < 0x8000)
return;
*d=(*d & 0x7FFF) << 16;
b=ReadBlobByte(image);
*d+=(size_t) b;
b=ReadBlobByte(image);
*d+=(size_t) b*256l;
return;
}
static MagickBooleanType InsertRow(Image *image,unsigned char *p,ssize_t y,
int bpp,ExceptionInfo *exception)
{
int
bit;
Quantum
index;
register Quantum
*q;
ssize_t
x;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
return(MagickFalse);
switch (bpp)
{
case 1: /* Convert bitmap scanline. */
{
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (ssize_t) (image->columns % 8); bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
p++;
}
break;
}
case 2: /* Convert PseudoColor scanline. */
{
for (x=0; x < ((ssize_t) image->columns-3); x+=4)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
p++;
}
if ((image->columns % 4) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
if ((image->columns % 4) > 1)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
if ((image->columns % 4) > 2)
{
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,
exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
}
p++;
}
break;
}
case 4: /* Convert PseudoColor scanline. */
{
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0x0f,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
if ((image->columns % 2) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
break;
}
case 8: /* Convert PseudoColor scanline. */
{
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
}
break;
case 24: /* Convert DirectColor scanline. */
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
break;
}
if (!SyncAuthenticPixels(image,exception))
return(MagickFalse);
return(MagickTrue);
}
/* Helper for WPG1 raster reader. */
#define InsertByte(b) \
{ \
BImgBuff[x]=b; \
x++; \
if((ssize_t) x>=ldblk) \
{ \
if (InsertRow(image,BImgBuff,(ssize_t) y,bpp,exception) != MagickFalse) \
y++; \
x=0; \
} \
}
/* WPG1 raster reader. */
static int UnpackWPGRaster(Image *image,int bpp,ExceptionInfo *exception)
{
int
x,
y,
i;
unsigned char
bbuf,
*BImgBuff,
RunCount;
ssize_t
ldblk;
x=0;
y=0;
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
8*sizeof(*BImgBuff));
if(BImgBuff==NULL) return(-2);
while(y<(ssize_t) image->rows)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
bbuf=(unsigned char) c;
RunCount=bbuf & 0x7F;
if(bbuf & 0x80)
{
if(RunCount) /* repeat next byte runcount * */
{
bbuf=ReadBlobByte(image);
for(i=0;i<(int) RunCount;i++) InsertByte(bbuf);
}
else { /* read next byte as RunCount; repeat 0xFF runcount* */
c=ReadBlobByte(image);
if (c < 0)
break;
RunCount=(unsigned char) c;
for(i=0;i<(int) RunCount;i++) InsertByte(0xFF);
}
}
else {
if(RunCount) /* next runcount byte are readed directly */
{
for(i=0;i < (int) RunCount;i++)
{
bbuf=ReadBlobByte(image);
InsertByte(bbuf);
}
}
else { /* repeat previous line runcount* */
c=ReadBlobByte(image);
if (c < 0)
break;
RunCount=(unsigned char) c;
if(x) { /* attempt to duplicate row from x position: */
/* I do not know what to do here */
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-3);
}
for(i=0;i < (int) RunCount;i++)
{
x=0;
y++; /* Here I need to duplicate previous row RUNCOUNT* */
if(y<2) continue;
if(y>(ssize_t) image->rows)
{
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-4);
}
InsertRow(image,BImgBuff,y-1,bpp,exception);
}
}
}
if (EOFBlob(image) != MagickFalse)
break;
}
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(y <(ssize_t) image->rows ? -5 : 0);
}
/* Helper for WPG2 reader. */
#define InsertByte6(b) \
{ \
DisableMSCWarning(4310) \
if(XorMe)\
BImgBuff[x] = (unsigned char)~b;\
else\
BImgBuff[x] = b;\
RestoreMSCWarning \
x++; \
if((ssize_t) x >= ldblk) \
{ \
if (InsertRow(image,BImgBuff,(ssize_t) y,bpp,exception) != MagickFalse) \
y++; \
x=0; \
} \
}
/* WPG2 raster reader. */
static int UnpackWPG2Raster(Image *image,int bpp,ExceptionInfo *exception)
{
int
RunCount,
XorMe = 0;
size_t
x,
y;
ssize_t
i,
ldblk;
unsigned int
SampleSize=1;
unsigned char
bbuf,
*BImgBuff,
SampleBuffer[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
x=0;
y=0;
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
sizeof(*BImgBuff));
if(BImgBuff==NULL)
return(-2);
while( y< image->rows)
{
bbuf=ReadBlobByte(image);
switch(bbuf)
{
case 0x7D:
SampleSize=ReadBlobByte(image); /* DSZ */
if(SampleSize>8)
{
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-2);
}
if(SampleSize<1)
{
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-2);
}
break;
case 0x7E:
(void) FormatLocaleFile(stderr,
"\nUnsupported WPG token XOR, please report!");
XorMe=!XorMe;
break;
case 0x7F:
RunCount=ReadBlobByte(image); /* BLK */
if (RunCount < 0)
break;
for(i=0; i < SampleSize*(RunCount+1); i++)
{
InsertByte6(0);
}
break;
case 0xFD:
RunCount=ReadBlobByte(image); /* EXT */
if (RunCount < 0)
break;
for(i=0; i<= RunCount;i++)
for(bbuf=0; bbuf < SampleSize; bbuf++)
InsertByte6(SampleBuffer[bbuf]);
break;
case 0xFE:
RunCount=ReadBlobByte(image); /* RST */
if (RunCount < 0)
break;
if(x!=0)
{
(void) FormatLocaleFile(stderr,
"\nUnsupported WPG2 unaligned token RST x=%.20g, please report!\n"
,(double) x);
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-3);
}
{
/* duplicate the previous row RunCount x */
for(i=0;i<=RunCount;i++)
{
if (InsertRow(image,BImgBuff,(ssize_t) (image->rows >= y ? y : image->rows-1),
bpp,exception) != MagickFalse)
y++;
}
}
break;
case 0xFF:
RunCount=ReadBlobByte(image); /* WHT */
if (RunCount < 0)
break;
for(i=0; i < SampleSize*(RunCount+1); i++)
{
InsertByte6(0xFF);
}
break;
default:
RunCount=bbuf & 0x7F;
if(bbuf & 0x80) /* REP */
{
for(i=0; i < SampleSize; i++)
SampleBuffer[i]=ReadBlobByte(image);
for(i=0;i<=RunCount;i++)
for(bbuf=0;bbuf<SampleSize;bbuf++)
InsertByte6(SampleBuffer[bbuf]);
}
else { /* NRP */
for(i=0; i< SampleSize*(RunCount+1);i++)
{
bbuf=ReadBlobByte(image);
InsertByte6(bbuf);
}
}
}
if (EOFBlob(image) != MagickFalse)
break;
}
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(0);
}
typedef float tCTM[3][3];
static unsigned LoadWPG2Flags(Image *image,char Precision,float *Angle,tCTM *CTM)
{
const unsigned char TPR=1,TRN=2,SKW=4,SCL=8,ROT=0x10,OID=0x20,LCK=0x80;
ssize_t x;
unsigned DenX;
unsigned Flags;
(void) memset(*CTM,0,sizeof(*CTM)); /*CTM.erase();CTM.resize(3,3);*/
(*CTM)[0][0]=1;
(*CTM)[1][1]=1;
(*CTM)[2][2]=1;
Flags=ReadBlobLSBShort(image);
if(Flags & LCK) (void) ReadBlobLSBLong(image); /*Edit lock*/
if(Flags & OID)
{
if(Precision==0)
{(void) ReadBlobLSBShort(image);} /*ObjectID*/
else
{(void) ReadBlobLSBLong(image);} /*ObjectID (Double precision)*/
}
if(Flags & ROT)
{
x=ReadBlobLSBLong(image); /*Rot Angle*/
if(Angle) *Angle=x/65536.0;
}
if(Flags & (ROT|SCL))
{
x=ReadBlobLSBLong(image); /*Sx*cos()*/
(*CTM)[0][0] = (float)x/0x10000;
x=ReadBlobLSBLong(image); /*Sy*cos()*/
(*CTM)[1][1] = (float)x/0x10000;
}
if(Flags & (ROT|SKW))
{
x=ReadBlobLSBLong(image); /*Kx*sin()*/
(*CTM)[1][0] = (float)x/0x10000;
x=ReadBlobLSBLong(image); /*Ky*sin()*/
(*CTM)[0][1] = (float)x/0x10000;
}
if(Flags & TRN)
{
x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Tx*/
if(x>=0) (*CTM)[0][2] = (float)x+(float)DenX/0x10000;
else (*CTM)[0][2] = (float)x-(float)DenX/0x10000;
x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Ty*/
(*CTM)[1][2]=(float)x + ((x>=0)?1:-1)*(float)DenX/0x10000;
if(x>=0) (*CTM)[1][2] = (float)x+(float)DenX/0x10000;
else (*CTM)[1][2] = (float)x-(float)DenX/0x10000;
}
if(Flags & TPR)
{
x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Px*/
(*CTM)[2][0] = x + (float)DenX/0x10000;;
x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Py*/
(*CTM)[2][1] = x + (float)DenX/0x10000;
}
return(Flags);
}
static Image *ExtractPostscript(Image *image,const ImageInfo *image_info,
MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
char
postscript_file[MagickPathExtent];
const MagicInfo
*magic_info;
FILE
*ps_file;
ImageInfo
*clone_info;
Image
*image2;
unsigned char
magick[2*MagickPathExtent];
if ((clone_info=CloneImageInfo(image_info)) == NULL)
return(image);
clone_info->blob=(void *) NULL;
clone_info->length=0;
/* Obtain temporary file */
(void) AcquireUniqueFilename(postscript_file);
ps_file=fopen_utf8(postscript_file,"wb");
if (ps_file == (FILE *) NULL)
goto FINISH;
/* Copy postscript to temporary file */
(void) SeekBlob(image,PS_Offset,SEEK_SET);
(void) ReadBlob(image, 2*MagickPathExtent, magick);
(void) SeekBlob(image,PS_Offset,SEEK_SET);
while(PS_Size-- > 0)
{
(void) fputc(ReadBlobByte(image),ps_file);
}
(void) fclose(ps_file);
/* Detect file format - Check magic.mgk configuration file. */
magic_info=GetMagicInfo(magick,2*MagickPathExtent,exception);
if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
/* printf("Detected:%s \n",magic_info->name); */
if(exception->severity != UndefinedException) goto FINISH_UNL;
if(magic_info->name == (char *) NULL) goto FINISH_UNL;
(void) strncpy(clone_info->magick,magic_info->name,MagickPathExtent-1);
/* Read nested image */
/*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
FormatLocaleString(clone_info->filename,MagickPathExtent,"%s",postscript_file);
image2=ReadImage(clone_info,exception);
if (!image2)
goto FINISH_UNL;
/*
Replace current image with new image while copying base image
attributes.
*/
(void) CopyMagickString(image2->filename,image->filename,MagickPathExtent);
(void) CopyMagickString(image2->magick_filename,image->magick_filename,MagickPathExtent);
(void) CopyMagickString(image2->magick,image->magick,MagickPathExtent);
image2->depth=image->depth;
DestroyBlob(image2);
image2->blob=ReferenceBlob(image->blob);
if ((image->rows == 0) || (image->columns == 0))
DeleteImageFromList(&image);
AppendImageToList(&image,image2);
FINISH_UNL:
(void) RelinquishUniqueFileResource(postscript_file);
FINISH:
DestroyImageInfo(clone_info);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d W P G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method ReadWPGImage reads an WPG X image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadWPGImage method is:
%
% Image *ReadWPGImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: Method ReadWPGImage returns a pointer to the image after
% reading. A null image is returned if there is a memory shortage or if
% the image cannot be read.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadWPGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct
{
size_t FileId;
MagickOffsetType DataOffset;
unsigned int ProductType;
unsigned int FileType;
unsigned char MajorVersion;
unsigned char MinorVersion;
unsigned int EncryptKey;
unsigned int Reserved;
} WPGHeader;
typedef struct
{
unsigned char RecType;
size_t RecordLength;
} WPGRecord;
typedef struct
{
unsigned char Class;
unsigned char RecType;
size_t Extension;
size_t RecordLength;
} WPG2Record;
typedef struct
{
unsigned HorizontalUnits;
unsigned VerticalUnits;
unsigned char PosSizePrecision;
} WPG2Start;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType1;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned char Depth;
unsigned char Compression;
} WPG2BitmapType1;
typedef struct
{
unsigned int RotAngle;
unsigned int LowLeftX;
unsigned int LowLeftY;
unsigned int UpRightX;
unsigned int UpRightY;
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType2;
typedef struct
{
unsigned int StartIndex;
unsigned int NumOfEntries;
} WPGColorMapRec;
/*
typedef struct {
size_t PS_unknown1;
unsigned int PS_unknown2;
unsigned int PS_unknown3;
} WPGPSl1Record;
*/
Image
*image;
unsigned int
status;
WPGHeader
Header;
WPGRecord
Rec;
WPG2Record
Rec2;
WPG2Start StartWPG;
WPGBitmapType1
BitmapHeader1;
WPG2BitmapType1
Bitmap2Header1;
WPGBitmapType2
BitmapHeader2;
WPGColorMapRec
WPG_Palette;
int
i,
bpp,
WPG2Flags;
ssize_t
ldblk;
size_t
one;
unsigned char
*BImgBuff;
tCTM CTM; /*current transform matrix*/
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1;
image=AcquireImage(image_info,exception);
image->depth=8;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read WPG image.
*/
Header.FileId=ReadBlobLSBLong(image);
Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);
Header.ProductType=ReadBlobLSBShort(image);
Header.FileType=ReadBlobLSBShort(image);
Header.MajorVersion=ReadBlobByte(image);
Header.MinorVersion=ReadBlobByte(image);
Header.EncryptKey=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (Header.EncryptKey!=0)
ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported");
image->columns = 1;
image->rows = 1;
image->colors = 0;
bpp=0;
BitmapHeader2.RotAngle=0;
Rec2.RecordLength=0;
switch(Header.FileType)
{
case 1: /* WPG level 1 */
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec.RecordLength);
if (Rec.RecordLength > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec.RecordLength;
switch(Rec.RecType)
{
case 0x0B: /* bitmap type 1 */
BitmapHeader1.Width=ReadBlobLSBShort(image);
BitmapHeader1.Height=ReadBlobLSBShort(image);
if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader1.Depth=ReadBlobLSBShort(image);
BitmapHeader1.HorzRes=ReadBlobLSBShort(image);
BitmapHeader1.VertRes=ReadBlobLSBShort(image);
if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)
{
image->units=PixelsPerCentimeterResolution;
image->resolution.x=BitmapHeader1.HorzRes/470.0;
image->resolution.y=BitmapHeader1.VertRes/470.0;
}
image->columns=BitmapHeader1.Width;
image->rows=BitmapHeader1.Height;
bpp=BitmapHeader1.Depth;
goto UnpackRaster;
case 0x0E: /*Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) >
(Rec2.RecordLength-2-2)/3)
ThrowReaderException(CorruptImageError,"InvalidColormapIndex");
if (WPG_Palette.StartIndex > WPG_Palette.NumOfEntries)
ThrowReaderException(CorruptImageError,"InvalidColormapIndex");
image->colors=WPG_Palette.NumOfEntries;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
}
break;
case 0x11: /* Start PS l1 */
if(Rec.RecordLength > 8)
image=ExtractPostscript(image,image_info,
TellBlob(image)+8, /* skip PS header in the wpg */
(ssize_t) Rec.RecordLength-8,exception);
break;
case 0x14: /* bitmap type 2 */
BitmapHeader2.RotAngle=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);
BitmapHeader2.UpRightX=ReadBlobLSBShort(image);
BitmapHeader2.UpRightY=ReadBlobLSBShort(image);
BitmapHeader2.Width=ReadBlobLSBShort(image);
BitmapHeader2.Height=ReadBlobLSBShort(image);
if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader2.Depth=ReadBlobLSBShort(image);
BitmapHeader2.HorzRes=ReadBlobLSBShort(image);
BitmapHeader2.VertRes=ReadBlobLSBShort(image);
image->units=PixelsPerCentimeterResolution;
image->page.width=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);
image->page.height=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);
image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);
image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);
if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)
{
image->resolution.x=BitmapHeader2.HorzRes/470.0;
image->resolution.y=BitmapHeader2.VertRes/470.0;
}
image->columns=BitmapHeader2.Width;
image->rows=BitmapHeader2.Height;
bpp=BitmapHeader2.Depth;
UnpackRaster:
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
if ((image->colors == 0) && (bpp <= 16))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
{
NoMemory:
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
/* printf("Load default colormap \n"); */
for (i=0; (i < (int) image->colors) && (i < 256); i++)
{
image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);
image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);
image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);
}
}
else
{
if (bpp < 24)
if ( (image->colors < (one << bpp)) && (bpp != 24) )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
if (bpp == 1)
{
if(image->colormap[0].red==0 &&
image->colormap[0].green==0 &&
image->colormap[0].blue==0 &&
image->colormap[1].red==0 &&
image->colormap[1].green==0 &&
image->colormap[1].blue==0)
{ /* fix crippled monochrome palette */
image->colormap[1].red =
image->colormap[1].green =
image->colormap[1].blue = QuantumRange;
}
}
if(UnpackWPGRaster(image,bpp,exception) < 0)
/* The raster cannot be unpacked */
{
DecompressionFailed:
ThrowReaderException(CoderError,"UnableToDecompressImage");
}
if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)
{
/* flop command */
if(BitmapHeader2.RotAngle & 0x8000)
{
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
ReplaceImageInList(&image,flop_image);
}
}
/* flip command */
if(BitmapHeader2.RotAngle & 0x2000)
{
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
ReplaceImageInList(&image,flip_image);
}
}
/* rotate command */
if(BitmapHeader2.RotAngle & 0x0FFF)
{
Image
*rotate_image;
rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &
0x0FFF), exception);
if (rotate_image != (Image *) NULL) {
DuplicateBlob(rotate_image,image);
ReplaceImageInList(&image,rotate_image);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x1B: /* Postscript l2 */
if(Rec.RecordLength>0x3C)
image=ExtractPostscript(image,image_info,
TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */
(ssize_t) Rec.RecordLength-0x3C,exception);
break;
}
}
break;
case 2: /* WPG level 2 */
(void) memset(CTM,0,sizeof(CTM));
StartWPG.PosSizePrecision = 0;
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec2.Class=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rec2.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec2.Extension);
Rd_WP_DWORD(image,&Rec2.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec2.RecordLength;
switch(Rec2.RecType)
{
case 1:
StartWPG.HorizontalUnits=ReadBlobLSBShort(image);
StartWPG.VerticalUnits=ReadBlobLSBShort(image);
StartWPG.PosSizePrecision=ReadBlobByte(image);
break;
case 0x0C: /* Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) >
(Rec2.RecordLength-2-2) / 3)
ThrowReaderException(CorruptImageError,"InvalidColormapIndex");
image->colors=WPG_Palette.NumOfEntries;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((char)
ReadBlobByte(image));
(void) ReadBlobByte(image); /*Opacity??*/
}
break;
case 0x0E:
Bitmap2Header1.Width=ReadBlobLSBShort(image);
Bitmap2Header1.Height=ReadBlobLSBShort(image);
if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
Bitmap2Header1.Depth=ReadBlobByte(image);
Bitmap2Header1.Compression=ReadBlobByte(image);
if(Bitmap2Header1.Compression > 1)
continue; /*Unknown compression method */
switch(Bitmap2Header1.Depth)
{
case 1:
bpp=1;
break;
case 2:
bpp=2;
break;
case 3:
bpp=4;
break;
case 4:
bpp=8;
break;
case 8:
bpp=24;
break;
default:
continue; /*Ignore raster with unknown depth*/
}
image->columns=Bitmap2Header1.Width;
image->rows=Bitmap2Header1.Height;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
switch(Bitmap2Header1.Compression)
{
case 0: /*Uncompressed raster*/
{
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)
ldblk+1,sizeof(*BImgBuff));
if (BImgBuff == (unsigned char *) NULL)
goto NoMemory;
for(i=0; i< (ssize_t) image->rows; i++)
{
(void) ReadBlob(image,ldblk,BImgBuff);
InsertRow(image,BImgBuff,i,bpp,exception);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp,exception) < 0)
goto DecompressionFailed;
break;
}
}
if(CTM[0][0]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
ReplaceImageInList(&image,flop_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0;
Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);
Tx(1,2)=0; Tx(2,2)=1; */
}
if(CTM[1][1]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
ReplaceImageInList(&image,flip_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
float_matrix Tx(3,3);
Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0;
Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);
Tx(2,2)=1; */
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x12: /* Postscript WPG2*/
i=ReadBlobLSBShort(image);
if(Rec2.RecordLength > (unsigned int) i)
image=ExtractPostscript(image,image_info,
TellBlob(image)+i, /*skip PS header in the wpg2*/
(ssize_t) (Rec2.RecordLength-i-2),exception);
break;
case 0x1B: /*bitmap rectangle*/
WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);
(void) WPG2Flags;
break;
}
}
break;
default:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
}
}
Finish:
(void) CloseBlob(image);
{
Image
*p;
ssize_t
scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers.
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=(size_t) scene++;
}
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r W P G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method RegisterWPGImage adds attributes for the WPG 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 RegisterWPGImage method is:
%
% size_t RegisterWPGImage(void)
%
*/
ModuleExport size_t RegisterWPGImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("WPG","WPG","Word Perfect Graphics");
entry->decoder=(DecodeImageHandler *) ReadWPGImage;
entry->magick=(IsImageFormatHandler *) IsWPG;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r W P G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method UnregisterWPGImage removes format registrations made by the
% WPG module from the list of supported formats.
%
% The format of the UnregisterWPGImage method is:
%
% UnregisterWPGImage(void)
%
*/
ModuleExport void UnregisterWPGImage(void)
{
(void) UnregisterMagickInfo("WPG");
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2918_0 |
crossvul-cpp_data_good_341_3 | /*
* card-tcos.c: Support for TCOS cards
*
* Copyright (C) 2011 Peter Koch <pk@opensc-project.org>
* Copyright (C) 2002 g10 Code GmbH
* Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static struct sc_atr_table tcos_atrs[] = {
/* Infineon SLE44 */
{ "3B:BA:13:00:81:31:86:5D:00:64:05:0A:02:01:31:80:90:00:8B", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66S */
{ "3B:BA:14:00:81:31:86:5D:00:64:05:14:02:02:31:80:90:00:91", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX320P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:60:02:03:31:80:90:00:66", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX322P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:7B:02:03:31:80:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Philips P5CT072 */
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:03:01:31:C0:73:F7:01:D0:00:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:04:0F:31:C0:73:F7:01:D0:00:90:00:74", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
/* Philips P5CT080 */
{ "3B:BF:B6:00:81:31:FE:5D:00:64:04:28:03:02:31:C0:73:F7:01:D0:00:90:00:67", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
static struct sc_card_operations tcos_ops;
static struct sc_card_driver tcos_drv = {
"TCOS 3.0",
"tcos",
&tcos_ops,
NULL, 0, NULL
};
static const struct sc_card_operations *iso_ops = NULL;
typedef struct tcos_data_st {
unsigned int pad_flags;
unsigned int next_sign;
} tcos_data;
static int tcos_finish(sc_card_t *card)
{
free(card->drv_data);
return 0;
}
static int tcos_match_card(sc_card_t *card)
{
int i;
i = _sc_match_atr(card, tcos_atrs, &card->type);
if (i < 0)
return 0;
return 1;
}
static int tcos_init(sc_card_t *card)
{
unsigned long flags;
tcos_data *data = malloc(sizeof(tcos_data));
if (!data) return SC_ERROR_OUT_OF_MEMORY;
card->name = "TCOS";
card->drv_data = (void *)data;
card->cla = 0x00;
flags = SC_ALGORITHM_RSA_RAW;
flags |= SC_ALGORITHM_RSA_PAD_PKCS1;
flags |= SC_ALGORITHM_RSA_HASH_NONE;
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 768, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
if (card->type == SC_CARD_TYPE_TCOS_V3) {
card->caps |= SC_CARD_CAP_APDU_EXT;
_sc_card_add_rsa_alg(card, 1280, flags, 0);
_sc_card_add_rsa_alg(card, 1536, flags, 0);
_sc_card_add_rsa_alg(card, 1792, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
return 0;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static int tcos_construct_fci(const sc_file_t *file,
u8 *out, size_t *outlen)
{
u8 *p = out;
u8 buf[64];
size_t n;
/* FIXME: possible buffer overflow */
*p++ = 0x6F; /* FCI */
p++;
/* File size */
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x81, buf, 2, p, 16, &p);
/* File descriptor */
n = 0;
buf[n] = file->shareable ? 0x40 : 0;
switch (file->type) {
case SC_FILE_TYPE_WORKING_EF:
break;
case SC_FILE_TYPE_DF:
buf[0] |= 0x38;
break;
default:
return SC_ERROR_NOT_SUPPORTED;
}
buf[n++] |= file->ef_structure & 7;
if ( (file->ef_structure & 7) > 1) {
/* record structured file */
buf[n++] = 0x41; /* indicate 3rd byte */
buf[n++] = file->record_length;
}
sc_asn1_put_tag(0x82, buf, n, p, 8, &p);
/* File identifier */
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, 16, &p);
/* Directory name */
if (file->type == SC_FILE_TYPE_DF) {
if (file->namelen) {
sc_asn1_put_tag(0x84, file->name, file->namelen,
p, 16, &p);
}
else {
/* TCOS needs one, so we use a faked one */
snprintf ((char *) buf, sizeof(buf)-1, "foo-%lu",
(unsigned long) time (NULL));
sc_asn1_put_tag(0x84, buf, strlen ((char *) buf), p, 16, &p);
}
}
/* File descriptor extension */
if (file->prop_attr_len && file->prop_attr) {
n = file->prop_attr_len;
memcpy(buf, file->prop_attr, n);
}
else {
n = 0;
buf[n++] = 0x01; /* not invalidated, permanent */
if (file->type == SC_FILE_TYPE_WORKING_EF)
buf[n++] = 0x00; /* generic data file */
}
sc_asn1_put_tag(0x85, buf, n, p, 16, &p);
/* Security attributes */
if (file->sec_attr_len && file->sec_attr) {
memcpy(buf, file->sec_attr, file->sec_attr_len);
n = file->sec_attr_len;
}
else {
/* no attributes given - fall back to default one */
memcpy (buf+ 0, "\xa4\x00\x00\x00\xff\xff", 6); /* select */
memcpy (buf+ 6, "\xb0\x00\x00\x00\xff\xff", 6); /* read bin */
memcpy (buf+12, "\xd6\x00\x00\x00\xff\xff", 6); /* upd bin */
memcpy (buf+18, "\x60\x00\x00\x00\xff\xff", 6); /* admin grp*/
n = 24;
}
sc_asn1_put_tag(0x86, buf, n, p, sizeof (buf), &p);
/* fixup length of FCI */
out[1] = p - out - 2;
*outlen = p - out;
return 0;
}
static int tcos_create_file(sc_card_t *card, sc_file_t *file)
{
int r;
size_t len;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_apdu_t apdu;
len = SC_MAX_APDU_BUFFER_SIZE;
r = tcos_construct_fci(file, sbuf, &len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "tcos_construct_fci() failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00);
apdu.cla |= 0x80; /* this is an proprietary extension */
apdu.lc = len;
apdu.datalen = len;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static unsigned int map_operations (int commandbyte )
{
unsigned int op = (unsigned int)-1;
switch ( (commandbyte & 0xfe) ) {
case 0xe2: /* append record */ op = SC_AC_OP_UPDATE; break;
case 0x24: /* change password */ op = SC_AC_OP_UPDATE; break;
case 0xe0: /* create */ op = SC_AC_OP_CREATE; break;
case 0xe4: /* delete */ op = SC_AC_OP_DELETE; break;
case 0xe8: /* exclude sfi */ op = SC_AC_OP_WRITE; break;
case 0x82: /* external auth */ op = SC_AC_OP_READ; break;
case 0xe6: /* include sfi */ op = SC_AC_OP_WRITE; break;
case 0x88: /* internal auth */ op = SC_AC_OP_READ; break;
case 0x04: /* invalidate */ op = SC_AC_OP_INVALIDATE; break;
case 0x2a: /* perform sec. op */ op = SC_AC_OP_SELECT; break;
case 0xb0: /* read binary */ op = SC_AC_OP_READ; break;
case 0xb2: /* read record */ op = SC_AC_OP_READ; break;
case 0x44: /* rehabilitate */ op = SC_AC_OP_REHABILITATE; break;
case 0xa4: /* select */ op = SC_AC_OP_SELECT; break;
case 0xee: /* set permanent */ op = SC_AC_OP_CREATE; break;
case 0x2c: /* unblock password */op = SC_AC_OP_WRITE; break;
case 0xd6: /* update binary */ op = SC_AC_OP_WRITE; break;
case 0xdc: /* update record */ op = SC_AC_OP_WRITE; break;
case 0x20: /* verify password */ op = SC_AC_OP_SELECT; break;
case 0x60: /* admin group */ op = SC_AC_OP_CREATE; break;
}
return op;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static void parse_sec_attr(sc_card_t *card,
sc_file_t *file, const u8 *buf, size_t len)
{
unsigned int op;
/* list directory is not covered by ACLs - so always add an entry */
sc_file_add_acl_entry (file, SC_AC_OP_LIST_FILES,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
/* FIXME: check for what LOCK is used */
sc_file_add_acl_entry (file, SC_AC_OP_LOCK,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
for (; len >= 6; len -= 6, buf += 6) {
/* FIXME: temporary hacks */
if (!memcmp(buf, "\xa4\x00\x00\x00\xff\xff", 6)) /* select */
sc_file_add_acl_entry (file, SC_AC_OP_SELECT,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\xb0\x00\x00\x00\xff\xff", 6)) /*read*/
sc_file_add_acl_entry (file, SC_AC_OP_READ,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\xd6\x00\x00\x00\xff\xff", 6)) /*upd*/
sc_file_add_acl_entry (file, SC_AC_OP_UPDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\x60\x00\x00\x00\xff\xff", 6)) {/*adm */
sc_file_add_acl_entry (file, SC_AC_OP_WRITE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_CREATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_INVALIDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_REHABILITATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
}
else {
/* the first byte tells use the command or the
command group. We have to mask bit 0
because this one distinguish between AND/OR
combination of PINs*/
op = map_operations (buf[0]);
if (op == (unsigned int)-1)
{
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Unknown security command byte %02x\n",
buf[0]);
continue;
}
if (!buf[1])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_CHV, buf[1]);
if (!buf[2] && !buf[3])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_TERM,
(buf[2]<<8)|buf[3]);
}
}
}
static int tcos_select_file(sc_card_t *card,
const sc_path_t *in_path,
sc_file_t **file_out)
{
sc_context_t *ctx;
sc_apdu_t apdu;
sc_file_t *file=NULL;
u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
unsigned int i;
int r, pathlen;
assert(card != NULL && in_path != NULL);
ctx=card->ctx;
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS;
/* fall through */
case SC_PATH_TYPE_FROM_CURRENT:
apdu.p1 = 9;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
case SC_PATH_TYPE_PATH:
apdu.p1 = 8;
if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2;
if (pathlen == 0) apdu.p1 = 0;
break;
case SC_PATH_TYPE_PARENT:
apdu.p1 = 3;
pathlen = 0;
break;
default:
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 256;
} else {
apdu.resplen = 0;
apdu.le = 0;
apdu.p2 = 0x0C;
apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r);
if (apdu.resplen < 1 || apdu.resp[0] != 0x62){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
file = sc_file_new();
if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
*file_out = file;
file->path = *in_path;
for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){
size_t j, len=apdu.resp[i+1];
unsigned char type=apdu.resp[i], *d=apdu.resp+i+2;
switch (type) {
case 0x80:
case 0x81:
file->size=0;
for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j];
break;
case 0x82:
file->shareable = (d[0] & 0x40) ? 1 : 0;
file->ef_structure = d[0] & 7;
switch ((d[0]>>3) & 7) {
case 0: file->type = SC_FILE_TYPE_WORKING_EF; break;
case 7: file->type = SC_FILE_TYPE_DF; break;
default:
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
break;
case 0x83:
file->id = (d[0]<<8) | d[1];
break;
case 0x84:
file->namelen = MIN(sizeof file->name, len);
memcpy(file->name, d, file->namelen);
break;
case 0x86:
sc_file_set_sec_attr(file, d, len);
break;
default:
if (len>0) sc_file_set_prop_attr(file, d, len);
}
}
file->magic = SC_FILE_MAGIC;
parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len);
return 0;
}
static int tcos_list_files(sc_card_t *card, u8 *buf, size_t buflen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE], p1;
int r, count = 0;
assert(card != NULL);
ctx = card->ctx;
for (p1=1; p1<=2; p1++) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, p1, 0);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1==0x6A && (apdu.sw2==0x82 || apdu.sw2==0x88)) continue;
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "List Dir failed");
if (apdu.resplen > buflen) return SC_ERROR_BUFFER_TOO_SMALL;
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"got %"SC_FORMAT_LEN_SIZE_T"u %s-FileIDs\n",
apdu.resplen / 2, p1 == 1 ? "DF" : "EF");
memcpy(buf, apdu.resp, apdu.resplen);
buf += apdu.resplen;
buflen -= apdu.resplen;
count += apdu.resplen;
}
return count;
}
static int tcos_delete_file(sc_card_t *card, const sc_path_t *path)
{
int r;
u8 sbuf[2];
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (path->type != SC_PATH_TYPE_FILE_ID && path->len != 2) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File type has to be SC_PATH_TYPE_FILE_ID\n");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
sbuf[0] = path->value[0];
sbuf[1] = path->value[1];
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p;
int r, default_key, tcos3;
tcos_data *data;
assert(card != NULL && env != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
if (se_num || (env->operation!=SC_SEC_OPERATION_DECIPHER && env->operation!=SC_SEC_OPERATION_SIGN)){
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
if(!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT))
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"No Key-Reference in SecEnvironment\n");
else
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Key-Reference %02X (len=%"SC_FORMAT_LEN_SIZE_T"u)\n",
env->key_ref[0], env->key_ref_len);
/* Key-Reference 0x80 ?? */
default_key= !(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len==1 && env->key_ref[0]==0x80);
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"TCOS3:%d PKCS1:%d\n", tcos3,
!!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
data->pad_flags = env->algorithm_flags;
data->next_sign = default_key;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, tcos3 ? 0x41 : 0xC1, 0xB8);
p = sbuf;
*p++=0x80; *p++=0x01; *p++=tcos3 ? 0x0A : 0x10;
if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) {
*p++ = (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) ? 0x83 : 0x84;
*p++ = env->key_ref_len;
memcpy(p, env->key_ref, env->key_ref_len);
p += env->key_ref_len;
}
apdu.data = sbuf;
apdu.lc = apdu.datalen = (p - sbuf);
r=sc_transmit_apdu(card, &apdu);
if (r) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"%s: APDU transmit failed", sc_strerror(r));
return r;
}
if (apdu.sw1==0x6A && (apdu.sw2==0x81 || apdu.sw2==0x88)) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Detected Signature-Only key\n");
if (env->operation==SC_SEC_OPERATION_SIGN && default_key) return SC_SUCCESS;
}
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_restore_security_env(sc_card_t *card, int se_num)
{
return 0;
}
static int tcos_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen)
{
size_t i, dlen=datalen;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
int tcos3, r;
assert(card != NULL && data != NULL && out != NULL);
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
if (datalen > 255) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
if(((tcos_data *)card->drv_data)->next_sign){
if(datalen>48){
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Data to be signed is too long (TCOS supports max. 48 bytes)\n");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A);
memcpy(sbuf, data, datalen);
dlen=datalen;
} else {
int keylen= tcos3 ? 256 : 128;
sc_format_apdu(card, &apdu, keylen>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
}
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = tcos3 ? 256 : 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (tcos3 && apdu.p1==0x80 && apdu.sw1==0x6A && apdu.sw2==0x87) {
int keylen=128;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
}
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len = apdu.resplen>outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
tcos_data *data;
int tcos3, r;
assert(card != NULL && crgram != NULL && out != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_NORMAL);
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"TCOS3:%d PKCS1:%d\n",tcos3,
!!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = crgram_len;
apdu.data = sbuf;
apdu.lc = apdu.datalen = crgram_len+1;
sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02);
memcpy(sbuf+1, crgram, crgram_len);
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen;
unsigned int offset=0;
if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2){
offset=2; while(offset<len && apdu.resp[offset]!=0) ++offset;
offset=(offset<len-1) ? offset+1 : 0;
}
memcpy(out, apdu.resp+offset, len-offset);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
/* Issue the SET PERMANENT command. With ENABLE_NULLPIN set the
NullPIN method will be activated, otherwise the permanent operation
will be done on the active file. */
static int tcos_setperm(sc_card_t *card, int enable_nullpin)
{
int r;
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xEE, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 0;
apdu.datalen = 0;
apdu.data = NULL;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial)
{
int r;
if (!serial)
return SC_ERROR_INVALID_ARGUMENTS;
/* see if we have cached serial number */
if (card->serialnr.len) {
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
card->serialnr.len = sizeof card->serialnr.value;
r = sc_parse_ef_gdo(card, card->serialnr.value, &card->serialnr.len, NULL, 0);
if (r < 0) {
card->serialnr.len = 0;
return r;
}
/* copy and return serial number */
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
static int tcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
switch (cmd) {
case SC_CARDCTL_TCOS_SETPERM:
return tcos_setperm(card, !!ptr);
case SC_CARDCTL_GET_SERIALNR:
return tcos_get_serialnr(card, (sc_serial_number_t *)ptr);
}
return SC_ERROR_NOT_SUPPORTED;
}
struct sc_card_driver * sc_get_tcos_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL) iso_ops = iso_drv->ops;
tcos_ops = *iso_drv->ops;
tcos_ops.match_card = tcos_match_card;
tcos_ops.init = tcos_init;
tcos_ops.finish = tcos_finish;
tcos_ops.create_file = tcos_create_file;
tcos_ops.set_security_env = tcos_set_security_env;
tcos_ops.select_file = tcos_select_file;
tcos_ops.list_files = tcos_list_files;
tcos_ops.delete_file = tcos_delete_file;
tcos_ops.set_security_env = tcos_set_security_env;
tcos_ops.compute_signature = tcos_compute_signature;
tcos_ops.decipher = tcos_decipher;
tcos_ops.restore_security_env = tcos_restore_security_env;
tcos_ops.card_ctl = tcos_card_ctl;
return &tcos_drv;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_341_3 |
crossvul-cpp_data_bad_343_10 | /*
* util.c: utility functions used by OpenSC command line tools.
*
* Copyright (C) 2011 OpenSC Project developers
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#ifndef _WIN32
#include <termios.h>
#else
#include <conio.h>
#endif
#include <ctype.h>
#include "util.h"
#include "ui/notify.h"
int
is_string_valid_atr(const char *atr_str)
{
unsigned char atr[SC_MAX_ATR_SIZE];
size_t atr_len = sizeof(atr);
if (sc_hex_to_bin(atr_str, atr, &atr_len))
return 0;
if (atr_len < 2)
return 0;
if (atr[0] != 0x3B && atr[0] != 0x3F)
return 0;
return 1;
}
int
util_connect_card_ex(sc_context_t *ctx, sc_card_t **cardp,
const char *reader_id, int do_wait, int do_lock, int verbose)
{
struct sc_reader *reader = NULL, *found = NULL;
struct sc_card *card = NULL;
int r;
sc_notify_init();
if (do_wait) {
unsigned int event;
if (sc_ctx_get_reader_count(ctx) == 0) {
fprintf(stderr, "Waiting for a reader to be attached...\n");
r = sc_wait_for_event(ctx, SC_EVENT_READER_ATTACHED, &found, &event, -1, NULL);
if (r < 0) {
fprintf(stderr, "Error while waiting for a reader: %s\n", sc_strerror(r));
return 3;
}
r = sc_ctx_detect_readers(ctx);
if (r < 0) {
fprintf(stderr, "Error while refreshing readers: %s\n", sc_strerror(r));
return 3;
}
}
fprintf(stderr, "Waiting for a card to be inserted...\n");
r = sc_wait_for_event(ctx, SC_EVENT_CARD_INSERTED, &found, &event, -1, NULL);
if (r < 0) {
fprintf(stderr, "Error while waiting for a card: %s\n", sc_strerror(r));
return 3;
}
reader = found;
}
else if (sc_ctx_get_reader_count(ctx) == 0) {
fprintf(stderr, "No smart card readers found.\n");
return 1;
}
else {
if (!reader_id) {
unsigned int i;
/* Automatically try to skip to a reader with a card if reader not specified */
for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) {
reader = sc_ctx_get_reader(ctx, i);
if (sc_detect_card_presence(reader) & SC_READER_CARD_PRESENT) {
fprintf(stderr, "Using reader with a card: %s\n", reader->name);
goto autofound;
}
}
/* If no reader had a card, default to the first reader */
reader = sc_ctx_get_reader(ctx, 0);
}
else {
/* If the reader identifier looks like an ATR, try to find the reader with that card */
if (is_string_valid_atr(reader_id)) {
unsigned char atr_buf[SC_MAX_ATR_SIZE];
size_t atr_buf_len = sizeof(atr_buf);
unsigned int i;
sc_hex_to_bin(reader_id, atr_buf, &atr_buf_len);
/* Loop readers, looking for a card with ATR */
for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) {
struct sc_reader *rdr = sc_ctx_get_reader(ctx, i);
if (!(sc_detect_card_presence(rdr) & SC_READER_CARD_PRESENT))
continue;
else if (rdr->atr.len != atr_buf_len)
continue;
else if (memcmp(rdr->atr.value, atr_buf, rdr->atr.len))
continue;
fprintf(stderr, "Matched ATR in reader: %s\n", rdr->name);
reader = rdr;
goto autofound;
}
}
else {
char *endptr = NULL;
unsigned int num;
errno = 0;
num = strtol(reader_id, &endptr, 0);
if (!errno && endptr && *endptr == '\0')
reader = sc_ctx_get_reader(ctx, num);
else
reader = sc_ctx_get_reader_by_name(ctx, reader_id);
}
}
autofound:
if (!reader) {
fprintf(stderr, "Reader \"%s\" not found (%d reader(s) detected)\n",
reader_id, sc_ctx_get_reader_count(ctx));
return 1;
}
if (sc_detect_card_presence(reader) <= 0) {
fprintf(stderr, "Card not present.\n");
return 3;
}
}
if (verbose)
printf("Connecting to card in reader %s...\n", reader->name);
r = sc_connect_card(reader, &card);
if (r < 0) {
fprintf(stderr, "Failed to connect to card: %s\n", sc_strerror(r));
return 1;
}
if (verbose)
printf("Using card driver %s.\n", card->driver->name);
if (do_lock) {
r = sc_lock(card);
if (r < 0) {
fprintf(stderr, "Failed to lock card: %s\n", sc_strerror(r));
sc_disconnect_card(card);
return 1;
}
}
*cardp = card;
return 0;
}
int
util_connect_card(sc_context_t *ctx, sc_card_t **cardp,
const char *reader_id, int do_wait, int verbose)
{
return util_connect_card_ex(ctx, cardp, reader_id, do_wait, 1, verbose);
}
void util_print_binary(FILE *f, const u8 *buf, int count)
{
int i;
for (i = 0; i < count; i++) {
unsigned char c = buf[i];
const char *format;
if (!isprint(c))
format = "\\x%02X";
else
format = "%c";
fprintf(f, format, c);
}
(void) fflush(f);
}
void util_hex_dump(FILE *f, const u8 *in, int len, const char *sep)
{
int i;
for (i = 0; i < len; i++) {
if (sep != NULL && i)
fprintf(f, "%s", sep);
fprintf(f, "%02X", in[i]);
}
}
void util_hex_dump_asc(FILE *f, const u8 *in, size_t count, int addr)
{
int lines = 0;
while (count) {
char ascbuf[17];
size_t i;
if (addr >= 0) {
fprintf(f, "%08X: ", addr);
addr += 16;
}
for (i = 0; i < count && i < 16; i++) {
fprintf(f, "%02X ", *in);
if (isprint(*in))
ascbuf[i] = *in;
else
ascbuf[i] = '.';
in++;
}
count -= i;
ascbuf[i] = 0;
for (; i < 16 && lines; i++)
fprintf(f, " ");
fprintf(f, "%s\n", ascbuf);
lines++;
}
}
NORETURN void
util_print_usage_and_die(const char *app_name, const struct option options[],
const char *option_help[], const char *args)
{
int i;
int header_shown = 0;
if (args)
printf("Usage: %s [OPTIONS] %s\n", app_name, args);
else
printf("Usage: %s [OPTIONS]\n", app_name);
for (i = 0; options[i].name; i++) {
char buf[40];
const char *arg_str;
/* Skip "hidden" options */
if (option_help[i] == NULL)
continue;
if (!header_shown++)
printf("Options:\n");
switch (options[i].has_arg) {
case 1:
arg_str = " <arg>";
break;
case 2:
arg_str = " [arg]";
break;
default:
arg_str = "";
break;
}
if (isascii(options[i].val) &&
isprint(options[i].val) && !isspace(options[i].val))
sprintf(buf, "-%c, --%s%s", options[i].val, options[i].name, arg_str);
else
sprintf(buf, " --%s%s", options[i].name, arg_str);
/* print the line - wrap if necessary */
if (strlen(buf) > 28) {
printf(" %s\n", buf);
buf[0] = '\0';
}
printf(" %-28s %s\n", buf, option_help[i]);
}
exit(2);
}
const char * util_acl_to_str(const sc_acl_entry_t *e)
{
static char line[80], buf[20];
unsigned int acl;
if (e == NULL)
return "N/A";
line[0] = 0;
while (e != NULL) {
acl = e->method;
switch (acl) {
case SC_AC_UNKNOWN:
return "N/A";
case SC_AC_NEVER:
return "NEVR";
case SC_AC_NONE:
return "NONE";
case SC_AC_CHV:
strcpy(buf, "CHV");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "%d", e->key_ref);
break;
case SC_AC_TERM:
strcpy(buf, "TERM");
break;
case SC_AC_PRO:
strcpy(buf, "PROT");
break;
case SC_AC_AUT:
strcpy(buf, "AUTH");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 4, "%d", e->key_ref);
break;
case SC_AC_SEN:
strcpy(buf, "Sec.Env. ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
case SC_AC_SCB:
strcpy(buf, "Sec.ControlByte ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "Ox%X", e->key_ref);
break;
case SC_AC_IDA:
strcpy(buf, "PKCS#15 AuthID ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
default:
strcpy(buf, "????");
break;
}
strcat(line, buf);
strcat(line, " ");
e = e->next;
}
line[strlen(line)-1] = 0; /* get rid of trailing space */
return line;
}
NORETURN void
util_fatal(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\nAborting.\n");
va_end(ap);
sc_notify_close();
exit(1);
}
void
util_error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
void
util_warn(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "warning: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
int
util_getpass (char **lineptr, size_t *len, FILE *stream)
{
#define MAX_PASS_SIZE 128
char *buf;
size_t i;
int ch = 0;
#ifndef _WIN32
struct termios old, new;
fflush(stdout);
if (tcgetattr (fileno (stdout), &old) != 0)
return -1;
new = old;
new.c_lflag &= ~ECHO;
if (tcsetattr (fileno (stdout), TCSAFLUSH, &new) != 0)
return -1;
#endif
buf = calloc(1, MAX_PASS_SIZE);
if (!buf)
return -1;
for (i = 0; i < MAX_PASS_SIZE - 1; i++) {
#ifndef _WIN32
ch = getchar();
#else
ch = _getch();
#endif
if (ch == 0 || ch == 3)
break;
if (ch == '\n' || ch == '\r')
break;
buf[i] = (char) ch;
}
#ifndef _WIN32
tcsetattr (fileno (stdout), TCSAFLUSH, &old);
fputs("\n", stdout);
#endif
if (ch == 0 || ch == 3) {
free(buf);
return -1;
}
if (*lineptr && (!len || *len < i+1)) {
free(*lineptr);
*lineptr = NULL;
}
if (*lineptr) {
memcpy(*lineptr,buf,i+1);
memset(buf, 0, MAX_PASS_SIZE);
free(buf);
} else {
*lineptr = buf;
if (len)
*len = MAX_PASS_SIZE;
}
return i;
}
size_t
util_get_pin(const char *input, const char **pin)
{
size_t inputlen = strlen(input);
size_t pinlen = 0;
if(inputlen > 4 && strncasecmp(input, "env:", 4) == 0) {
// Get a PIN from a environment variable
*pin = getenv(input + 4);
pinlen = *pin ? strlen(*pin) : 0;
} else {
//Just use the input
*pin = input;
pinlen = inputlen;
}
return pinlen;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_343_10 |
crossvul-cpp_data_bad_3445_0 | /*********************************************************************
*
* Filename: iriap.c
* Version: 0.8
* Description: Information Access Protocol (IAP)
* Status: Experimental.
* Author: Dag Brattli <dagb@cs.uit.no>
* Created at: Thu Aug 21 00:02:07 1997
* Modified at: Sat Dec 25 16:42:42 1999
* Modified by: Dag Brattli <dagb@cs.uit.no>
*
* Copyright (c) 1998-1999 Dag Brattli <dagb@cs.uit.no>,
* All Rights Reserved.
* Copyright (c) 2000-2003 Jean Tourrilhes <jt@hpl.hp.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.
*
* Neither Dag Brattli nor University of Tromsø admit liability nor
* provide warranty for any of this software. This material is
* provided "AS-IS" and at no charge.
*
********************************************************************/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/skbuff.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <asm/byteorder.h>
#include <asm/unaligned.h>
#include <net/irda/irda.h>
#include <net/irda/irttp.h>
#include <net/irda/irlmp.h>
#include <net/irda/irias_object.h>
#include <net/irda/iriap_event.h>
#include <net/irda/iriap.h>
#ifdef CONFIG_IRDA_DEBUG
/* FIXME: This one should go in irlmp.c */
static const char *const ias_charset_types[] = {
"CS_ASCII",
"CS_ISO_8859_1",
"CS_ISO_8859_2",
"CS_ISO_8859_3",
"CS_ISO_8859_4",
"CS_ISO_8859_5",
"CS_ISO_8859_6",
"CS_ISO_8859_7",
"CS_ISO_8859_8",
"CS_ISO_8859_9",
"CS_UNICODE"
};
#endif /* CONFIG_IRDA_DEBUG */
static hashbin_t *iriap = NULL;
static void *service_handle;
static void __iriap_close(struct iriap_cb *self);
static int iriap_register_lsap(struct iriap_cb *self, __u8 slsap_sel, int mode);
static void iriap_disconnect_indication(void *instance, void *sap,
LM_REASON reason, struct sk_buff *skb);
static void iriap_connect_indication(void *instance, void *sap,
struct qos_info *qos, __u32 max_sdu_size,
__u8 max_header_size,
struct sk_buff *skb);
static void iriap_connect_confirm(void *instance, void *sap,
struct qos_info *qos,
__u32 max_sdu_size, __u8 max_header_size,
struct sk_buff *skb);
static int iriap_data_indication(void *instance, void *sap,
struct sk_buff *skb);
static void iriap_watchdog_timer_expired(void *data);
static inline void iriap_start_watchdog_timer(struct iriap_cb *self,
int timeout)
{
irda_start_timer(&self->watchdog_timer, timeout, self,
iriap_watchdog_timer_expired);
}
/*
* Function iriap_init (void)
*
* Initializes the IrIAP layer, called by the module initialization code
* in irmod.c
*/
int __init iriap_init(void)
{
struct ias_object *obj;
struct iriap_cb *server;
__u8 oct_seq[6];
__u16 hints;
/* Allocate master array */
iriap = hashbin_new(HB_LOCK);
if (!iriap)
return -ENOMEM;
/* Object repository - defined in irias_object.c */
irias_objects = hashbin_new(HB_LOCK);
if (!irias_objects) {
IRDA_WARNING("%s: Can't allocate irias_objects hashbin!\n",
__func__);
hashbin_delete(iriap, NULL);
return -ENOMEM;
}
/*
* Register some default services for IrLMP
*/
hints = irlmp_service_to_hint(S_COMPUTER);
service_handle = irlmp_register_service(hints);
/* Register the Device object with LM-IAS */
obj = irias_new_object("Device", IAS_DEVICE_ID);
irias_add_string_attrib(obj, "DeviceName", "Linux", IAS_KERNEL_ATTR);
oct_seq[0] = 0x01; /* Version 1 */
oct_seq[1] = 0x00; /* IAS support bits */
oct_seq[2] = 0x00; /* LM-MUX support bits */
#ifdef CONFIG_IRDA_ULTRA
oct_seq[2] |= 0x04; /* Connectionless Data support */
#endif
irias_add_octseq_attrib(obj, "IrLMPSupport", oct_seq, 3,
IAS_KERNEL_ATTR);
irias_insert_object(obj);
/*
* Register server support with IrLMP so we can accept incoming
* connections
*/
server = iriap_open(LSAP_IAS, IAS_SERVER, NULL, NULL);
if (!server) {
IRDA_DEBUG(0, "%s(), unable to open server\n", __func__);
return -1;
}
iriap_register_lsap(server, LSAP_IAS, IAS_SERVER);
return 0;
}
/*
* Function iriap_cleanup (void)
*
* Initializes the IrIAP layer, called by the module cleanup code in
* irmod.c
*/
void iriap_cleanup(void)
{
irlmp_unregister_service(service_handle);
hashbin_delete(iriap, (FREE_FUNC) __iriap_close);
hashbin_delete(irias_objects, (FREE_FUNC) __irias_delete_object);
}
/*
* Function iriap_open (void)
*
* Opens an instance of the IrIAP layer, and registers with IrLMP
*/
struct iriap_cb *iriap_open(__u8 slsap_sel, int mode, void *priv,
CONFIRM_CALLBACK callback)
{
struct iriap_cb *self;
IRDA_DEBUG(2, "%s()\n", __func__);
self = kzalloc(sizeof(*self), GFP_ATOMIC);
if (!self) {
IRDA_WARNING("%s: Unable to kmalloc!\n", __func__);
return NULL;
}
/*
* Initialize instance
*/
self->magic = IAS_MAGIC;
self->mode = mode;
if (mode == IAS_CLIENT)
iriap_register_lsap(self, slsap_sel, mode);
self->confirm = callback;
self->priv = priv;
/* iriap_getvaluebyclass_request() will construct packets before
* we connect, so this must have a sane value... Jean II */
self->max_header_size = LMP_MAX_HEADER;
init_timer(&self->watchdog_timer);
hashbin_insert(iriap, (irda_queue_t *) self, (long) self, NULL);
/* Initialize state machines */
iriap_next_client_state(self, S_DISCONNECT);
iriap_next_call_state(self, S_MAKE_CALL);
iriap_next_server_state(self, R_DISCONNECT);
iriap_next_r_connect_state(self, R_WAITING);
return self;
}
EXPORT_SYMBOL(iriap_open);
/*
* Function __iriap_close (self)
*
* Removes (deallocates) the IrIAP instance
*
*/
static void __iriap_close(struct iriap_cb *self)
{
IRDA_DEBUG(4, "%s()\n", __func__);
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IAS_MAGIC, return;);
del_timer(&self->watchdog_timer);
if (self->request_skb)
dev_kfree_skb(self->request_skb);
self->magic = 0;
kfree(self);
}
/*
* Function iriap_close (void)
*
* Closes IrIAP and deregisters with IrLMP
*/
void iriap_close(struct iriap_cb *self)
{
struct iriap_cb *entry;
IRDA_DEBUG(2, "%s()\n", __func__);
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IAS_MAGIC, return;);
if (self->lsap) {
irlmp_close_lsap(self->lsap);
self->lsap = NULL;
}
entry = (struct iriap_cb *) hashbin_remove(iriap, (long) self, NULL);
IRDA_ASSERT(entry == self, return;);
__iriap_close(self);
}
EXPORT_SYMBOL(iriap_close);
static int iriap_register_lsap(struct iriap_cb *self, __u8 slsap_sel, int mode)
{
notify_t notify;
IRDA_DEBUG(2, "%s()\n", __func__);
irda_notify_init(¬ify);
notify.connect_confirm = iriap_connect_confirm;
notify.connect_indication = iriap_connect_indication;
notify.disconnect_indication = iriap_disconnect_indication;
notify.data_indication = iriap_data_indication;
notify.instance = self;
if (mode == IAS_CLIENT)
strcpy(notify.name, "IrIAS cli");
else
strcpy(notify.name, "IrIAS srv");
self->lsap = irlmp_open_lsap(slsap_sel, ¬ify, 0);
if (self->lsap == NULL) {
IRDA_ERROR("%s: Unable to allocated LSAP!\n", __func__);
return -1;
}
self->slsap_sel = self->lsap->slsap_sel;
return 0;
}
/*
* Function iriap_disconnect_indication (handle, reason)
*
* Got disconnect, so clean up everything associated with this connection
*
*/
static void iriap_disconnect_indication(void *instance, void *sap,
LM_REASON reason,
struct sk_buff *skb)
{
struct iriap_cb *self;
IRDA_DEBUG(4, "%s(), reason=%s\n", __func__, irlmp_reasons[reason]);
self = (struct iriap_cb *) instance;
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IAS_MAGIC, return;);
IRDA_ASSERT(iriap != NULL, return;);
del_timer(&self->watchdog_timer);
/* Not needed */
if (skb)
dev_kfree_skb(skb);
if (self->mode == IAS_CLIENT) {
IRDA_DEBUG(4, "%s(), disconnect as client\n", __func__);
iriap_do_client_event(self, IAP_LM_DISCONNECT_INDICATION,
NULL);
/*
* Inform service user that the request failed by sending
* it a NULL value. Warning, the client might close us, so
* remember no to use self anymore after calling confirm
*/
if (self->confirm)
self->confirm(IAS_DISCONNECT, 0, NULL, self->priv);
} else {
IRDA_DEBUG(4, "%s(), disconnect as server\n", __func__);
iriap_do_server_event(self, IAP_LM_DISCONNECT_INDICATION,
NULL);
iriap_close(self);
}
}
/*
* Function iriap_disconnect_request (handle)
*/
static void iriap_disconnect_request(struct iriap_cb *self)
{
struct sk_buff *tx_skb;
IRDA_DEBUG(4, "%s()\n", __func__);
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IAS_MAGIC, return;);
tx_skb = alloc_skb(LMP_MAX_HEADER, GFP_ATOMIC);
if (tx_skb == NULL) {
IRDA_DEBUG(0,
"%s(), Could not allocate an sk_buff of length %d\n",
__func__, LMP_MAX_HEADER);
return;
}
/*
* Reserve space for MUX control and LAP header
*/
skb_reserve(tx_skb, LMP_MAX_HEADER);
irlmp_disconnect_request(self->lsap, tx_skb);
}
/*
* Function iriap_getvaluebyclass (addr, name, attr)
*
* Retrieve all values from attribute in all objects with given class
* name
*/
int iriap_getvaluebyclass_request(struct iriap_cb *self,
__u32 saddr, __u32 daddr,
char *name, char *attr)
{
struct sk_buff *tx_skb;
int name_len, attr_len, skb_len;
__u8 *frame;
IRDA_ASSERT(self != NULL, return -1;);
IRDA_ASSERT(self->magic == IAS_MAGIC, return -1;);
/* Client must supply the destination device address */
if (!daddr)
return -1;
self->daddr = daddr;
self->saddr = saddr;
/*
* Save operation, so we know what the later indication is about
*/
self->operation = GET_VALUE_BY_CLASS;
/* Give ourselves 10 secs to finish this operation */
iriap_start_watchdog_timer(self, 10*HZ);
name_len = strlen(name); /* Up to IAS_MAX_CLASSNAME = 60 */
attr_len = strlen(attr); /* Up to IAS_MAX_ATTRIBNAME = 60 */
skb_len = self->max_header_size+2+name_len+1+attr_len+4;
tx_skb = alloc_skb(skb_len, GFP_ATOMIC);
if (!tx_skb)
return -ENOMEM;
/* Reserve space for MUX and LAP header */
skb_reserve(tx_skb, self->max_header_size);
skb_put(tx_skb, 3+name_len+attr_len);
frame = tx_skb->data;
/* Build frame */
frame[0] = IAP_LST | GET_VALUE_BY_CLASS;
frame[1] = name_len; /* Insert length of name */
memcpy(frame+2, name, name_len); /* Insert name */
frame[2+name_len] = attr_len; /* Insert length of attr */
memcpy(frame+3+name_len, attr, attr_len); /* Insert attr */
iriap_do_client_event(self, IAP_CALL_REQUEST_GVBC, tx_skb);
/* Drop reference count - see state_s_disconnect(). */
dev_kfree_skb(tx_skb);
return 0;
}
EXPORT_SYMBOL(iriap_getvaluebyclass_request);
/*
* Function iriap_getvaluebyclass_confirm (self, skb)
*
* Got result from GetValueByClass command. Parse it and return result
* to service user.
*
*/
static void iriap_getvaluebyclass_confirm(struct iriap_cb *self,
struct sk_buff *skb)
{
struct ias_value *value;
int charset;
__u32 value_len;
__u32 tmp_cpu32;
__u16 obj_id;
__u16 len;
__u8 type;
__u8 *fp;
int n;
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IAS_MAGIC, return;);
IRDA_ASSERT(skb != NULL, return;);
/* Initialize variables */
fp = skb->data;
n = 2;
/* Get length, MSB first */
len = get_unaligned_be16(fp + n);
n += 2;
IRDA_DEBUG(4, "%s(), len=%d\n", __func__, len);
/* Get object ID, MSB first */
obj_id = get_unaligned_be16(fp + n);
n += 2;
type = fp[n++];
IRDA_DEBUG(4, "%s(), Value type = %d\n", __func__, type);
switch (type) {
case IAS_INTEGER:
memcpy(&tmp_cpu32, fp+n, 4); n += 4;
be32_to_cpus(&tmp_cpu32);
value = irias_new_integer_value(tmp_cpu32);
/* Legal values restricted to 0x01-0x6f, page 15 irttp */
IRDA_DEBUG(4, "%s(), lsap=%d\n", __func__, value->t.integer);
break;
case IAS_STRING:
charset = fp[n++];
switch (charset) {
case CS_ASCII:
break;
/* case CS_ISO_8859_1: */
/* case CS_ISO_8859_2: */
/* case CS_ISO_8859_3: */
/* case CS_ISO_8859_4: */
/* case CS_ISO_8859_5: */
/* case CS_ISO_8859_6: */
/* case CS_ISO_8859_7: */
/* case CS_ISO_8859_8: */
/* case CS_ISO_8859_9: */
/* case CS_UNICODE: */
default:
IRDA_DEBUG(0, "%s(), charset %s, not supported\n",
__func__, ias_charset_types[charset]);
/* Aborting, close connection! */
iriap_disconnect_request(self);
return;
/* break; */
}
value_len = fp[n++];
IRDA_DEBUG(4, "%s(), strlen=%d\n", __func__, value_len);
/* Make sure the string is null-terminated */
if (n + value_len < skb->len)
fp[n + value_len] = 0x00;
IRDA_DEBUG(4, "Got string %s\n", fp+n);
/* Will truncate to IAS_MAX_STRING bytes */
value = irias_new_string_value(fp+n);
break;
case IAS_OCT_SEQ:
value_len = get_unaligned_be16(fp + n);
n += 2;
/* Will truncate to IAS_MAX_OCTET_STRING bytes */
value = irias_new_octseq_value(fp+n, value_len);
break;
default:
value = irias_new_missing_value();
break;
}
/* Finished, close connection! */
iriap_disconnect_request(self);
/* Warning, the client might close us, so remember no to use self
* anymore after calling confirm
*/
if (self->confirm)
self->confirm(IAS_SUCCESS, obj_id, value, self->priv);
else {
IRDA_DEBUG(0, "%s(), missing handler!\n", __func__);
irias_delete_value(value);
}
}
/*
* Function iriap_getvaluebyclass_response ()
*
* Send answer back to remote LM-IAS
*
*/
static void iriap_getvaluebyclass_response(struct iriap_cb *self,
__u16 obj_id,
__u8 ret_code,
struct ias_value *value)
{
struct sk_buff *tx_skb;
int n;
__be32 tmp_be32;
__be16 tmp_be16;
__u8 *fp;
IRDA_DEBUG(4, "%s()\n", __func__);
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IAS_MAGIC, return;);
IRDA_ASSERT(value != NULL, return;);
IRDA_ASSERT(value->len <= 1024, return;);
/* Initialize variables */
n = 0;
/*
* We must adjust the size of the response after the length of the
* value. We add 32 bytes because of the 6 bytes for the frame and
* max 5 bytes for the value coding.
*/
tx_skb = alloc_skb(value->len + self->max_header_size + 32,
GFP_ATOMIC);
if (!tx_skb)
return;
/* Reserve space for MUX and LAP header */
skb_reserve(tx_skb, self->max_header_size);
skb_put(tx_skb, 6);
fp = tx_skb->data;
/* Build frame */
fp[n++] = GET_VALUE_BY_CLASS | IAP_LST;
fp[n++] = ret_code;
/* Insert list length (MSB first) */
tmp_be16 = htons(0x0001);
memcpy(fp+n, &tmp_be16, 2); n += 2;
/* Insert object identifier ( MSB first) */
tmp_be16 = cpu_to_be16(obj_id);
memcpy(fp+n, &tmp_be16, 2); n += 2;
switch (value->type) {
case IAS_STRING:
skb_put(tx_skb, 3 + value->len);
fp[n++] = value->type;
fp[n++] = 0; /* ASCII */
fp[n++] = (__u8) value->len;
memcpy(fp+n, value->t.string, value->len); n+=value->len;
break;
case IAS_INTEGER:
skb_put(tx_skb, 5);
fp[n++] = value->type;
tmp_be32 = cpu_to_be32(value->t.integer);
memcpy(fp+n, &tmp_be32, 4); n += 4;
break;
case IAS_OCT_SEQ:
skb_put(tx_skb, 3 + value->len);
fp[n++] = value->type;
tmp_be16 = cpu_to_be16(value->len);
memcpy(fp+n, &tmp_be16, 2); n += 2;
memcpy(fp+n, value->t.oct_seq, value->len); n+=value->len;
break;
case IAS_MISSING:
IRDA_DEBUG( 3, "%s: sending IAS_MISSING\n", __func__);
skb_put(tx_skb, 1);
fp[n++] = value->type;
break;
default:
IRDA_DEBUG(0, "%s(), type not implemented!\n", __func__);
break;
}
iriap_do_r_connect_event(self, IAP_CALL_RESPONSE, tx_skb);
/* Drop reference count - see state_r_execute(). */
dev_kfree_skb(tx_skb);
}
/*
* Function iriap_getvaluebyclass_indication (self, skb)
*
* getvaluebyclass is requested from peer LM-IAS
*
*/
static void iriap_getvaluebyclass_indication(struct iriap_cb *self,
struct sk_buff *skb)
{
struct ias_object *obj;
struct ias_attrib *attrib;
int name_len;
int attr_len;
char name[IAS_MAX_CLASSNAME + 1]; /* 60 bytes */
char attr[IAS_MAX_ATTRIBNAME + 1]; /* 60 bytes */
__u8 *fp;
int n;
IRDA_DEBUG(4, "%s()\n", __func__);
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IAS_MAGIC, return;);
IRDA_ASSERT(skb != NULL, return;);
fp = skb->data;
n = 1;
name_len = fp[n++];
memcpy(name, fp+n, name_len); n+=name_len;
name[name_len] = '\0';
attr_len = fp[n++];
memcpy(attr, fp+n, attr_len); n+=attr_len;
attr[attr_len] = '\0';
IRDA_DEBUG(4, "LM-IAS: Looking up %s: %s\n", name, attr);
obj = irias_find_object(name);
if (obj == NULL) {
IRDA_DEBUG(2, "LM-IAS: Object %s not found\n", name);
iriap_getvaluebyclass_response(self, 0x1235, IAS_CLASS_UNKNOWN,
&irias_missing);
return;
}
IRDA_DEBUG(4, "LM-IAS: found %s, id=%d\n", obj->name, obj->id);
attrib = irias_find_attrib(obj, attr);
if (attrib == NULL) {
IRDA_DEBUG(2, "LM-IAS: Attribute %s not found\n", attr);
iriap_getvaluebyclass_response(self, obj->id,
IAS_ATTRIB_UNKNOWN,
&irias_missing);
return;
}
/* We have a match; send the value. */
iriap_getvaluebyclass_response(self, obj->id, IAS_SUCCESS,
attrib->value);
}
/*
* Function iriap_send_ack (void)
*
* Currently not used
*
*/
void iriap_send_ack(struct iriap_cb *self)
{
struct sk_buff *tx_skb;
__u8 *frame;
IRDA_DEBUG(2, "%s()\n", __func__);
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IAS_MAGIC, return;);
tx_skb = alloc_skb(LMP_MAX_HEADER + 1, GFP_ATOMIC);
if (!tx_skb)
return;
/* Reserve space for MUX and LAP header */
skb_reserve(tx_skb, self->max_header_size);
skb_put(tx_skb, 1);
frame = tx_skb->data;
/* Build frame */
frame[0] = IAP_LST | IAP_ACK | self->operation;
irlmp_data_request(self->lsap, tx_skb);
}
void iriap_connect_request(struct iriap_cb *self)
{
int ret;
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IAS_MAGIC, return;);
ret = irlmp_connect_request(self->lsap, LSAP_IAS,
self->saddr, self->daddr,
NULL, NULL);
if (ret < 0) {
IRDA_DEBUG(0, "%s(), connect failed!\n", __func__);
self->confirm(IAS_DISCONNECT, 0, NULL, self->priv);
}
}
/*
* Function iriap_connect_confirm (handle, skb)
*
* LSAP connection confirmed!
*
*/
static void iriap_connect_confirm(void *instance, void *sap,
struct qos_info *qos, __u32 max_seg_size,
__u8 max_header_size,
struct sk_buff *skb)
{
struct iriap_cb *self;
self = (struct iriap_cb *) instance;
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IAS_MAGIC, return;);
IRDA_ASSERT(skb != NULL, return;);
self->max_data_size = max_seg_size;
self->max_header_size = max_header_size;
del_timer(&self->watchdog_timer);
iriap_do_client_event(self, IAP_LM_CONNECT_CONFIRM, skb);
/* Drop reference count - see state_s_make_call(). */
dev_kfree_skb(skb);
}
/*
* Function iriap_connect_indication ( handle, skb)
*
* Remote LM-IAS is requesting connection
*
*/
static void iriap_connect_indication(void *instance, void *sap,
struct qos_info *qos, __u32 max_seg_size,
__u8 max_header_size,
struct sk_buff *skb)
{
struct iriap_cb *self, *new;
IRDA_DEBUG(1, "%s()\n", __func__);
self = (struct iriap_cb *) instance;
IRDA_ASSERT(skb != NULL, return;);
IRDA_ASSERT(self != NULL, goto out;);
IRDA_ASSERT(self->magic == IAS_MAGIC, goto out;);
/* Start new server */
new = iriap_open(LSAP_IAS, IAS_SERVER, NULL, NULL);
if (!new) {
IRDA_DEBUG(0, "%s(), open failed\n", __func__);
goto out;
}
/* Now attach up the new "socket" */
new->lsap = irlmp_dup(self->lsap, new);
if (!new->lsap) {
IRDA_DEBUG(0, "%s(), dup failed!\n", __func__);
goto out;
}
new->max_data_size = max_seg_size;
new->max_header_size = max_header_size;
/* Clean up the original one to keep it in listen state */
irlmp_listen(self->lsap);
iriap_do_server_event(new, IAP_LM_CONNECT_INDICATION, skb);
out:
/* Drop reference count - see state_r_disconnect(). */
dev_kfree_skb(skb);
}
/*
* Function iriap_data_indication (handle, skb)
*
* Receives data from connection identified by handle from IrLMP
*
*/
static int iriap_data_indication(void *instance, void *sap,
struct sk_buff *skb)
{
struct iriap_cb *self;
__u8 *frame;
__u8 opcode;
IRDA_DEBUG(3, "%s()\n", __func__);
self = (struct iriap_cb *) instance;
IRDA_ASSERT(skb != NULL, return 0;);
IRDA_ASSERT(self != NULL, goto out;);
IRDA_ASSERT(self->magic == IAS_MAGIC, goto out;);
frame = skb->data;
if (self->mode == IAS_SERVER) {
/* Call server */
IRDA_DEBUG(4, "%s(), Calling server!\n", __func__);
iriap_do_r_connect_event(self, IAP_RECV_F_LST, skb);
goto out;
}
opcode = frame[0];
if (~opcode & IAP_LST) {
IRDA_WARNING("%s:, IrIAS multiframe commands or "
"results is not implemented yet!\n",
__func__);
goto out;
}
/* Check for ack frames since they don't contain any data */
if (opcode & IAP_ACK) {
IRDA_DEBUG(0, "%s() Got ack frame!\n", __func__);
goto out;
}
opcode &= ~IAP_LST; /* Mask away LST bit */
switch (opcode) {
case GET_INFO_BASE:
IRDA_DEBUG(0, "IrLMP GetInfoBaseDetails not implemented!\n");
break;
case GET_VALUE_BY_CLASS:
iriap_do_call_event(self, IAP_RECV_F_LST, NULL);
switch (frame[1]) {
case IAS_SUCCESS:
iriap_getvaluebyclass_confirm(self, skb);
break;
case IAS_CLASS_UNKNOWN:
IRDA_DEBUG(1, "%s(), No such class!\n", __func__);
/* Finished, close connection! */
iriap_disconnect_request(self);
/*
* Warning, the client might close us, so remember
* no to use self anymore after calling confirm
*/
if (self->confirm)
self->confirm(IAS_CLASS_UNKNOWN, 0, NULL,
self->priv);
break;
case IAS_ATTRIB_UNKNOWN:
IRDA_DEBUG(1, "%s(), No such attribute!\n", __func__);
/* Finished, close connection! */
iriap_disconnect_request(self);
/*
* Warning, the client might close us, so remember
* no to use self anymore after calling confirm
*/
if (self->confirm)
self->confirm(IAS_ATTRIB_UNKNOWN, 0, NULL,
self->priv);
break;
}
break;
default:
IRDA_DEBUG(0, "%s(), Unknown op-code: %02x\n", __func__,
opcode);
break;
}
out:
/* Cleanup - sub-calls will have done skb_get() as needed. */
dev_kfree_skb(skb);
return 0;
}
/*
* Function iriap_call_indication (self, skb)
*
* Received call to server from peer LM-IAS
*
*/
void iriap_call_indication(struct iriap_cb *self, struct sk_buff *skb)
{
__u8 *fp;
__u8 opcode;
IRDA_DEBUG(4, "%s()\n", __func__);
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IAS_MAGIC, return;);
IRDA_ASSERT(skb != NULL, return;);
fp = skb->data;
opcode = fp[0];
if (~opcode & 0x80) {
IRDA_WARNING("%s: IrIAS multiframe commands or results "
"is not implemented yet!\n", __func__);
return;
}
opcode &= 0x7f; /* Mask away LST bit */
switch (opcode) {
case GET_INFO_BASE:
IRDA_WARNING("%s: GetInfoBaseDetails not implemented yet!\n",
__func__);
break;
case GET_VALUE_BY_CLASS:
iriap_getvaluebyclass_indication(self, skb);
break;
}
/* skb will be cleaned up in iriap_data_indication */
}
/*
* Function iriap_watchdog_timer_expired (data)
*
* Query has taken too long time, so abort
*
*/
static void iriap_watchdog_timer_expired(void *data)
{
struct iriap_cb *self = (struct iriap_cb *) data;
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IAS_MAGIC, return;);
/* iriap_close(self); */
}
#ifdef CONFIG_PROC_FS
static const char *const ias_value_types[] = {
"IAS_MISSING",
"IAS_INTEGER",
"IAS_OCT_SEQ",
"IAS_STRING"
};
static inline struct ias_object *irias_seq_idx(loff_t pos)
{
struct ias_object *obj;
for (obj = (struct ias_object *) hashbin_get_first(irias_objects);
obj; obj = (struct ias_object *) hashbin_get_next(irias_objects)) {
if (pos-- == 0)
break;
}
return obj;
}
static void *irias_seq_start(struct seq_file *seq, loff_t *pos)
{
spin_lock_irq(&irias_objects->hb_spinlock);
return *pos ? irias_seq_idx(*pos - 1) : SEQ_START_TOKEN;
}
static void *irias_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
++*pos;
return (v == SEQ_START_TOKEN)
? (void *) hashbin_get_first(irias_objects)
: (void *) hashbin_get_next(irias_objects);
}
static void irias_seq_stop(struct seq_file *seq, void *v)
{
spin_unlock_irq(&irias_objects->hb_spinlock);
}
static int irias_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq, "LM-IAS Objects:\n");
else {
struct ias_object *obj = v;
struct ias_attrib *attrib;
IRDA_ASSERT(obj->magic == IAS_OBJECT_MAGIC, return -EINVAL;);
seq_printf(seq, "name: %s, id=%d\n",
obj->name, obj->id);
/* Careful for priority inversions here !
* All other uses of attrib spinlock are independent of
* the object spinlock, so we are safe. Jean II */
spin_lock(&obj->attribs->hb_spinlock);
/* List all attributes for this object */
for (attrib = (struct ias_attrib *) hashbin_get_first(obj->attribs);
attrib != NULL;
attrib = (struct ias_attrib *) hashbin_get_next(obj->attribs)) {
IRDA_ASSERT(attrib->magic == IAS_ATTRIB_MAGIC,
goto outloop; );
seq_printf(seq, " - Attribute name: \"%s\", ",
attrib->name);
seq_printf(seq, "value[%s]: ",
ias_value_types[attrib->value->type]);
switch (attrib->value->type) {
case IAS_INTEGER:
seq_printf(seq, "%d\n",
attrib->value->t.integer);
break;
case IAS_STRING:
seq_printf(seq, "\"%s\"\n",
attrib->value->t.string);
break;
case IAS_OCT_SEQ:
seq_printf(seq, "octet sequence (%d bytes)\n",
attrib->value->len);
break;
case IAS_MISSING:
seq_puts(seq, "missing\n");
break;
default:
seq_printf(seq, "type %d?\n",
attrib->value->type);
}
seq_putc(seq, '\n');
}
IRDA_ASSERT_LABEL(outloop:)
spin_unlock(&obj->attribs->hb_spinlock);
}
return 0;
}
static const struct seq_operations irias_seq_ops = {
.start = irias_seq_start,
.next = irias_seq_next,
.stop = irias_seq_stop,
.show = irias_seq_show,
};
static int irias_seq_open(struct inode *inode, struct file *file)
{
IRDA_ASSERT( irias_objects != NULL, return -EINVAL;);
return seq_open(file, &irias_seq_ops);
}
const struct file_operations irias_seq_fops = {
.owner = THIS_MODULE,
.open = irias_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
#endif /* PROC_FS */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3445_0 |
crossvul-cpp_data_bad_1611_4 | /* t1lib
*
* This file contains functions for reading PFA and PFB files.
*
* Copyright (c) 1998-2013 Eddie Kohler
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, subject to the
* conditions listed in the Click LICENSE file, which is available in full at
* http://github.com/kohler/click/blob/master/LICENSE. The conditions
* include: you must preserve this copyright notice, and you cannot mention
* the copyright holders in advertising related to the Software without
* their permission. The Software is provided WITHOUT ANY WARRANTY, EXPRESS
* OR IMPLIED. This notice is a summary of the Click LICENSE file; the
* license in that file is binding.
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "t1lib.h"
#ifdef __cplusplus
extern "C" {
#endif
#define PFA_ASCII 1
#define PFA_EEXEC_TEST 2
#define PFA_HEX 3
#define PFA_BINARY 4
/* This function returns the value (0-15) of a single hex digit. It returns
0 for an invalid hex digit. */
static int
hexval(char c)
{
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
else if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
else if (c >= '0' && c <= '9')
return c - '0';
else
return 0;
}
/* This function translates a string of hexadecimal digits into binary data.
We allow an odd number of digits. Returns length of binary data. */
static int
translate_hex_string(char *s, char *saved_orphan)
{
int c1 = *saved_orphan;
char *start = s;
char *t = s;
for (; *s; s++) {
if (isspace(*s))
continue;
if (c1) {
*t++ = (hexval(c1) << 4) + hexval(*s);
c1 = 0;
} else
c1 = *s;
}
*saved_orphan = c1;
return t - start;
}
/* This function returns 1 if the string contains all '0's. */
static int
all_zeroes(char *s)
{
if (*s == '\0' || *s == '\n')
return 0;
while (*s == '0')
s++;
return *s == '\0' || *s == '\n';
}
/* This function handles the entire file. */
#define LINESIZE 1024
void
process_pfa(FILE *ifp, const char *ifp_filename, struct font_reader *fr)
{
/* Loop until no more input. We need to look for `currentfile eexec' to
start eexec section (hex to binary conversion) and line of all zeros to
switch back to ASCII. */
/* Don't use fgets() in case line-endings are indicated by bare \r's, as
occurs in Macintosh fonts. */
/* 2.Aug.1999 - At the behest of Tom Kacvinsky <tjk@ams.org>, support
binary PFA fonts. */
char buffer[LINESIZE];
int c = 0;
int blocktyp = PFA_ASCII;
char saved_orphan = 0;
(void)ifp_filename;
while (c != EOF) {
char *line = buffer, *last = buffer;
int crlf = 0;
c = getc(ifp);
while (c != EOF && c != '\r' && c != '\n' && last < buffer + LINESIZE - 1) {
*last++ = c;
c = getc(ifp);
}
/* handle the end of the line */
if (last == buffer + LINESIZE - 1)
/* buffer overrun: don't append newline even if we have it */
ungetc(c, ifp);
else if (c == '\r' && blocktyp != PFA_BINARY) {
/* change CR or CR/LF into LF, unless reading binary data! (This
condition was wrong before, caused Thanh problems -
6.Mar.2001) */
c = getc(ifp);
if (c != '\n')
ungetc(c, ifp), crlf = 1;
else
crlf = 2;
*last++ = '\n';
} else if (c != EOF)
*last++ = c;
*last = 0;
/* now that we have the line, handle it */
if (blocktyp == PFA_ASCII) {
if (strncmp(line, "currentfile eexec", 17) == 0 && isspace(line[17])) {
char saved_p;
/* assert(line == buffer); */
for (line += 18; isspace(*line); line++)
/* nada */;
saved_p = *line;
*line = 0;
fr->output_ascii(buffer, line - buffer);
*line = saved_p;
blocktyp = PFA_EEXEC_TEST;
if (!*line)
continue;
} else {
fr->output_ascii(line, last - line);
continue;
}
}
/* check immediately after "currentfile eexec" for ASCII or binary */
if (blocktyp == PFA_EEXEC_TEST) {
/* 8.Feb.2004: fix bug if first character in a binary eexec block
is 0, reported by Werner Lemberg */
for (; line < last && isspace(*line); line++)
/* nada */;
if (line == last)
continue;
else if (last >= line + 4 && isxdigit(line[0]) && isxdigit(line[1])
&& isxdigit(line[2]) && isxdigit(line[3]))
blocktyp = PFA_HEX;
else
blocktyp = PFA_BINARY;
memmove(buffer, line, last - line + 1);
last = buffer + (last - line);
line = buffer;
/* patch up crlf fix */
if (blocktyp == PFA_BINARY && crlf) {
last[-1] = '\r';
if (crlf == 2)
*last++ = '\n';
}
}
/* blocktyp == PFA_HEX || blocktyp == PFA_BINARY */
if (all_zeroes(line)) { /* XXX not safe */
fr->output_ascii(line, last - line);
blocktyp = PFA_ASCII;
} else if (blocktyp == PFA_HEX) {
int len = translate_hex_string(line, &saved_orphan);
if (len)
fr->output_binary((unsigned char *)line, len);
} else
fr->output_binary((unsigned char *)line, last - line);
}
fr->output_end();
}
/* Process a PFB file. */
/* XXX Doesn't handle "currentfile eexec" as intelligently as process_pfa
does. */
static int
handle_pfb_ascii(struct font_reader *fr, char *line, int len)
{
/* Divide PFB_ASCII blocks into lines */
int start = 0;
while (1) {
int pos = start;
while (pos < len && line[pos] != '\n' && line[pos] != '\r')
pos++;
if (pos >= len) {
if (pos == start)
return 0;
else if (start == 0 && pos == LINESIZE - 1) {
line[pos] = 0;
fr->output_ascii(line, pos);
return 0;
} else {
memmove(line, line + start, pos - start);
return pos - start;
}
} else if (pos < len - 1 && line[pos] == '\r' && line[pos+1] == '\n') {
line[pos] = '\n';
line[pos+1] = 0;
fr->output_ascii(line + start, pos + 1 - start);
start = pos + 2;
} else {
char save = line[pos+1];
line[pos] = '\n';
line[pos+1] = 0;
fr->output_ascii(line + start, pos + 1 - start);
line[pos+1] = save;
start = pos + 1;
}
}
}
void
process_pfb(FILE *ifp, const char *ifp_filename, struct font_reader *fr)
{
int blocktyp = 0;
unsigned block_len = 0;
int c = 0;
unsigned filepos = 0;
int linepos = 0;
char line[LINESIZE];
while (1) {
while (block_len == 0) {
c = getc(ifp);
blocktyp = getc(ifp);
if (c != PFB_MARKER
|| (blocktyp != PFB_ASCII && blocktyp != PFB_BINARY
&& blocktyp != PFB_DONE)) {
if (c == EOF || blocktyp == EOF)
error("%s corrupted: no end-of-file marker", ifp_filename);
else
error("%s corrupted: bad block marker at position %u",
ifp_filename, filepos);
blocktyp = PFB_DONE;
}
if (blocktyp == PFB_DONE)
goto done;
block_len = getc(ifp) & 0xFF;
block_len |= (getc(ifp) & 0xFF) << 8;
block_len |= (getc(ifp) & 0xFF) << 16;
block_len |= (unsigned) (getc(ifp) & 0xFF) << 24;
if (feof(ifp)) {
error("%s corrupted: bad block length at position %u",
ifp_filename, filepos);
blocktyp = PFB_DONE;
goto done;
}
filepos += 6;
}
/* read the block in its entirety, in LINESIZE chunks */
while (block_len > 0) {
unsigned rest = LINESIZE - 1 - linepos; /* leave space for '\0' */
unsigned n = (block_len > rest ? rest : block_len);
int actual = fread(line + linepos, 1, n, ifp);
if (actual != (int) n) {
error("%s corrupted: block short by %u bytes at position %u",
ifp_filename, block_len - actual, filepos);
block_len = actual;
}
if (blocktyp == PFB_BINARY)
fr->output_binary((unsigned char *)line, actual);
else
linepos = handle_pfb_ascii(fr, line, linepos + actual);
block_len -= actual;
filepos += actual;
}
/* handle any leftover line */
if (linepos > 0) {
line[linepos] = 0;
fr->output_ascii(line, linepos);
linepos = 0;
}
}
done:
c = getc(ifp);
if (c != EOF)
error("%s corrupted: data after PFB end marker at position %u",
ifp_filename, filepos - 2);
fr->output_end();
}
#define DEFAULT_BLOCKLEN (1L<<12)
void
init_pfb_writer(struct pfb_writer *w, int blocklen, FILE *f)
{
w->len = DEFAULT_BLOCKLEN;
w->buf = (unsigned char *)malloc(w->len);
if (!w->buf)
fatal_error("out of memory");
w->max_len = (blocklen <= 0 ? 0xFFFFFFFFU : (unsigned)blocklen);
w->pos = 0;
w->blocktyp = PFB_ASCII;
w->binary_blocks_written = 0;
w->f = f;
}
void
pfb_writer_output_block(struct pfb_writer *w)
{
/* do nothing if nothing in block */
if (w->pos == 0)
return;
/* output four-byte block length */
putc(PFB_MARKER, w->f);
putc(w->blocktyp, w->f);
putc((int)(w->pos & 0xff), w->f);
putc((int)((w->pos >> 8) & 0xff), w->f);
putc((int)((w->pos >> 16) & 0xff), w->f);
putc((int)((w->pos >> 24) & 0xff), w->f);
/* output block data */
fwrite(w->buf, 1, w->pos, w->f);
/* mark block buffer empty and uninitialized */
w->pos = 0;
if (w->blocktyp == PFB_BINARY)
w->binary_blocks_written++;
}
void
pfb_writer_grow_buf(struct pfb_writer *w)
{
if (w->len < w->max_len) {
/* grow w->buf */
unsigned new_len = w->len * 2;
unsigned char *new_buf;
if (new_len > w->max_len)
new_len = w->max_len;
new_buf = (unsigned char *)malloc(new_len);
if (!new_buf) {
error("out of memory; continuing with a smaller block size");
w->max_len = w->len;
pfb_writer_output_block(w);
} else {
memcpy(new_buf, w->buf, w->len);
free(w->buf);
w->buf = new_buf;
w->len = new_len;
}
} else
/* buf already the right size, just output the block */
pfb_writer_output_block(w);
}
void
pfb_writer_end(struct pfb_writer *w)
{
if (w->pos)
pfb_writer_output_block(w);
putc(PFB_MARKER, w->f);
putc(PFB_DONE, w->f);
}
/* This CRC table and routine were borrowed from macutils-2.0b3 */
static unsigned short crctab[256] = {
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0,
};
/*
* Update a CRC check on the given buffer.
*/
int
crcbuf(int crc, unsigned int len, const char *buf)
{
const unsigned char *ubuf = (const unsigned char *)buf;
while (len--)
crc = ((crc << 8) & 0xFF00) ^ crctab[((crc >> 8) & 0xFF) ^ *ubuf++];
return crc;
}
#ifdef __cplusplus
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1611_4 |
crossvul-cpp_data_bad_4734_0 | /*
* helper functions for vmalloc video4linux capture buffers
*
* The functions expect the hardware being able to scatter gatter
* (i.e. the buffers are not linear in physical memory, but fragmented
* into PAGE_SIZE chunks). They also assume the driver does not need
* to touch the video data.
*
* (c) 2007 Mauro Carvalho Chehab, <mchehab@infradead.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
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include <linux/pagemap.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <media/videobuf-vmalloc.h>
#define MAGIC_DMABUF 0x17760309
#define MAGIC_VMAL_MEM 0x18221223
#define MAGIC_CHECK(is,should) if (unlikely((is) != (should))) \
{ printk(KERN_ERR "magic mismatch: %x (expected %x)\n",is,should); BUG(); }
static int debug = 0;
module_param(debug, int, 0644);
MODULE_DESCRIPTION("helper module to manage video4linux vmalloc buffers");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@infradead.org>");
MODULE_LICENSE("GPL");
#define dprintk(level, fmt, arg...) if (debug >= level) \
printk(KERN_DEBUG "vbuf-sg: " fmt , ## arg)
/***************************************************************************/
static void
videobuf_vm_open(struct vm_area_struct *vma)
{
struct videobuf_mapping *map = vma->vm_private_data;
dprintk(2,"vm_open %p [count=%d,vma=%08lx-%08lx]\n",map,
map->count,vma->vm_start,vma->vm_end);
map->count++;
}
static void
videobuf_vm_close(struct vm_area_struct *vma)
{
struct videobuf_mapping *map = vma->vm_private_data;
struct videobuf_queue *q = map->q;
int i;
dprintk(2,"vm_close %p [count=%d,vma=%08lx-%08lx]\n",map,
map->count,vma->vm_start,vma->vm_end);
map->count--;
if (0 == map->count) {
dprintk(1,"munmap %p q=%p\n",map,q);
mutex_lock(&q->lock);
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
if (NULL == q->bufs[i])
continue;
if (q->bufs[i]->map != map)
continue;
q->ops->buf_release(q,q->bufs[i]);
q->bufs[i]->map = NULL;
q->bufs[i]->baddr = 0;
}
mutex_unlock(&q->lock);
kfree(map);
}
return;
}
static struct vm_operations_struct videobuf_vm_ops =
{
.open = videobuf_vm_open,
.close = videobuf_vm_close,
};
/* ---------------------------------------------------------------------
* vmalloc handlers for the generic methods
*/
/* Allocated area consists on 3 parts:
struct video_buffer
struct <driver>_buffer (cx88_buffer, saa7134_buf, ...)
struct videobuf_pci_sg_memory
*/
static void *__videobuf_alloc(size_t size)
{
struct videbuf_vmalloc_memory *mem;
struct videobuf_buffer *vb;
vb = kzalloc(size+sizeof(*mem),GFP_KERNEL);
mem = vb->priv = ((char *)vb)+size;
mem->magic=MAGIC_VMAL_MEM;
dprintk(1,"%s: allocated at %p(%ld+%ld) & %p(%ld)\n",
__FUNCTION__,vb,(long)sizeof(*vb),(long)size-sizeof(*vb),
mem,(long)sizeof(*mem));
return vb;
}
static int __videobuf_iolock (struct videobuf_queue* q,
struct videobuf_buffer *vb,
struct v4l2_framebuffer *fbuf)
{
int pages;
struct videbuf_vmalloc_memory *mem=vb->priv;
BUG_ON(!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
pages = PAGE_ALIGN(vb->size) >> PAGE_SHIFT;
/* Currently, doesn't support V4L2_MEMORY_OVERLAY */
if ((vb->memory != V4L2_MEMORY_MMAP) &&
(vb->memory != V4L2_MEMORY_USERPTR) ) {
printk(KERN_ERR "Method currently unsupported.\n");
return -EINVAL;
}
/* FIXME: should be tested with kernel mmap mem */
mem->vmalloc=vmalloc_user (PAGE_ALIGN(vb->size));
if (NULL == mem->vmalloc) {
printk(KERN_ERR "vmalloc (%d pages) failed\n",pages);
return -ENOMEM;
}
dprintk(1,"vmalloc is at addr 0x%08lx, size=%d\n",
(unsigned long)mem->vmalloc,
pages << PAGE_SHIFT);
/* It seems that some kernel versions need to do remap *after*
the mmap() call
*/
if (mem->vma) {
int retval=remap_vmalloc_range(mem->vma, mem->vmalloc,0);
kfree(mem->vma);
mem->vma=NULL;
if (retval<0) {
dprintk(1,"mmap app bug: remap_vmalloc_range area %p error %d\n",
mem->vmalloc,retval);
return retval;
}
}
return 0;
}
static int __videobuf_sync(struct videobuf_queue *q,
struct videobuf_buffer *buf)
{
return 0;
}
static int __videobuf_mmap_free(struct videobuf_queue *q)
{
unsigned int i;
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
if (q->bufs[i]) {
if (q->bufs[i]->map)
return -EBUSY;
}
}
return 0;
}
static int __videobuf_mmap_mapper(struct videobuf_queue *q,
struct vm_area_struct *vma)
{
struct videbuf_vmalloc_memory *mem;
struct videobuf_mapping *map;
unsigned int first;
int retval;
unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
if (! (vma->vm_flags & VM_WRITE) || ! (vma->vm_flags & VM_SHARED))
return -EINVAL;
/* look for first buffer to map */
for (first = 0; first < VIDEO_MAX_FRAME; first++) {
if (NULL == q->bufs[first])
continue;
if (V4L2_MEMORY_MMAP != q->bufs[first]->memory)
continue;
if (q->bufs[first]->boff == offset)
break;
}
if (VIDEO_MAX_FRAME == first) {
dprintk(1,"mmap app bug: offset invalid [offset=0x%lx]\n",
(vma->vm_pgoff << PAGE_SHIFT));
return -EINVAL;
}
/* create mapping + update buffer list */
map = q->bufs[first]->map = kmalloc(sizeof(struct videobuf_mapping),GFP_KERNEL);
if (NULL == map)
return -ENOMEM;
map->start = vma->vm_start;
map->end = vma->vm_end;
map->q = q;
q->bufs[first]->baddr = vma->vm_start;
vma->vm_ops = &videobuf_vm_ops;
vma->vm_flags |= VM_DONTEXPAND | VM_RESERVED;
vma->vm_private_data = map;
mem=q->bufs[first]->priv;
BUG_ON (!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
/* Try to remap memory */
retval=remap_vmalloc_range(vma, mem->vmalloc,0);
if (retval<0) {
dprintk(1,"mmap: postponing remap_vmalloc_range\n");
mem->vma=kmalloc(sizeof(*vma),GFP_KERNEL);
if (!mem->vma) {
kfree(map);
q->bufs[first]->map=NULL;
return -ENOMEM;
}
memcpy(mem->vma,vma,sizeof(*vma));
}
dprintk(1,"mmap %p: q=%p %08lx-%08lx (%lx) pgoff %08lx buf %d\n",
map,q,vma->vm_start,vma->vm_end,
(long int) q->bufs[first]->bsize,
vma->vm_pgoff,first);
videobuf_vm_open(vma);
return (0);
}
static int __videobuf_copy_to_user ( struct videobuf_queue *q,
char __user *data, size_t count,
int nonblocking )
{
struct videbuf_vmalloc_memory *mem=q->read_buf->priv;
BUG_ON (!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
BUG_ON (!mem->vmalloc);
/* copy to userspace */
if (count > q->read_buf->size - q->read_off)
count = q->read_buf->size - q->read_off;
if (copy_to_user(data, mem->vmalloc+q->read_off, count))
return -EFAULT;
return count;
}
static int __videobuf_copy_stream ( struct videobuf_queue *q,
char __user *data, size_t count, size_t pos,
int vbihack, int nonblocking )
{
unsigned int *fc;
struct videbuf_vmalloc_memory *mem=q->read_buf->priv;
BUG_ON (!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
if (vbihack) {
/* dirty, undocumented hack -- pass the frame counter
* within the last four bytes of each vbi data block.
* We need that one to maintain backward compatibility
* to all vbi decoding software out there ... */
fc = (unsigned int*)mem->vmalloc;
fc += (q->read_buf->size>>2) -1;
*fc = q->read_buf->field_count >> 1;
dprintk(1,"vbihack: %d\n",*fc);
}
/* copy stuff using the common method */
count = __videobuf_copy_to_user (q,data,count,nonblocking);
if ( (count==-EFAULT) && (0 == pos) )
return -EFAULT;
return count;
}
static struct videobuf_qtype_ops qops = {
.magic = MAGIC_QTYPE_OPS,
.alloc = __videobuf_alloc,
.iolock = __videobuf_iolock,
.sync = __videobuf_sync,
.mmap_free = __videobuf_mmap_free,
.mmap_mapper = __videobuf_mmap_mapper,
.video_copy_to_user = __videobuf_copy_to_user,
.copy_stream = __videobuf_copy_stream,
};
void videobuf_queue_vmalloc_init(struct videobuf_queue* q,
struct videobuf_queue_ops *ops,
void *dev,
spinlock_t *irqlock,
enum v4l2_buf_type type,
enum v4l2_field field,
unsigned int msize,
void *priv)
{
videobuf_queue_core_init(q, ops, dev, irqlock, type, field, msize,
priv, &qops);
}
EXPORT_SYMBOL_GPL(videobuf_queue_vmalloc_init);
void *videobuf_to_vmalloc (struct videobuf_buffer *buf)
{
struct videbuf_vmalloc_memory *mem=buf->priv;
BUG_ON (!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
return mem->vmalloc;
}
EXPORT_SYMBOL_GPL(videobuf_to_vmalloc);
void videobuf_vmalloc_free (struct videobuf_buffer *buf)
{
struct videbuf_vmalloc_memory *mem=buf->priv;
BUG_ON (!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
vfree(mem->vmalloc);
mem->vmalloc=NULL;
return;
}
EXPORT_SYMBOL_GPL(videobuf_vmalloc_free);
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4734_0 |
crossvul-cpp_data_bad_4787_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% AAA AAA IIIII %
% A A A A I %
% AAAAA AAAAA I %
% A A A A I %
% A A A A IIIII %
% %
% %
% Read/Write AAI X Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.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/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteAAIImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d A A I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadAAIImage() reads an AAI Dune 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 ReadAAIImage method is:
%
% Image *ReadAAIImage(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 *ReadAAIImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register ssize_t
x;
register PixelPacket
*q;
register unsigned char
*p;
size_t
height,
length,
width;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read AAI Dune image.
*/
width=ReadBlobLSBLong(image);
height=ReadBlobLSBLong(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((width == 0UL) || (height == 0UL))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Convert AAI raster image to pixel packets.
*/
image->columns=width;
image->rows=height;
image->depth=8;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,
4*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
length=(size_t) 4*image->columns;
for (y=0; y < (ssize_t) image->rows; y++)
{
count=ReadBlob(image,length,pixels);
if ((size_t) count != length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
p=pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelBlue(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelRed(q,ScaleCharToQuantum(*p++));
if (*p == 254)
*p=255;
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
if (q->opacity != OpaqueOpacity)
image->matte=MagickTrue;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
width=ReadBlobLSBLong(image);
height=ReadBlobLSBLong(image);
if ((width != 0UL) && (height != 0UL))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((width != 0UL) && (height != 0UL));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r A A I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterAAIImage() adds attributes for the AAI Dune 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 RegisterAAIImage method is:
%
% size_t RegisterAAIImage(void)
%
*/
ModuleExport size_t RegisterAAIImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("AAI");
entry->decoder=(DecodeImageHandler *) ReadAAIImage;
entry->encoder=(EncodeImageHandler *) WriteAAIImage;
entry->description=ConstantString("AAI Dune image");
entry->module=ConstantString("AAI");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r A A I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterAAIImage() removes format registrations made by the
% AAI module from the list of supported formats.
%
% The format of the UnregisterAAIImage method is:
%
% UnregisterAAIImage(void)
%
*/
ModuleExport void UnregisterAAIImage(void)
{
(void) UnregisterMagickInfo("AAI");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e A A I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteAAIImage() writes an image to a file in AAI Dune image format.
%
% The format of the WriteAAIImage method is:
%
% MagickBooleanType WriteAAIImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteAAIImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
MagickOffsetType
scene;
register const PixelPacket
*restrict p;
register ssize_t
x;
register unsigned char
*restrict q;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
/*
Write AAI header.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
(void) WriteBlobLSBLong(image,(unsigned int) image->columns);
(void) WriteBlobLSBLong(image,(unsigned int) image->rows);
/*
Allocate memory for pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory((size_t) image->columns,
4*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert MIFF to AAI raster pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (PixelPacket *) NULL)
break;
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(p));
*q++=ScaleQuantumToChar(GetPixelGreen(p));
*q++=ScaleQuantumToChar(GetPixelRed(p));
*q=ScaleQuantumToChar((Quantum) (QuantumRange-(image->matte !=
MagickFalse ? GetPixelOpacity(p) : OpaqueOpacity)));
if (*q == 255)
*q=254;
p++;
q++;
}
count=WriteBlob(image,(size_t) (q-pixels),pixels);
if (count != (ssize_t) (q-pixels))
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4787_1 |
crossvul-cpp_data_bad_2593_1 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2593_1 |
crossvul-cpp_data_bad_5283_2 | /*
+----------------------------------------------------------------------+
| phar php single-file executable PHP extension |
| utility functions |
+----------------------------------------------------------------------+
| Copyright (c) 2005-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Gregory Beaver <cellog@php.net> |
| Marcus Boerger <helly@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "phar_internal.h"
#ifdef PHAR_HASH_OK
#include "ext/hash/php_hash_sha.h"
#endif
#ifdef PHAR_HAVE_OPENSSL
/* OpenSSL includes */
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/crypto.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/conf.h>
#include <openssl/rand.h>
#include <openssl/ssl.h>
#include <openssl/pkcs12.h>
#else
static int phar_call_openssl_signverify(int is_sign, php_stream *fp, zend_off_t end, char *key, int key_len, char **signature, int *signature_len);
#endif
/* for links to relative location, prepend cwd of the entry */
static char *phar_get_link_location(phar_entry_info *entry) /* {{{ */
{
char *p, *ret = NULL;
if (!entry->link) {
return NULL;
}
if (entry->link[0] == '/') {
return estrdup(entry->link + 1);
}
p = strrchr(entry->filename, '/');
if (p) {
*p = '\0';
spprintf(&ret, 0, "%s/%s", entry->filename, entry->link);
return ret;
}
return entry->link;
}
/* }}} */
phar_entry_info *phar_get_link_source(phar_entry_info *entry) /* {{{ */
{
phar_entry_info *link_entry;
char *link;
if (!entry->link) {
return entry;
}
link = phar_get_link_location(entry);
if (NULL != (link_entry = zend_hash_str_find_ptr(&(entry->phar->manifest), entry->link, strlen(entry->link))) ||
NULL != (link_entry = zend_hash_str_find_ptr(&(entry->phar->manifest), link, strlen(link)))) {
if (link != entry->link) {
efree(link);
}
return phar_get_link_source(link_entry);
} else {
if (link != entry->link) {
efree(link);
}
return NULL;
}
}
/* }}} */
/* retrieve a phar_entry_info's current file pointer for reading contents */
php_stream *phar_get_efp(phar_entry_info *entry, int follow_links) /* {{{ */
{
if (follow_links && entry->link) {
phar_entry_info *link_entry = phar_get_link_source(entry);
if (link_entry && link_entry != entry) {
return phar_get_efp(link_entry, 1);
}
}
if (phar_get_fp_type(entry) == PHAR_FP) {
if (!phar_get_entrypfp(entry)) {
/* re-open just in time for cases where our refcount reached 0 on the phar archive */
phar_open_archive_fp(entry->phar);
}
return phar_get_entrypfp(entry);
} else if (phar_get_fp_type(entry) == PHAR_UFP) {
return phar_get_entrypufp(entry);
} else if (entry->fp_type == PHAR_MOD) {
return entry->fp;
} else {
/* temporary manifest entry */
if (!entry->fp) {
entry->fp = php_stream_open_wrapper(entry->tmp, "rb", STREAM_MUST_SEEK|0, NULL);
}
return entry->fp;
}
}
/* }}} */
int phar_seek_efp(phar_entry_info *entry, zend_off_t offset, int whence, zend_off_t position, int follow_links) /* {{{ */
{
php_stream *fp = phar_get_efp(entry, follow_links);
zend_off_t temp, eoffset;
if (!fp) {
return -1;
}
if (follow_links) {
phar_entry_info *t;
t = phar_get_link_source(entry);
if (t) {
entry = t;
}
}
if (entry->is_dir) {
return 0;
}
eoffset = phar_get_fp_offset(entry);
switch (whence) {
case SEEK_END:
temp = eoffset + entry->uncompressed_filesize + offset;
break;
case SEEK_CUR:
temp = eoffset + position + offset;
break;
case SEEK_SET:
temp = eoffset + offset;
break;
default:
temp = 0;
}
if (temp > eoffset + (zend_off_t) entry->uncompressed_filesize) {
return -1;
}
if (temp < eoffset) {
return -1;
}
return php_stream_seek(fp, temp, SEEK_SET);
}
/* }}} */
/* mount an absolute path or uri to a path internal to the phar archive */
int phar_mount_entry(phar_archive_data *phar, char *filename, int filename_len, char *path, int path_len) /* {{{ */
{
phar_entry_info entry = {0};
php_stream_statbuf ssb;
int is_phar;
const char *err;
if (phar_path_check(&path, &path_len, &err) > pcr_is_ok) {
return FAILURE;
}
if (path_len >= sizeof(".phar")-1 && !memcmp(path, ".phar", sizeof(".phar")-1)) {
/* no creating magic phar files by mounting them */
return FAILURE;
}
is_phar = (filename_len > 7 && !memcmp(filename, "phar://", 7));
entry.phar = phar;
entry.filename = estrndup(path, path_len);
#ifdef PHP_WIN32
phar_unixify_path_separators(entry.filename, path_len);
#endif
entry.filename_len = path_len;
if (is_phar) {
entry.tmp = estrndup(filename, filename_len);
} else {
entry.tmp = expand_filepath(filename, NULL);
if (!entry.tmp) {
entry.tmp = estrndup(filename, filename_len);
}
}
#if PHP_API_VERSION < 20100412
if (PG(safe_mode) && !is_phar && (!php_checkuid(entry.tmp, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
efree(entry.tmp);
efree(entry.filename);
return FAILURE;
}
#endif
filename = entry.tmp;
/* only check openbasedir for files, not for phar streams */
if (!is_phar && php_check_open_basedir(filename)) {
efree(entry.tmp);
efree(entry.filename);
return FAILURE;
}
entry.is_mounted = 1;
entry.is_crc_checked = 1;
entry.fp_type = PHAR_TMP;
if (SUCCESS != php_stream_stat_path(filename, &ssb)) {
efree(entry.tmp);
efree(entry.filename);
return FAILURE;
}
if (ssb.sb.st_mode & S_IFDIR) {
entry.is_dir = 1;
if (NULL == zend_hash_str_add_ptr(&phar->mounted_dirs, entry.filename, path_len, entry.filename)) {
/* directory already mounted */
efree(entry.tmp);
efree(entry.filename);
return FAILURE;
}
} else {
entry.is_dir = 0;
entry.uncompressed_filesize = entry.compressed_filesize = ssb.sb.st_size;
}
entry.flags = ssb.sb.st_mode;
if (NULL != zend_hash_str_add_mem(&phar->manifest, entry.filename, path_len, (void*)&entry, sizeof(phar_entry_info))) {
return SUCCESS;
}
efree(entry.tmp);
efree(entry.filename);
return FAILURE;
}
/* }}} */
zend_string *phar_find_in_include_path(char *filename, int filename_len, phar_archive_data **pphar) /* {{{ */
{
zend_string *ret;
char *path, *fname, *arch, *entry, *test;
int arch_len, entry_len, fname_len;
phar_archive_data *phar;
if (pphar) {
*pphar = NULL;
} else {
pphar = &phar;
}
if (!zend_is_executing() || !PHAR_G(cwd)) {
return phar_save_resolve_path(filename, filename_len);
}
fname = (char*)zend_get_executed_filename();
fname_len = strlen(fname);
if (PHAR_G(last_phar) && !memcmp(fname, "phar://", 7) && fname_len - 7 >= PHAR_G(last_phar_name_len) && !memcmp(fname + 7, PHAR_G(last_phar_name), PHAR_G(last_phar_name_len))) {
arch = estrndup(PHAR_G(last_phar_name), PHAR_G(last_phar_name_len));
arch_len = PHAR_G(last_phar_name_len);
phar = PHAR_G(last_phar);
goto splitted;
}
if (fname_len < 7 || memcmp(fname, "phar://", 7) || SUCCESS != phar_split_fname(fname, strlen(fname), &arch, &arch_len, &entry, &entry_len, 1, 0)) {
return phar_save_resolve_path(filename, filename_len);
}
efree(entry);
if (*filename == '.') {
int try_len;
if (FAILURE == phar_get_archive(&phar, arch, arch_len, NULL, 0, NULL)) {
efree(arch);
return phar_save_resolve_path(filename, filename_len);
}
splitted:
if (pphar) {
*pphar = phar;
}
try_len = filename_len;
test = phar_fix_filepath(estrndup(filename, filename_len), &try_len, 1);
if (*test == '/') {
if (zend_hash_str_exists(&(phar->manifest), test + 1, try_len - 1)) {
ret = strpprintf(0, "phar://%s%s", arch, test);
efree(arch);
efree(test);
return ret;
}
} else {
if (zend_hash_str_exists(&(phar->manifest), test, try_len)) {
ret = strpprintf(0, "phar://%s/%s", arch, test);
efree(arch);
efree(test);
return ret;
}
}
efree(test);
}
spprintf(&path, MAXPATHLEN, "phar://%s/%s%c%s", arch, PHAR_G(cwd), DEFAULT_DIR_SEPARATOR, PG(include_path));
efree(arch);
ret = php_resolve_path(filename, filename_len, path);
efree(path);
if (ret && ZSTR_LEN(ret) > 8 && !strncmp(ZSTR_VAL(ret), "phar://", 7)) {
/* found phar:// */
if (SUCCESS != phar_split_fname(ZSTR_VAL(ret), ZSTR_LEN(ret), &arch, &arch_len, &entry, &entry_len, 1, 0)) {
return ret;
}
*pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), arch, arch_len);
if (!*pphar && PHAR_G(manifest_cached)) {
*pphar = zend_hash_str_find_ptr(&cached_phars, arch, arch_len);
}
efree(arch);
efree(entry);
}
return ret;
}
/* }}} */
/**
* Retrieve a copy of the file information on a single file within a phar, or null.
* This also transfers the open file pointer, if any, to the entry.
*
* If the file does not already exist, this will fail. Pre-existing files can be
* appended, truncated, or read. For read, if the entry is marked unmodified, it is
* assumed that the file pointer, if present, is opened for reading
*/
int phar_get_entry_data(phar_entry_data **ret, char *fname, int fname_len, char *path, int path_len, const char *mode, char allow_dir, char **error, int security) /* {{{ */
{
phar_archive_data *phar;
phar_entry_info *entry;
int for_write = mode[0] != 'r' || mode[1] == '+';
int for_append = mode[0] == 'a';
int for_create = mode[0] != 'r';
int for_trunc = mode[0] == 'w';
if (!ret) {
return FAILURE;
}
*ret = NULL;
if (error) {
*error = NULL;
}
if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, error)) {
return FAILURE;
}
if (for_write && PHAR_G(readonly) && !phar->is_data) {
if (error) {
spprintf(error, 4096, "phar error: file \"%s\" in phar \"%s\" cannot be opened for writing, disabled by ini setting", path, fname);
}
return FAILURE;
}
if (!path_len) {
if (error) {
spprintf(error, 4096, "phar error: file \"\" in phar \"%s\" cannot be empty", fname);
}
return FAILURE;
}
really_get_entry:
if (allow_dir) {
if ((entry = phar_get_entry_info_dir(phar, path, path_len, allow_dir, for_create && !PHAR_G(readonly) && !phar->is_data ? NULL : error, security)) == NULL) {
if (for_create && (!PHAR_G(readonly) || phar->is_data)) {
return SUCCESS;
}
return FAILURE;
}
} else {
if ((entry = phar_get_entry_info(phar, path, path_len, for_create && !PHAR_G(readonly) && !phar->is_data ? NULL : error, security)) == NULL) {
if (for_create && (!PHAR_G(readonly) || phar->is_data)) {
return SUCCESS;
}
return FAILURE;
}
}
if (for_write && phar->is_persistent) {
if (FAILURE == phar_copy_on_write(&phar)) {
if (error) {
spprintf(error, 4096, "phar error: file \"%s\" in phar \"%s\" cannot be opened for writing, could not make cached phar writeable", path, fname);
}
return FAILURE;
} else {
goto really_get_entry;
}
}
if (entry->is_modified && !for_write) {
if (error) {
spprintf(error, 4096, "phar error: file \"%s\" in phar \"%s\" cannot be opened for reading, writable file pointers are open", path, fname);
}
return FAILURE;
}
if (entry->fp_refcount && for_write) {
if (error) {
spprintf(error, 4096, "phar error: file \"%s\" in phar \"%s\" cannot be opened for writing, readable file pointers are open", path, fname);
}
return FAILURE;
}
if (entry->is_deleted) {
if (!for_create) {
return FAILURE;
}
entry->is_deleted = 0;
}
if (entry->is_dir) {
*ret = (phar_entry_data *) emalloc(sizeof(phar_entry_data));
(*ret)->position = 0;
(*ret)->fp = NULL;
(*ret)->phar = phar;
(*ret)->for_write = for_write;
(*ret)->internal_file = entry;
(*ret)->is_zip = entry->is_zip;
(*ret)->is_tar = entry->is_tar;
if (!phar->is_persistent) {
++(entry->phar->refcount);
++(entry->fp_refcount);
}
return SUCCESS;
}
if (entry->fp_type == PHAR_MOD) {
if (for_trunc) {
if (FAILURE == phar_create_writeable_entry(phar, entry, error)) {
return FAILURE;
}
} else if (for_append) {
phar_seek_efp(entry, 0, SEEK_END, 0, 0);
}
} else {
if (for_write) {
if (entry->link) {
efree(entry->link);
entry->link = NULL;
entry->tar_type = (entry->is_tar ? TAR_FILE : '\0');
}
if (for_trunc) {
if (FAILURE == phar_create_writeable_entry(phar, entry, error)) {
return FAILURE;
}
} else {
if (FAILURE == phar_separate_entry_fp(entry, error)) {
return FAILURE;
}
}
} else {
if (FAILURE == phar_open_entry_fp(entry, error, 1)) {
return FAILURE;
}
}
}
*ret = (phar_entry_data *) emalloc(sizeof(phar_entry_data));
(*ret)->position = 0;
(*ret)->phar = phar;
(*ret)->for_write = for_write;
(*ret)->internal_file = entry;
(*ret)->is_zip = entry->is_zip;
(*ret)->is_tar = entry->is_tar;
(*ret)->fp = phar_get_efp(entry, 1);
if (entry->link) {
phar_entry_info *link = phar_get_link_source(entry);
if(!link) {
efree(*ret);
return FAILURE;
}
(*ret)->zero = phar_get_fp_offset(link);
} else {
(*ret)->zero = phar_get_fp_offset(entry);
}
if (!phar->is_persistent) {
++(entry->fp_refcount);
++(entry->phar->refcount);
}
return SUCCESS;
}
/* }}} */
/**
* Create a new dummy file slot within a writeable phar for a newly created file
*/
phar_entry_data *phar_get_or_create_entry_data(char *fname, int fname_len, char *path, int path_len, const char *mode, char allow_dir, char **error, int security) /* {{{ */
{
phar_archive_data *phar;
phar_entry_info *entry, etemp;
phar_entry_data *ret;
const char *pcr_error;
char is_dir;
#ifdef PHP_WIN32
phar_unixify_path_separators(path, path_len);
#endif
is_dir = (path_len && path[path_len - 1] == '/') ? 1 : 0;
if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, error)) {
return NULL;
}
if (FAILURE == phar_get_entry_data(&ret, fname, fname_len, path, path_len, mode, allow_dir, error, security)) {
return NULL;
} else if (ret) {
return ret;
}
if (phar_path_check(&path, &path_len, &pcr_error) > pcr_is_ok) {
if (error) {
spprintf(error, 0, "phar error: invalid path \"%s\" contains %s", path, pcr_error);
}
return NULL;
}
if (phar->is_persistent && FAILURE == phar_copy_on_write(&phar)) {
if (error) {
spprintf(error, 4096, "phar error: file \"%s\" in phar \"%s\" cannot be created, could not make cached phar writeable", path, fname);
}
return NULL;
}
/* create a new phar data holder */
ret = (phar_entry_data *) emalloc(sizeof(phar_entry_data));
/* create an entry, this is a new file */
memset(&etemp, 0, sizeof(phar_entry_info));
etemp.filename_len = path_len;
etemp.fp_type = PHAR_MOD;
etemp.fp = php_stream_fopen_tmpfile();
if (!etemp.fp) {
if (error) {
spprintf(error, 0, "phar error: unable to create temporary file");
}
efree(ret);
return NULL;
}
etemp.fp_refcount = 1;
if (allow_dir == 2) {
etemp.is_dir = 1;
etemp.flags = etemp.old_flags = PHAR_ENT_PERM_DEF_DIR;
} else {
etemp.flags = etemp.old_flags = PHAR_ENT_PERM_DEF_FILE;
}
if (is_dir) {
etemp.filename_len--; /* strip trailing / */
path_len--;
}
phar_add_virtual_dirs(phar, path, path_len);
etemp.is_modified = 1;
etemp.timestamp = time(0);
etemp.is_crc_checked = 1;
etemp.phar = phar;
etemp.filename = estrndup(path, path_len);
etemp.is_zip = phar->is_zip;
if (phar->is_tar) {
etemp.is_tar = phar->is_tar;
etemp.tar_type = etemp.is_dir ? TAR_DIR : TAR_FILE;
}
if (NULL == (entry = zend_hash_str_add_mem(&phar->manifest, etemp.filename, path_len, (void*)&etemp, sizeof(phar_entry_info)))) {
php_stream_close(etemp.fp);
if (error) {
spprintf(error, 0, "phar error: unable to add new entry \"%s\" to phar \"%s\"", etemp.filename, phar->fname);
}
efree(ret);
efree(etemp.filename);
return NULL;
}
if (!entry) {
php_stream_close(etemp.fp);
efree(etemp.filename);
efree(ret);
return NULL;
}
++(phar->refcount);
ret->phar = phar;
ret->fp = entry->fp;
ret->position = ret->zero = 0;
ret->for_write = 1;
ret->is_zip = entry->is_zip;
ret->is_tar = entry->is_tar;
ret->internal_file = entry;
return ret;
}
/* }}} */
/* initialize a phar_archive_data's read-only fp for existing phar data */
int phar_open_archive_fp(phar_archive_data *phar) /* {{{ */
{
if (phar_get_pharfp(phar)) {
return SUCCESS;
}
if (php_check_open_basedir(phar->fname)) {
return FAILURE;
}
phar_set_pharfp(phar, php_stream_open_wrapper(phar->fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|0, NULL));
if (!phar_get_pharfp(phar)) {
return FAILURE;
}
return SUCCESS;
}
/* }}} */
/* copy file data from an existing to a new phar_entry_info that is not in the manifest */
int phar_copy_entry_fp(phar_entry_info *source, phar_entry_info *dest, char **error) /* {{{ */
{
phar_entry_info *link;
if (FAILURE == phar_open_entry_fp(source, error, 1)) {
return FAILURE;
}
if (dest->link) {
efree(dest->link);
dest->link = NULL;
dest->tar_type = (dest->is_tar ? TAR_FILE : '\0');
}
dest->fp_type = PHAR_MOD;
dest->offset = 0;
dest->is_modified = 1;
dest->fp = php_stream_fopen_tmpfile();
if (dest->fp == NULL) {
spprintf(error, 0, "phar error: unable to create temporary file");
return EOF;
}
phar_seek_efp(source, 0, SEEK_SET, 0, 1);
link = phar_get_link_source(source);
if (!link) {
link = source;
}
if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(link, 0), dest->fp, link->uncompressed_filesize, NULL)) {
php_stream_close(dest->fp);
dest->fp_type = PHAR_FP;
if (error) {
spprintf(error, 4096, "phar error: unable to copy contents of file \"%s\" to \"%s\" in phar archive \"%s\"", source->filename, dest->filename, source->phar->fname);
}
return FAILURE;
}
return SUCCESS;
}
/* }}} */
/* open and decompress a compressed phar entry
*/
int phar_open_entry_fp(phar_entry_info *entry, char **error, int follow_links) /* {{{ */
{
php_stream_filter *filter;
phar_archive_data *phar = entry->phar;
char *filtername;
zend_off_t loc;
php_stream *ufp;
phar_entry_data dummy;
if (follow_links && entry->link) {
phar_entry_info *link_entry = phar_get_link_source(entry);
if (link_entry && link_entry != entry) {
return phar_open_entry_fp(link_entry, error, 1);
}
}
if (entry->is_modified) {
return SUCCESS;
}
if (entry->fp_type == PHAR_TMP) {
if (!entry->fp) {
entry->fp = php_stream_open_wrapper(entry->tmp, "rb", STREAM_MUST_SEEK|0, NULL);
}
return SUCCESS;
}
if (entry->fp_type != PHAR_FP) {
/* either newly created or already modified */
return SUCCESS;
}
if (!phar_get_pharfp(phar)) {
if (FAILURE == phar_open_archive_fp(phar)) {
spprintf(error, 4096, "phar error: Cannot open phar archive \"%s\" for reading", phar->fname);
return FAILURE;
}
}
if ((entry->old_flags && !(entry->old_flags & PHAR_ENT_COMPRESSION_MASK)) || !(entry->flags & PHAR_ENT_COMPRESSION_MASK)) {
dummy.internal_file = entry;
dummy.phar = phar;
dummy.zero = entry->offset;
dummy.fp = phar_get_pharfp(phar);
if (FAILURE == phar_postprocess_file(&dummy, entry->crc32, error, 1)) {
return FAILURE;
}
return SUCCESS;
}
if (!phar_get_entrypufp(entry)) {
phar_set_entrypufp(entry, php_stream_fopen_tmpfile());
if (!phar_get_entrypufp(entry)) {
spprintf(error, 4096, "phar error: Cannot open temporary file for decompressing phar archive \"%s\" file \"%s\"", phar->fname, entry->filename);
return FAILURE;
}
}
dummy.internal_file = entry;
dummy.phar = phar;
dummy.zero = entry->offset;
dummy.fp = phar_get_pharfp(phar);
if (FAILURE == phar_postprocess_file(&dummy, entry->crc32, error, 1)) {
return FAILURE;
}
ufp = phar_get_entrypufp(entry);
if ((filtername = phar_decompress_filter(entry, 0)) != NULL) {
filter = php_stream_filter_create(filtername, NULL, 0);
} else {
filter = NULL;
}
if (!filter) {
spprintf(error, 4096, "phar error: unable to read phar \"%s\" (cannot create %s filter while decompressing file \"%s\")", phar->fname, phar_decompress_filter(entry, 1), entry->filename);
return FAILURE;
}
/* now we can safely use proper decompression */
/* save the new offset location within ufp */
php_stream_seek(ufp, 0, SEEK_END);
loc = php_stream_tell(ufp);
php_stream_filter_append(&ufp->writefilters, filter);
php_stream_seek(phar_get_entrypfp(entry), phar_get_fp_offset(entry), SEEK_SET);
if (entry->uncompressed_filesize) {
if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_entrypfp(entry), ufp, entry->compressed_filesize, NULL)) {
spprintf(error, 4096, "phar error: internal corruption of phar \"%s\" (actual filesize mismatch on file \"%s\")", phar->fname, entry->filename);
php_stream_filter_remove(filter, 1);
return FAILURE;
}
}
php_stream_filter_flush(filter, 1);
php_stream_flush(ufp);
php_stream_filter_remove(filter, 1);
if (php_stream_tell(ufp) - loc != (zend_off_t) entry->uncompressed_filesize) {
spprintf(error, 4096, "phar error: internal corruption of phar \"%s\" (actual filesize mismatch on file \"%s\")", phar->fname, entry->filename);
return FAILURE;
}
entry->old_flags = entry->flags;
/* this is now the new location of the file contents within this fp */
phar_set_fp_type(entry, PHAR_UFP, loc);
dummy.zero = entry->offset;
dummy.fp = ufp;
if (FAILURE == phar_postprocess_file(&dummy, entry->crc32, error, 0)) {
return FAILURE;
}
return SUCCESS;
}
/* }}} */
int phar_create_writeable_entry(phar_archive_data *phar, phar_entry_info *entry, char **error) /* {{{ */
{
if (entry->fp_type == PHAR_MOD) {
/* already newly created, truncate */
php_stream_truncate_set_size(entry->fp, 0);
entry->old_flags = entry->flags;
entry->is_modified = 1;
phar->is_modified = 1;
/* reset file size */
entry->uncompressed_filesize = 0;
entry->compressed_filesize = 0;
entry->crc32 = 0;
entry->flags = PHAR_ENT_PERM_DEF_FILE;
entry->fp_type = PHAR_MOD;
entry->offset = 0;
return SUCCESS;
}
if (error) {
*error = NULL;
}
/* open a new temp file for writing */
if (entry->link) {
efree(entry->link);
entry->link = NULL;
entry->tar_type = (entry->is_tar ? TAR_FILE : '\0');
}
entry->fp = php_stream_fopen_tmpfile();
if (!entry->fp) {
if (error) {
spprintf(error, 0, "phar error: unable to create temporary file");
}
return FAILURE;
}
entry->old_flags = entry->flags;
entry->is_modified = 1;
phar->is_modified = 1;
/* reset file size */
entry->uncompressed_filesize = 0;
entry->compressed_filesize = 0;
entry->crc32 = 0;
entry->flags = PHAR_ENT_PERM_DEF_FILE;
entry->fp_type = PHAR_MOD;
entry->offset = 0;
return SUCCESS;
}
/* }}} */
int phar_separate_entry_fp(phar_entry_info *entry, char **error) /* {{{ */
{
php_stream *fp;
phar_entry_info *link;
if (FAILURE == phar_open_entry_fp(entry, error, 1)) {
return FAILURE;
}
if (entry->fp_type == PHAR_MOD) {
return SUCCESS;
}
fp = php_stream_fopen_tmpfile();
if (fp == NULL) {
spprintf(error, 0, "phar error: unable to create temporary file");
return FAILURE;
}
phar_seek_efp(entry, 0, SEEK_SET, 0, 1);
link = phar_get_link_source(entry);
if (!link) {
link = entry;
}
if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(link, 0), fp, link->uncompressed_filesize, NULL)) {
if (error) {
spprintf(error, 4096, "phar error: cannot separate entry file \"%s\" contents in phar archive \"%s\" for write access", entry->filename, entry->phar->fname);
}
return FAILURE;
}
if (entry->link) {
efree(entry->link);
entry->link = NULL;
entry->tar_type = (entry->is_tar ? TAR_FILE : '\0');
}
entry->offset = 0;
entry->fp = fp;
entry->fp_type = PHAR_MOD;
entry->is_modified = 1;
return SUCCESS;
}
/* }}} */
/**
* helper function to open an internal file's fp just-in-time
*/
phar_entry_info * phar_open_jit(phar_archive_data *phar, phar_entry_info *entry, char **error) /* {{{ */
{
if (error) {
*error = NULL;
}
/* seek to start of internal file and read it */
if (FAILURE == phar_open_entry_fp(entry, error, 1)) {
return NULL;
}
if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 1)) {
spprintf(error, 4096, "phar error: cannot seek to start of file \"%s\" in phar \"%s\"", entry->filename, phar->fname);
return NULL;
}
return entry;
}
/* }}} */
PHP_PHAR_API int phar_resolve_alias(char *alias, int alias_len, char **filename, int *filename_len) /* {{{ */ {
phar_archive_data *fd_ptr;
if (PHAR_G(phar_alias_map.u.flags)
&& NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len))) {
*filename = fd_ptr->fname;
*filename_len = fd_ptr->fname_len;
return SUCCESS;
}
return FAILURE;
}
/* }}} */
int phar_free_alias(phar_archive_data *phar, char *alias, int alias_len) /* {{{ */
{
if (phar->refcount || phar->is_persistent) {
return FAILURE;
}
/* this archive has no open references, so emit an E_STRICT and remove it */
if (zend_hash_str_del(&(PHAR_G(phar_fname_map)), phar->fname, phar->fname_len) != SUCCESS) {
return FAILURE;
}
/* invalidate phar cache */
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
return SUCCESS;
}
/* }}} */
/**
* Looks up a phar archive in the filename map, connecting it to the alias
* (if any) or returns null
*/
int phar_get_archive(phar_archive_data **archive, char *fname, int fname_len, char *alias, int alias_len, char **error) /* {{{ */
{
phar_archive_data *fd, *fd_ptr;
char *my_realpath, *save;
int save_len;
phar_request_initialize();
if (error) {
*error = NULL;
}
*archive = NULL;
if (PHAR_G(last_phar) && fname_len == PHAR_G(last_phar_name_len) && !memcmp(fname, PHAR_G(last_phar_name), fname_len)) {
*archive = PHAR_G(last_phar);
if (alias && alias_len) {
if (!PHAR_G(last_phar)->is_temporary_alias && (alias_len != PHAR_G(last_phar)->alias_len || memcmp(PHAR_G(last_phar)->alias, alias, alias_len))) {
if (error) {
spprintf(error, 0, "alias \"%s\" is already used for archive \"%s\" cannot be overloaded with \"%s\"", alias, PHAR_G(last_phar)->fname, fname);
}
*archive = NULL;
return FAILURE;
}
if (PHAR_G(last_phar)->alias_len && NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), PHAR_G(last_phar)->alias, PHAR_G(last_phar)->alias_len))) {
zend_hash_str_del(&(PHAR_G(phar_alias_map)), PHAR_G(last_phar)->alias, PHAR_G(last_phar)->alias_len);
}
zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len, *archive);
PHAR_G(last_alias) = alias;
PHAR_G(last_alias_len) = alias_len;
}
return SUCCESS;
}
if (alias && alias_len && PHAR_G(last_phar) && alias_len == PHAR_G(last_alias_len) && !memcmp(alias, PHAR_G(last_alias), alias_len)) {
fd = PHAR_G(last_phar);
fd_ptr = fd;
goto alias_success;
}
if (alias && alias_len) {
if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len))) {
alias_success:
if (fname && (fname_len != fd_ptr->fname_len || strncmp(fname, fd_ptr->fname, fname_len))) {
if (error) {
spprintf(error, 0, "alias \"%s\" is already used for archive \"%s\" cannot be overloaded with \"%s\"", alias, fd_ptr->fname, fname);
}
if (SUCCESS == phar_free_alias(fd_ptr, alias, alias_len)) {
if (error) {
efree(*error);
*error = NULL;
}
}
return FAILURE;
}
*archive = fd_ptr;
fd = fd_ptr;
PHAR_G(last_phar) = fd;
PHAR_G(last_phar_name) = fd->fname;
PHAR_G(last_phar_name_len) = fd->fname_len;
PHAR_G(last_alias) = alias;
PHAR_G(last_alias_len) = alias_len;
return SUCCESS;
}
if (PHAR_G(manifest_cached) && NULL != (fd_ptr = zend_hash_str_find_ptr(&cached_alias, alias, alias_len))) {
goto alias_success;
}
}
my_realpath = NULL;
save = fname;
save_len = fname_len;
if (fname && fname_len) {
if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), fname, fname_len))) {
*archive = fd_ptr;
fd = fd_ptr;
if (alias && alias_len) {
if (!fd->is_temporary_alias && (alias_len != fd->alias_len || memcmp(fd->alias, alias, alias_len))) {
if (error) {
spprintf(error, 0, "alias \"%s\" is already used for archive \"%s\" cannot be overloaded with \"%s\"", alias, fd_ptr->fname, fname);
}
return FAILURE;
}
if (fd->alias_len && NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), fd->alias, fd->alias_len))) {
zend_hash_str_del(&(PHAR_G(phar_alias_map)), fd->alias, fd->alias_len);
}
zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len, fd);
}
PHAR_G(last_phar) = fd;
PHAR_G(last_phar_name) = fd->fname;
PHAR_G(last_phar_name_len) = fd->fname_len;
PHAR_G(last_alias) = fd->alias;
PHAR_G(last_alias_len) = fd->alias_len;
return SUCCESS;
}
if (PHAR_G(manifest_cached) && NULL != (fd_ptr = zend_hash_str_find_ptr(&cached_phars, fname, fname_len))) {
*archive = fd_ptr;
fd = fd_ptr;
/* this could be problematic - alias should never be different from manifest alias
for cached phars */
if (!fd->is_temporary_alias && alias && alias_len) {
if (alias_len != fd->alias_len || memcmp(fd->alias, alias, alias_len)) {
if (error) {
spprintf(error, 0, "alias \"%s\" is already used for archive \"%s\" cannot be overloaded with \"%s\"", alias, fd_ptr->fname, fname);
}
return FAILURE;
}
}
PHAR_G(last_phar) = fd;
PHAR_G(last_phar_name) = fd->fname;
PHAR_G(last_phar_name_len) = fd->fname_len;
PHAR_G(last_alias) = fd->alias;
PHAR_G(last_alias_len) = fd->alias_len;
return SUCCESS;
}
if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), save, save_len))) {
fd = *archive = fd_ptr;
PHAR_G(last_phar) = fd;
PHAR_G(last_phar_name) = fd->fname;
PHAR_G(last_phar_name_len) = fd->fname_len;
PHAR_G(last_alias) = fd->alias;
PHAR_G(last_alias_len) = fd->alias_len;
return SUCCESS;
}
if (PHAR_G(manifest_cached) && NULL != (fd_ptr = zend_hash_str_find_ptr(&cached_alias, save, save_len))) {
fd = *archive = fd_ptr;
PHAR_G(last_phar) = fd;
PHAR_G(last_phar_name) = fd->fname;
PHAR_G(last_phar_name_len) = fd->fname_len;
PHAR_G(last_alias) = fd->alias;
PHAR_G(last_alias_len) = fd->alias_len;
return SUCCESS;
}
/* not found, try converting \ to / */
my_realpath = expand_filepath(fname, my_realpath);
if (my_realpath) {
fname_len = strlen(my_realpath);
fname = my_realpath;
} else {
return FAILURE;
}
#ifdef PHP_WIN32
phar_unixify_path_separators(fname, fname_len);
#endif
if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), fname, fname_len))) {
realpath_success:
*archive = fd_ptr;
fd = fd_ptr;
if (alias && alias_len) {
zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len, fd);
}
efree(my_realpath);
PHAR_G(last_phar) = fd;
PHAR_G(last_phar_name) = fd->fname;
PHAR_G(last_phar_name_len) = fd->fname_len;
PHAR_G(last_alias) = fd->alias;
PHAR_G(last_alias_len) = fd->alias_len;
return SUCCESS;
}
if (PHAR_G(manifest_cached) && NULL != (fd_ptr = zend_hash_str_find_ptr(&cached_phars, fname, fname_len))) {
goto realpath_success;
}
efree(my_realpath);
}
return FAILURE;
}
/* }}} */
/**
* Determine which stream compression filter (if any) we need to read this file
*/
char * phar_compress_filter(phar_entry_info * entry, int return_unknown) /* {{{ */
{
switch (entry->flags & PHAR_ENT_COMPRESSION_MASK) {
case PHAR_ENT_COMPRESSED_GZ:
return "zlib.deflate";
case PHAR_ENT_COMPRESSED_BZ2:
return "bzip2.compress";
default:
return return_unknown ? "unknown" : NULL;
}
}
/* }}} */
/**
* Determine which stream decompression filter (if any) we need to read this file
*/
char * phar_decompress_filter(phar_entry_info * entry, int return_unknown) /* {{{ */
{
php_uint32 flags;
if (entry->is_modified) {
flags = entry->old_flags;
} else {
flags = entry->flags;
}
switch (flags & PHAR_ENT_COMPRESSION_MASK) {
case PHAR_ENT_COMPRESSED_GZ:
return "zlib.inflate";
case PHAR_ENT_COMPRESSED_BZ2:
return "bzip2.decompress";
default:
return return_unknown ? "unknown" : NULL;
}
}
/* }}} */
/**
* retrieve information on a file contained within a phar, or null if it ain't there
*/
phar_entry_info *phar_get_entry_info(phar_archive_data *phar, char *path, int path_len, char **error, int security) /* {{{ */
{
return phar_get_entry_info_dir(phar, path, path_len, 0, error, security);
}
/* }}} */
/**
* retrieve information on a file or directory contained within a phar, or null if none found
* allow_dir is 0 for none, 1 for both empty directories in the phar and temp directories, and 2 for only
* valid pre-existing empty directory entries
*/
phar_entry_info *phar_get_entry_info_dir(phar_archive_data *phar, char *path, int path_len, char dir, char **error, int security) /* {{{ */
{
const char *pcr_error;
phar_entry_info *entry;
int is_dir;
#ifdef PHP_WIN32
phar_unixify_path_separators(path, path_len);
#endif
is_dir = (path_len && (path[path_len - 1] == '/')) ? 1 : 0;
if (error) {
*error = NULL;
}
if (security && path_len >= sizeof(".phar")-1 && !memcmp(path, ".phar", sizeof(".phar")-1)) {
if (error) {
spprintf(error, 4096, "phar error: cannot directly access magic \".phar\" directory or files within it");
}
return NULL;
}
if (!path_len && !dir) {
if (error) {
spprintf(error, 4096, "phar error: invalid path \"%s\" must not be empty", path);
}
return NULL;
}
if (phar_path_check(&path, &path_len, &pcr_error) > pcr_is_ok) {
if (error) {
spprintf(error, 4096, "phar error: invalid path \"%s\" contains %s", path, pcr_error);
}
return NULL;
}
if (!phar->manifest.u.flags) {
return NULL;
}
if (is_dir) {
if (!path_len || path_len == 1) {
return NULL;
}
path_len--;
}
if (NULL != (entry = zend_hash_str_find_ptr(&phar->manifest, path, path_len))) {
if (entry->is_deleted) {
/* entry is deleted, but has not been flushed to disk yet */
return NULL;
}
if (entry->is_dir && !dir) {
if (error) {
spprintf(error, 4096, "phar error: path \"%s\" is a directory", path);
}
return NULL;
}
if (!entry->is_dir && dir == 2) {
/* user requested a directory, we must return one */
if (error) {
spprintf(error, 4096, "phar error: path \"%s\" exists and is a not a directory", path);
}
return NULL;
}
return entry;
}
if (dir) {
if (zend_hash_str_exists(&phar->virtual_dirs, path, path_len)) {
/* a file or directory exists in a sub-directory of this path */
entry = (phar_entry_info *) ecalloc(1, sizeof(phar_entry_info));
/* this next line tells PharFileInfo->__destruct() to efree the filename */
entry->is_temp_dir = entry->is_dir = 1;
entry->filename = (char *) estrndup(path, path_len + 1);
entry->filename_len = path_len;
entry->phar = phar;
return entry;
}
}
if (phar->mounted_dirs.u.flags && zend_hash_num_elements(&phar->mounted_dirs)) {
zend_string *str_key;
ZEND_HASH_FOREACH_STR_KEY(&phar->mounted_dirs, str_key) {
if ((int)ZSTR_LEN(str_key) >= path_len || strncmp(ZSTR_VAL(str_key), path, ZSTR_LEN(str_key))) {
continue;
} else {
char *test;
int test_len;
php_stream_statbuf ssb;
if (NULL == (entry = zend_hash_find_ptr(&phar->manifest, str_key))) {
if (error) {
spprintf(error, 4096, "phar internal error: mounted path \"%s\" could not be retrieved from manifest", ZSTR_VAL(str_key));
}
return NULL;
}
if (!entry->tmp || !entry->is_mounted) {
if (error) {
spprintf(error, 4096, "phar internal error: mounted path \"%s\" is not properly initialized as a mounted path", ZSTR_VAL(str_key));
}
return NULL;
}
test_len = spprintf(&test, MAXPATHLEN, "%s%s", entry->tmp, path + ZSTR_LEN(str_key));
if (SUCCESS != php_stream_stat_path(test, &ssb)) {
efree(test);
return NULL;
}
if (ssb.sb.st_mode & S_IFDIR && !dir) {
efree(test);
if (error) {
spprintf(error, 4096, "phar error: path \"%s\" is a directory", path);
}
return NULL;
}
if ((ssb.sb.st_mode & S_IFDIR) == 0 && dir) {
efree(test);
/* user requested a directory, we must return one */
if (error) {
spprintf(error, 4096, "phar error: path \"%s\" exists and is a not a directory", path);
}
return NULL;
}
/* mount the file just in time */
if (SUCCESS != phar_mount_entry(phar, test, test_len, path, path_len)) {
efree(test);
if (error) {
spprintf(error, 4096, "phar error: path \"%s\" exists as file \"%s\" and could not be mounted", path, test);
}
return NULL;
}
efree(test);
if (NULL == (entry = zend_hash_str_find_ptr(&phar->manifest, path, path_len))) {
if (error) {
spprintf(error, 4096, "phar error: path \"%s\" exists as file \"%s\" and could not be retrieved after being mounted", path, test);
}
return NULL;
}
return entry;
}
} ZEND_HASH_FOREACH_END();
}
return NULL;
}
/* }}} */
static const char hexChars[] = "0123456789ABCDEF";
static int phar_hex_str(const char *digest, size_t digest_len, char **signature) /* {{{ */
{
int pos = -1;
size_t len = 0;
*signature = (char*)safe_pemalloc(digest_len, 2, 1, PHAR_G(persist));
for (; len < digest_len; ++len) {
(*signature)[++pos] = hexChars[((const unsigned char *)digest)[len] >> 4];
(*signature)[++pos] = hexChars[((const unsigned char *)digest)[len] & 0x0F];
}
(*signature)[++pos] = '\0';
return pos;
}
/* }}} */
#ifndef PHAR_HAVE_OPENSSL
static int phar_call_openssl_signverify(int is_sign, php_stream *fp, zend_off_t end, char *key, int key_len, char **signature, int *signature_len) /* {{{ */
{
zend_fcall_info fci;
zend_fcall_info_cache fcc;
zval retval, zp[3], openssl;
zend_string *str;
ZVAL_STRINGL(&openssl, is_sign ? "openssl_sign" : "openssl_verify", is_sign ? sizeof("openssl_sign")-1 : sizeof("openssl_verify")-1);
ZVAL_STRINGL(&zp[1], *signature, *signature_len);
ZVAL_STRINGL(&zp[2], key, key_len);
php_stream_rewind(fp);
str = php_stream_copy_to_mem(fp, (size_t) end, 0);
if (str) {
ZVAL_STR(&zp[0], str);
} else {
ZVAL_EMPTY_STRING(&zp[0]);
}
if (end != Z_STRLEN(zp[0])) {
zval_dtor(&zp[0]);
zval_dtor(&zp[1]);
zval_dtor(&zp[2]);
zval_dtor(&openssl);
return FAILURE;
}
if (FAILURE == zend_fcall_info_init(&openssl, 0, &fci, &fcc, NULL, NULL)) {
zval_dtor(&zp[0]);
zval_dtor(&zp[1]);
zval_dtor(&zp[2]);
zval_dtor(&openssl);
return FAILURE;
}
fci.param_count = 3;
fci.params = zp;
Z_ADDREF(zp[0]);
if (is_sign) {
ZVAL_NEW_REF(&zp[1], &zp[1]);
} else {
Z_ADDREF(zp[1]);
}
Z_ADDREF(zp[2]);
fci.retval = &retval;
if (FAILURE == zend_call_function(&fci, &fcc)) {
zval_dtor(&zp[0]);
zval_dtor(&zp[1]);
zval_dtor(&zp[2]);
zval_dtor(&openssl);
return FAILURE;
}
zval_dtor(&openssl);
Z_DELREF(zp[0]);
if (is_sign) {
ZVAL_UNREF(&zp[1]);
} else {
Z_DELREF(zp[1]);
}
Z_DELREF(zp[2]);
zval_dtor(&zp[0]);
zval_dtor(&zp[2]);
switch (Z_TYPE(retval)) {
default:
case IS_LONG:
zval_dtor(&zp[1]);
if (1 == Z_LVAL(retval)) {
return SUCCESS;
}
return FAILURE;
case IS_TRUE:
*signature = estrndup(Z_STRVAL(zp[1]), Z_STRLEN(zp[1]));
*signature_len = Z_STRLEN(zp[1]);
zval_dtor(&zp[1]);
return SUCCESS;
case IS_FALSE:
zval_dtor(&zp[1]);
return FAILURE;
}
}
/* }}} */
#endif /* #ifndef PHAR_HAVE_OPENSSL */
int phar_verify_signature(php_stream *fp, size_t end_of_phar, php_uint32 sig_type, char *sig, int sig_len, char *fname, char **signature, int *signature_len, char **error) /* {{{ */
{
int read_size, len;
zend_off_t read_len;
unsigned char buf[1024];
php_stream_rewind(fp);
switch (sig_type) {
case PHAR_SIG_OPENSSL: {
#ifdef PHAR_HAVE_OPENSSL
BIO *in;
EVP_PKEY *key;
EVP_MD *mdtype = (EVP_MD *) EVP_sha1();
EVP_MD_CTX md_ctx;
#else
int tempsig;
#endif
zend_string *pubkey = NULL;
char *pfile;
php_stream *pfp;
#ifndef PHAR_HAVE_OPENSSL
if (!zend_hash_str_exists(&module_registry, "openssl", sizeof("openssl")-1)) {
if (error) {
spprintf(error, 0, "openssl not loaded");
}
return FAILURE;
}
#endif
/* use __FILE__ . '.pubkey' for public key file */
spprintf(&pfile, 0, "%s.pubkey", fname);
pfp = php_stream_open_wrapper(pfile, "rb", 0, NULL);
efree(pfile);
if (!pfp || !(pubkey = php_stream_copy_to_mem(pfp, PHP_STREAM_COPY_ALL, 0)) || !ZSTR_LEN(pubkey)) {
if (pfp) {
php_stream_close(pfp);
}
if (error) {
spprintf(error, 0, "openssl public key could not be read");
}
return FAILURE;
}
php_stream_close(pfp);
#ifndef PHAR_HAVE_OPENSSL
tempsig = sig_len;
if (FAILURE == phar_call_openssl_signverify(0, fp, end_of_phar, pubkey ? ZSTR_VAL(pubkey) : NULL, pubkey ? ZSTR_LEN(pubkey) : 0, &sig, &tempsig)) {
if (pubkey) {
zend_string_release(pubkey);
}
if (error) {
spprintf(error, 0, "openssl signature could not be verified");
}
return FAILURE;
}
if (pubkey) {
zend_string_release(pubkey);
}
sig_len = tempsig;
#else
in = BIO_new_mem_buf(pubkey ? ZSTR_VAL(pubkey) : NULL, pubkey ? ZSTR_LEN(pubkey) : 0);
if (NULL == in) {
zend_string_release(pubkey);
if (error) {
spprintf(error, 0, "openssl signature could not be processed");
}
return FAILURE;
}
key = PEM_read_bio_PUBKEY(in, NULL,NULL, NULL);
BIO_free(in);
zend_string_release(pubkey);
if (NULL == key) {
if (error) {
spprintf(error, 0, "openssl signature could not be processed");
}
return FAILURE;
}
EVP_VerifyInit(&md_ctx, mdtype);
read_len = end_of_phar;
if (read_len > sizeof(buf)) {
read_size = sizeof(buf);
} else {
read_size = (int)read_len;
}
php_stream_seek(fp, 0, SEEK_SET);
while (read_size && (len = php_stream_read(fp, (char*)buf, read_size)) > 0) {
EVP_VerifyUpdate (&md_ctx, buf, len);
read_len -= (zend_off_t)len;
if (read_len < read_size) {
read_size = (int)read_len;
}
}
if (EVP_VerifyFinal(&md_ctx, (unsigned char *)sig, sig_len, key) != 1) {
/* 1: signature verified, 0: signature does not match, -1: failed signature operation */
EVP_MD_CTX_cleanup(&md_ctx);
if (error) {
spprintf(error, 0, "broken openssl signature");
}
return FAILURE;
}
EVP_MD_CTX_cleanup(&md_ctx);
#endif
*signature_len = phar_hex_str((const char*)sig, sig_len, signature);
}
break;
#ifdef PHAR_HASH_OK
case PHAR_SIG_SHA512: {
unsigned char digest[64];
PHP_SHA512_CTX context;
PHP_SHA512Init(&context);
read_len = end_of_phar;
if (read_len > sizeof(buf)) {
read_size = sizeof(buf);
} else {
read_size = (int)read_len;
}
while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {
PHP_SHA512Update(&context, buf, len);
read_len -= (zend_off_t)len;
if (read_len < read_size) {
read_size = (int)read_len;
}
}
PHP_SHA512Final(digest, &context);
if (memcmp(digest, sig, sizeof(digest))) {
if (error) {
spprintf(error, 0, "broken signature");
}
return FAILURE;
}
*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);
break;
}
case PHAR_SIG_SHA256: {
unsigned char digest[32];
PHP_SHA256_CTX context;
PHP_SHA256Init(&context);
read_len = end_of_phar;
if (read_len > sizeof(buf)) {
read_size = sizeof(buf);
} else {
read_size = (int)read_len;
}
while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {
PHP_SHA256Update(&context, buf, len);
read_len -= (zend_off_t)len;
if (read_len < read_size) {
read_size = (int)read_len;
}
}
PHP_SHA256Final(digest, &context);
if (memcmp(digest, sig, sizeof(digest))) {
if (error) {
spprintf(error, 0, "broken signature");
}
return FAILURE;
}
*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);
break;
}
#else
case PHAR_SIG_SHA512:
case PHAR_SIG_SHA256:
if (error) {
spprintf(error, 0, "unsupported signature");
}
return FAILURE;
#endif
case PHAR_SIG_SHA1: {
unsigned char digest[20];
PHP_SHA1_CTX context;
PHP_SHA1Init(&context);
read_len = end_of_phar;
if (read_len > sizeof(buf)) {
read_size = sizeof(buf);
} else {
read_size = (int)read_len;
}
while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {
PHP_SHA1Update(&context, buf, len);
read_len -= (zend_off_t)len;
if (read_len < read_size) {
read_size = (int)read_len;
}
}
PHP_SHA1Final(digest, &context);
if (memcmp(digest, sig, sizeof(digest))) {
if (error) {
spprintf(error, 0, "broken signature");
}
return FAILURE;
}
*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);
break;
}
case PHAR_SIG_MD5: {
unsigned char digest[16];
PHP_MD5_CTX context;
PHP_MD5Init(&context);
read_len = end_of_phar;
if (read_len > sizeof(buf)) {
read_size = sizeof(buf);
} else {
read_size = (int)read_len;
}
while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {
PHP_MD5Update(&context, buf, len);
read_len -= (zend_off_t)len;
if (read_len < read_size) {
read_size = (int)read_len;
}
}
PHP_MD5Final(digest, &context);
if (memcmp(digest, sig, sizeof(digest))) {
if (error) {
spprintf(error, 0, "broken signature");
}
return FAILURE;
}
*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);
break;
}
default:
if (error) {
spprintf(error, 0, "broken or unsupported signature");
}
return FAILURE;
}
return SUCCESS;
}
/* }}} */
int phar_create_signature(phar_archive_data *phar, php_stream *fp, char **signature, int *signature_length, char **error) /* {{{ */
{
unsigned char buf[1024];
int sig_len;
php_stream_rewind(fp);
if (phar->signature) {
efree(phar->signature);
phar->signature = NULL;
}
switch(phar->sig_flags) {
#ifdef PHAR_HASH_OK
case PHAR_SIG_SHA512: {
unsigned char digest[64];
PHP_SHA512_CTX context;
PHP_SHA512Init(&context);
while ((sig_len = php_stream_read(fp, (char*)buf, sizeof(buf))) > 0) {
PHP_SHA512Update(&context, buf, sig_len);
}
PHP_SHA512Final(digest, &context);
*signature = estrndup((char *) digest, 64);
*signature_length = 64;
break;
}
case PHAR_SIG_SHA256: {
unsigned char digest[32];
PHP_SHA256_CTX context;
PHP_SHA256Init(&context);
while ((sig_len = php_stream_read(fp, (char*)buf, sizeof(buf))) > 0) {
PHP_SHA256Update(&context, buf, sig_len);
}
PHP_SHA256Final(digest, &context);
*signature = estrndup((char *) digest, 32);
*signature_length = 32;
break;
}
#else
case PHAR_SIG_SHA512:
case PHAR_SIG_SHA256:
if (error) {
spprintf(error, 0, "unable to write to phar \"%s\" with requested hash type", phar->fname);
}
return FAILURE;
#endif
case PHAR_SIG_OPENSSL: {
int siglen;
unsigned char *sigbuf;
#ifdef PHAR_HAVE_OPENSSL
BIO *in;
EVP_PKEY *key;
EVP_MD_CTX *md_ctx;
in = BIO_new_mem_buf(PHAR_G(openssl_privatekey), PHAR_G(openssl_privatekey_len));
if (in == NULL) {
if (error) {
spprintf(error, 0, "unable to write to phar \"%s\" with requested openssl signature", phar->fname);
}
return FAILURE;
}
key = PEM_read_bio_PrivateKey(in, NULL,NULL, "");
BIO_free(in);
if (!key) {
if (error) {
spprintf(error, 0, "unable to process private key");
}
return FAILURE;
}
md_ctx = EVP_MD_CTX_create();
siglen = EVP_PKEY_size(key);
sigbuf = emalloc(siglen + 1);
if (!EVP_SignInit(md_ctx, EVP_sha1())) {
efree(sigbuf);
if (error) {
spprintf(error, 0, "unable to initialize openssl signature for phar \"%s\"", phar->fname);
}
return FAILURE;
}
while ((sig_len = php_stream_read(fp, (char*)buf, sizeof(buf))) > 0) {
if (!EVP_SignUpdate(md_ctx, buf, sig_len)) {
efree(sigbuf);
if (error) {
spprintf(error, 0, "unable to update the openssl signature for phar \"%s\"", phar->fname);
}
return FAILURE;
}
}
if (!EVP_SignFinal (md_ctx, sigbuf,(unsigned int *)&siglen, key)) {
efree(sigbuf);
if (error) {
spprintf(error, 0, "unable to write phar \"%s\" with requested openssl signature", phar->fname);
}
return FAILURE;
}
sigbuf[siglen] = '\0';
EVP_MD_CTX_destroy(md_ctx);
#else
sigbuf = NULL;
siglen = 0;
php_stream_seek(fp, 0, SEEK_END);
if (FAILURE == phar_call_openssl_signverify(1, fp, php_stream_tell(fp), PHAR_G(openssl_privatekey), PHAR_G(openssl_privatekey_len), (char **)&sigbuf, &siglen)) {
if (error) {
spprintf(error, 0, "unable to write phar \"%s\" with requested openssl signature", phar->fname);
}
return FAILURE;
}
#endif
*signature = (char *) sigbuf;
*signature_length = siglen;
}
break;
default:
phar->sig_flags = PHAR_SIG_SHA1;
case PHAR_SIG_SHA1: {
unsigned char digest[20];
PHP_SHA1_CTX context;
PHP_SHA1Init(&context);
while ((sig_len = php_stream_read(fp, (char*)buf, sizeof(buf))) > 0) {
PHP_SHA1Update(&context, buf, sig_len);
}
PHP_SHA1Final(digest, &context);
*signature = estrndup((char *) digest, 20);
*signature_length = 20;
break;
}
case PHAR_SIG_MD5: {
unsigned char digest[16];
PHP_MD5_CTX context;
PHP_MD5Init(&context);
while ((sig_len = php_stream_read(fp, (char*)buf, sizeof(buf))) > 0) {
PHP_MD5Update(&context, buf, sig_len);
}
PHP_MD5Final(digest, &context);
*signature = estrndup((char *) digest, 16);
*signature_length = 16;
break;
}
}
phar->sig_len = phar_hex_str((const char *)*signature, *signature_length, &phar->signature);
return SUCCESS;
}
/* }}} */
void phar_add_virtual_dirs(phar_archive_data *phar, char *filename, int filename_len) /* {{{ */
{
const char *s;
while ((s = zend_memrchr(filename, '/', filename_len))) {
filename_len = s - filename;
if (!filename_len || NULL == zend_hash_str_add_empty_element(&phar->virtual_dirs, filename, filename_len)) {
break;
}
}
}
/* }}} */
static int phar_update_cached_entry(zval *data, void *argument) /* {{{ */
{
phar_entry_info *entry = (phar_entry_info *)Z_PTR_P(data);
entry->phar = (phar_archive_data *)argument;
if (entry->link) {
entry->link = estrdup(entry->link);
}
if (entry->tmp) {
entry->tmp = estrdup(entry->tmp);
}
entry->metadata_str.s = NULL;
entry->filename = estrndup(entry->filename, entry->filename_len);
entry->is_persistent = 0;
if (Z_TYPE(entry->metadata) != IS_UNDEF) {
if (entry->metadata_len) {
char *buf = estrndup((char *) Z_PTR(entry->metadata), entry->metadata_len);
/* assume success, we would have failed before */
phar_parse_metadata((char **) &buf, &entry->metadata, entry->metadata_len);
efree(buf);
} else {
zval_copy_ctor(&entry->metadata);
entry->metadata_str.s = NULL;
}
}
return ZEND_HASH_APPLY_KEEP;
}
/* }}} */
static void phar_manifest_copy_ctor(zval *zv) /* {{{ */
{
phar_entry_info *info = emalloc(sizeof(phar_entry_info));
memcpy(info, Z_PTR_P(zv), sizeof(phar_entry_info));
Z_PTR_P(zv) = info;
}
/* }}} */
static void phar_copy_cached_phar(phar_archive_data **pphar) /* {{{ */
{
phar_archive_data *phar;
HashTable newmanifest;
char *fname;
phar_archive_object *objphar;
phar = (phar_archive_data *) emalloc(sizeof(phar_archive_data));
*phar = **pphar;
phar->is_persistent = 0;
fname = phar->fname;
phar->fname = estrndup(phar->fname, phar->fname_len);
phar->ext = phar->fname + (phar->ext - fname);
if (phar->alias) {
phar->alias = estrndup(phar->alias, phar->alias_len);
}
if (phar->signature) {
phar->signature = estrdup(phar->signature);
}
if (Z_TYPE(phar->metadata) != IS_UNDEF) {
/* assume success, we would have failed before */
if (phar->metadata_len) {
char *buf = estrndup((char *) Z_PTR(phar->metadata), phar->metadata_len);
phar_parse_metadata(&buf, &phar->metadata, phar->metadata_len);
efree(buf);
} else {
zval_copy_ctor(&phar->metadata);
}
}
zend_hash_init(&newmanifest, sizeof(phar_entry_info),
zend_get_hash_value, destroy_phar_manifest_entry, 0);
zend_hash_copy(&newmanifest, &(*pphar)->manifest, phar_manifest_copy_ctor);
zend_hash_apply_with_argument(&newmanifest, phar_update_cached_entry, (void *)phar);
phar->manifest = newmanifest;
zend_hash_init(&phar->mounted_dirs, sizeof(char *),
zend_get_hash_value, NULL, 0);
zend_hash_init(&phar->virtual_dirs, sizeof(char *),
zend_get_hash_value, NULL, 0);
zend_hash_copy(&phar->virtual_dirs, &(*pphar)->virtual_dirs, NULL);
*pphar = phar;
/* now, scan the list of persistent Phar objects referencing this phar and update the pointers */
ZEND_HASH_FOREACH_PTR(&PHAR_G(phar_persist_map), objphar) {
if (objphar->archive->fname_len == phar->fname_len && !memcmp(objphar->archive->fname, phar->fname, phar->fname_len)) {
objphar->archive = phar;
}
} ZEND_HASH_FOREACH_END();
}
/* }}} */
int phar_copy_on_write(phar_archive_data **pphar) /* {{{ */
{
zval zv, *pzv;
phar_archive_data *newpphar;
ZVAL_PTR(&zv, *pphar);
if (NULL == (pzv = zend_hash_str_add(&(PHAR_G(phar_fname_map)), (*pphar)->fname, (*pphar)->fname_len, &zv))) {
return FAILURE;
}
phar_copy_cached_phar((phar_archive_data **)&Z_PTR_P(pzv));
newpphar = Z_PTR_P(pzv);
/* invalidate phar cache */
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
if (newpphar->alias_len && NULL == zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), newpphar->alias, newpphar->alias_len, newpphar)) {
zend_hash_str_del(&(PHAR_G(phar_fname_map)), (*pphar)->fname, (*pphar)->fname_len);
return FAILURE;
}
*pphar = newpphar;
return SUCCESS;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5283_2 |
crossvul-cpp_data_bad_3316_0 | /*
* Copyright (C) 2006, 2007, 2009 Rusty Russell, IBM Corporation
* Copyright (C) 2009, 2010, 2011 Red Hat, Inc.
* Copyright (C) 2009, 2010, 2011 Amit Shah <amit.shah@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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/cdev.h>
#include <linux/debugfs.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/freezer.h>
#include <linux/fs.h>
#include <linux/splice.h>
#include <linux/pagemap.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/poll.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/virtio.h>
#include <linux/virtio_console.h>
#include <linux/wait.h>
#include <linux/workqueue.h>
#include <linux/module.h>
#include <linux/dma-mapping.h>
#include "../tty/hvc/hvc_console.h"
#define is_rproc_enabled IS_ENABLED(CONFIG_REMOTEPROC)
/*
* This is a global struct for storing common data for all the devices
* this driver handles.
*
* Mainly, it has a linked list for all the consoles in one place so
* that callbacks from hvc for get_chars(), put_chars() work properly
* across multiple devices and multiple ports per device.
*/
struct ports_driver_data {
/* Used for registering chardevs */
struct class *class;
/* Used for exporting per-port information to debugfs */
struct dentry *debugfs_dir;
/* List of all the devices we're handling */
struct list_head portdevs;
/*
* This is used to keep track of the number of hvc consoles
* spawned by this driver. This number is given as the first
* argument to hvc_alloc(). To correctly map an initial
* console spawned via hvc_instantiate to the console being
* hooked up via hvc_alloc, we need to pass the same vtermno.
*
* We also just assume the first console being initialised was
* the first one that got used as the initial console.
*/
unsigned int next_vtermno;
/* All the console devices handled by this driver */
struct list_head consoles;
};
static struct ports_driver_data pdrvdata;
static DEFINE_SPINLOCK(pdrvdata_lock);
static DECLARE_COMPLETION(early_console_added);
/* This struct holds information that's relevant only for console ports */
struct console {
/* We'll place all consoles in a list in the pdrvdata struct */
struct list_head list;
/* The hvc device associated with this console port */
struct hvc_struct *hvc;
/* The size of the console */
struct winsize ws;
/*
* This number identifies the number that we used to register
* with hvc in hvc_instantiate() and hvc_alloc(); this is the
* number passed on by the hvc callbacks to us to
* differentiate between the other console ports handled by
* this driver
*/
u32 vtermno;
};
struct port_buffer {
char *buf;
/* size of the buffer in *buf above */
size_t size;
/* used length of the buffer */
size_t len;
/* offset in the buf from which to consume data */
size_t offset;
/* DMA address of buffer */
dma_addr_t dma;
/* Device we got DMA memory from */
struct device *dev;
/* List of pending dma buffers to free */
struct list_head list;
/* If sgpages == 0 then buf is used */
unsigned int sgpages;
/* sg is used if spages > 0. sg must be the last in is struct */
struct scatterlist sg[0];
};
/*
* This is a per-device struct that stores data common to all the
* ports for that device (vdev->priv).
*/
struct ports_device {
/* Next portdev in the list, head is in the pdrvdata struct */
struct list_head list;
/*
* Workqueue handlers where we process deferred work after
* notification
*/
struct work_struct control_work;
struct work_struct config_work;
struct list_head ports;
/* To protect the list of ports */
spinlock_t ports_lock;
/* To protect the vq operations for the control channel */
spinlock_t c_ivq_lock;
spinlock_t c_ovq_lock;
/* max. number of ports this device can hold */
u32 max_nr_ports;
/* The virtio device we're associated with */
struct virtio_device *vdev;
/*
* A couple of virtqueues for the control channel: one for
* guest->host transfers, one for host->guest transfers
*/
struct virtqueue *c_ivq, *c_ovq;
/*
* A control packet buffer for guest->host requests, protected
* by c_ovq_lock.
*/
struct virtio_console_control cpkt;
/* Array of per-port IO virtqueues */
struct virtqueue **in_vqs, **out_vqs;
/* Major number for this device. Ports will be created as minors. */
int chr_major;
};
struct port_stats {
unsigned long bytes_sent, bytes_received, bytes_discarded;
};
/* This struct holds the per-port data */
struct port {
/* Next port in the list, head is in the ports_device */
struct list_head list;
/* Pointer to the parent virtio_console device */
struct ports_device *portdev;
/* The current buffer from which data has to be fed to readers */
struct port_buffer *inbuf;
/*
* To protect the operations on the in_vq associated with this
* port. Has to be a spinlock because it can be called from
* interrupt context (get_char()).
*/
spinlock_t inbuf_lock;
/* Protect the operations on the out_vq. */
spinlock_t outvq_lock;
/* The IO vqs for this port */
struct virtqueue *in_vq, *out_vq;
/* File in the debugfs directory that exposes this port's information */
struct dentry *debugfs_file;
/*
* Keep count of the bytes sent, received and discarded for
* this port for accounting and debugging purposes. These
* counts are not reset across port open / close events.
*/
struct port_stats stats;
/*
* The entries in this struct will be valid if this port is
* hooked up to an hvc console
*/
struct console cons;
/* Each port associates with a separate char device */
struct cdev *cdev;
struct device *dev;
/* Reference-counting to handle port hot-unplugs and file operations */
struct kref kref;
/* A waitqueue for poll() or blocking read operations */
wait_queue_head_t waitqueue;
/* The 'name' of the port that we expose via sysfs properties */
char *name;
/* We can notify apps of host connect / disconnect events via SIGIO */
struct fasync_struct *async_queue;
/* The 'id' to identify the port with the Host */
u32 id;
bool outvq_full;
/* Is the host device open */
bool host_connected;
/* We should allow only one process to open a port */
bool guest_connected;
};
/* This is the very early arch-specified put chars function. */
static int (*early_put_chars)(u32, const char *, int);
static struct port *find_port_by_vtermno(u32 vtermno)
{
struct port *port;
struct console *cons;
unsigned long flags;
spin_lock_irqsave(&pdrvdata_lock, flags);
list_for_each_entry(cons, &pdrvdata.consoles, list) {
if (cons->vtermno == vtermno) {
port = container_of(cons, struct port, cons);
goto out;
}
}
port = NULL;
out:
spin_unlock_irqrestore(&pdrvdata_lock, flags);
return port;
}
static struct port *find_port_by_devt_in_portdev(struct ports_device *portdev,
dev_t dev)
{
struct port *port;
unsigned long flags;
spin_lock_irqsave(&portdev->ports_lock, flags);
list_for_each_entry(port, &portdev->ports, list) {
if (port->cdev->dev == dev) {
kref_get(&port->kref);
goto out;
}
}
port = NULL;
out:
spin_unlock_irqrestore(&portdev->ports_lock, flags);
return port;
}
static struct port *find_port_by_devt(dev_t dev)
{
struct ports_device *portdev;
struct port *port;
unsigned long flags;
spin_lock_irqsave(&pdrvdata_lock, flags);
list_for_each_entry(portdev, &pdrvdata.portdevs, list) {
port = find_port_by_devt_in_portdev(portdev, dev);
if (port)
goto out;
}
port = NULL;
out:
spin_unlock_irqrestore(&pdrvdata_lock, flags);
return port;
}
static struct port *find_port_by_id(struct ports_device *portdev, u32 id)
{
struct port *port;
unsigned long flags;
spin_lock_irqsave(&portdev->ports_lock, flags);
list_for_each_entry(port, &portdev->ports, list)
if (port->id == id)
goto out;
port = NULL;
out:
spin_unlock_irqrestore(&portdev->ports_lock, flags);
return port;
}
static struct port *find_port_by_vq(struct ports_device *portdev,
struct virtqueue *vq)
{
struct port *port;
unsigned long flags;
spin_lock_irqsave(&portdev->ports_lock, flags);
list_for_each_entry(port, &portdev->ports, list)
if (port->in_vq == vq || port->out_vq == vq)
goto out;
port = NULL;
out:
spin_unlock_irqrestore(&portdev->ports_lock, flags);
return port;
}
static bool is_console_port(struct port *port)
{
if (port->cons.hvc)
return true;
return false;
}
static bool is_rproc_serial(const struct virtio_device *vdev)
{
return is_rproc_enabled && vdev->id.device == VIRTIO_ID_RPROC_SERIAL;
}
static inline bool use_multiport(struct ports_device *portdev)
{
/*
* This condition can be true when put_chars is called from
* early_init
*/
if (!portdev->vdev)
return false;
return __virtio_test_bit(portdev->vdev, VIRTIO_CONSOLE_F_MULTIPORT);
}
static DEFINE_SPINLOCK(dma_bufs_lock);
static LIST_HEAD(pending_free_dma_bufs);
static void free_buf(struct port_buffer *buf, bool can_sleep)
{
unsigned int i;
for (i = 0; i < buf->sgpages; i++) {
struct page *page = sg_page(&buf->sg[i]);
if (!page)
break;
put_page(page);
}
if (!buf->dev) {
kfree(buf->buf);
} else if (is_rproc_enabled) {
unsigned long flags;
/* dma_free_coherent requires interrupts to be enabled. */
if (!can_sleep) {
/* queue up dma-buffers to be freed later */
spin_lock_irqsave(&dma_bufs_lock, flags);
list_add_tail(&buf->list, &pending_free_dma_bufs);
spin_unlock_irqrestore(&dma_bufs_lock, flags);
return;
}
dma_free_coherent(buf->dev, buf->size, buf->buf, buf->dma);
/* Release device refcnt and allow it to be freed */
put_device(buf->dev);
}
kfree(buf);
}
static void reclaim_dma_bufs(void)
{
unsigned long flags;
struct port_buffer *buf, *tmp;
LIST_HEAD(tmp_list);
if (list_empty(&pending_free_dma_bufs))
return;
/* Create a copy of the pending_free_dma_bufs while holding the lock */
spin_lock_irqsave(&dma_bufs_lock, flags);
list_cut_position(&tmp_list, &pending_free_dma_bufs,
pending_free_dma_bufs.prev);
spin_unlock_irqrestore(&dma_bufs_lock, flags);
/* Release the dma buffers, without irqs enabled */
list_for_each_entry_safe(buf, tmp, &tmp_list, list) {
list_del(&buf->list);
free_buf(buf, true);
}
}
static struct port_buffer *alloc_buf(struct virtqueue *vq, size_t buf_size,
int pages)
{
struct port_buffer *buf;
reclaim_dma_bufs();
/*
* Allocate buffer and the sg list. The sg list array is allocated
* directly after the port_buffer struct.
*/
buf = kmalloc(sizeof(*buf) + sizeof(struct scatterlist) * pages,
GFP_KERNEL);
if (!buf)
goto fail;
buf->sgpages = pages;
if (pages > 0) {
buf->dev = NULL;
buf->buf = NULL;
return buf;
}
if (is_rproc_serial(vq->vdev)) {
/*
* Allocate DMA memory from ancestor. When a virtio
* device is created by remoteproc, the DMA memory is
* associated with the grandparent device:
* vdev => rproc => platform-dev.
* The code here would have been less quirky if
* DMA_MEMORY_INCLUDES_CHILDREN had been supported
* in dma-coherent.c
*/
if (!vq->vdev->dev.parent || !vq->vdev->dev.parent->parent)
goto free_buf;
buf->dev = vq->vdev->dev.parent->parent;
/* Increase device refcnt to avoid freeing it */
get_device(buf->dev);
buf->buf = dma_alloc_coherent(buf->dev, buf_size, &buf->dma,
GFP_KERNEL);
} else {
buf->dev = NULL;
buf->buf = kmalloc(buf_size, GFP_KERNEL);
}
if (!buf->buf)
goto free_buf;
buf->len = 0;
buf->offset = 0;
buf->size = buf_size;
return buf;
free_buf:
kfree(buf);
fail:
return NULL;
}
/* Callers should take appropriate locks */
static struct port_buffer *get_inbuf(struct port *port)
{
struct port_buffer *buf;
unsigned int len;
if (port->inbuf)
return port->inbuf;
buf = virtqueue_get_buf(port->in_vq, &len);
if (buf) {
buf->len = len;
buf->offset = 0;
port->stats.bytes_received += len;
}
return buf;
}
/*
* Create a scatter-gather list representing our input buffer and put
* it in the queue.
*
* Callers should take appropriate locks.
*/
static int add_inbuf(struct virtqueue *vq, struct port_buffer *buf)
{
struct scatterlist sg[1];
int ret;
sg_init_one(sg, buf->buf, buf->size);
ret = virtqueue_add_inbuf(vq, sg, 1, buf, GFP_ATOMIC);
virtqueue_kick(vq);
if (!ret)
ret = vq->num_free;
return ret;
}
/* Discard any unread data this port has. Callers lockers. */
static void discard_port_data(struct port *port)
{
struct port_buffer *buf;
unsigned int err;
if (!port->portdev) {
/* Device has been unplugged. vqs are already gone. */
return;
}
buf = get_inbuf(port);
err = 0;
while (buf) {
port->stats.bytes_discarded += buf->len - buf->offset;
if (add_inbuf(port->in_vq, buf) < 0) {
err++;
free_buf(buf, false);
}
port->inbuf = NULL;
buf = get_inbuf(port);
}
if (err)
dev_warn(port->dev, "Errors adding %d buffers back to vq\n",
err);
}
static bool port_has_data(struct port *port)
{
unsigned long flags;
bool ret;
ret = false;
spin_lock_irqsave(&port->inbuf_lock, flags);
port->inbuf = get_inbuf(port);
if (port->inbuf)
ret = true;
spin_unlock_irqrestore(&port->inbuf_lock, flags);
return ret;
}
static ssize_t __send_control_msg(struct ports_device *portdev, u32 port_id,
unsigned int event, unsigned int value)
{
struct scatterlist sg[1];
struct virtqueue *vq;
unsigned int len;
if (!use_multiport(portdev))
return 0;
vq = portdev->c_ovq;
spin_lock(&portdev->c_ovq_lock);
portdev->cpkt.id = cpu_to_virtio32(portdev->vdev, port_id);
portdev->cpkt.event = cpu_to_virtio16(portdev->vdev, event);
portdev->cpkt.value = cpu_to_virtio16(portdev->vdev, value);
sg_init_one(sg, &portdev->cpkt, sizeof(struct virtio_console_control));
if (virtqueue_add_outbuf(vq, sg, 1, &portdev->cpkt, GFP_ATOMIC) == 0) {
virtqueue_kick(vq);
while (!virtqueue_get_buf(vq, &len)
&& !virtqueue_is_broken(vq))
cpu_relax();
}
spin_unlock(&portdev->c_ovq_lock);
return 0;
}
static ssize_t send_control_msg(struct port *port, unsigned int event,
unsigned int value)
{
/* Did the port get unplugged before userspace closed it? */
if (port->portdev)
return __send_control_msg(port->portdev, port->id, event, value);
return 0;
}
/* Callers must take the port->outvq_lock */
static void reclaim_consumed_buffers(struct port *port)
{
struct port_buffer *buf;
unsigned int len;
if (!port->portdev) {
/* Device has been unplugged. vqs are already gone. */
return;
}
while ((buf = virtqueue_get_buf(port->out_vq, &len))) {
free_buf(buf, false);
port->outvq_full = false;
}
}
static ssize_t __send_to_port(struct port *port, struct scatterlist *sg,
int nents, size_t in_count,
void *data, bool nonblock)
{
struct virtqueue *out_vq;
int err;
unsigned long flags;
unsigned int len;
out_vq = port->out_vq;
spin_lock_irqsave(&port->outvq_lock, flags);
reclaim_consumed_buffers(port);
err = virtqueue_add_outbuf(out_vq, sg, nents, data, GFP_ATOMIC);
/* Tell Host to go! */
virtqueue_kick(out_vq);
if (err) {
in_count = 0;
goto done;
}
if (out_vq->num_free == 0)
port->outvq_full = true;
if (nonblock)
goto done;
/*
* Wait till the host acknowledges it pushed out the data we
* sent. This is done for data from the hvc_console; the tty
* operations are performed with spinlocks held so we can't
* sleep here. An alternative would be to copy the data to a
* buffer and relax the spinning requirement. The downside is
* we need to kmalloc a GFP_ATOMIC buffer each time the
* console driver writes something out.
*/
while (!virtqueue_get_buf(out_vq, &len)
&& !virtqueue_is_broken(out_vq))
cpu_relax();
done:
spin_unlock_irqrestore(&port->outvq_lock, flags);
port->stats.bytes_sent += in_count;
/*
* We're expected to return the amount of data we wrote -- all
* of it
*/
return in_count;
}
/*
* Give out the data that's requested from the buffer that we have
* queued up.
*/
static ssize_t fill_readbuf(struct port *port, char __user *out_buf,
size_t out_count, bool to_user)
{
struct port_buffer *buf;
unsigned long flags;
if (!out_count || !port_has_data(port))
return 0;
buf = port->inbuf;
out_count = min(out_count, buf->len - buf->offset);
if (to_user) {
ssize_t ret;
ret = copy_to_user(out_buf, buf->buf + buf->offset, out_count);
if (ret)
return -EFAULT;
} else {
memcpy((__force char *)out_buf, buf->buf + buf->offset,
out_count);
}
buf->offset += out_count;
if (buf->offset == buf->len) {
/*
* We're done using all the data in this buffer.
* Re-queue so that the Host can send us more data.
*/
spin_lock_irqsave(&port->inbuf_lock, flags);
port->inbuf = NULL;
if (add_inbuf(port->in_vq, buf) < 0)
dev_warn(port->dev, "failed add_buf\n");
spin_unlock_irqrestore(&port->inbuf_lock, flags);
}
/* Return the number of bytes actually copied */
return out_count;
}
/* The condition that must be true for polling to end */
static bool will_read_block(struct port *port)
{
if (!port->guest_connected) {
/* Port got hot-unplugged. Let's exit. */
return false;
}
return !port_has_data(port) && port->host_connected;
}
static bool will_write_block(struct port *port)
{
bool ret;
if (!port->guest_connected) {
/* Port got hot-unplugged. Let's exit. */
return false;
}
if (!port->host_connected)
return true;
spin_lock_irq(&port->outvq_lock);
/*
* Check if the Host has consumed any buffers since we last
* sent data (this is only applicable for nonblocking ports).
*/
reclaim_consumed_buffers(port);
ret = port->outvq_full;
spin_unlock_irq(&port->outvq_lock);
return ret;
}
static ssize_t port_fops_read(struct file *filp, char __user *ubuf,
size_t count, loff_t *offp)
{
struct port *port;
ssize_t ret;
port = filp->private_data;
/* Port is hot-unplugged. */
if (!port->guest_connected)
return -ENODEV;
if (!port_has_data(port)) {
/*
* If nothing's connected on the host just return 0 in
* case of list_empty; this tells the userspace app
* that there's no connection
*/
if (!port->host_connected)
return 0;
if (filp->f_flags & O_NONBLOCK)
return -EAGAIN;
ret = wait_event_freezable(port->waitqueue,
!will_read_block(port));
if (ret < 0)
return ret;
}
/* Port got hot-unplugged while we were waiting above. */
if (!port->guest_connected)
return -ENODEV;
/*
* We could've received a disconnection message while we were
* waiting for more data.
*
* This check is not clubbed in the if() statement above as we
* might receive some data as well as the host could get
* disconnected after we got woken up from our wait. So we
* really want to give off whatever data we have and only then
* check for host_connected.
*/
if (!port_has_data(port) && !port->host_connected)
return 0;
return fill_readbuf(port, ubuf, count, true);
}
static int wait_port_writable(struct port *port, bool nonblock)
{
int ret;
if (will_write_block(port)) {
if (nonblock)
return -EAGAIN;
ret = wait_event_freezable(port->waitqueue,
!will_write_block(port));
if (ret < 0)
return ret;
}
/* Port got hot-unplugged. */
if (!port->guest_connected)
return -ENODEV;
return 0;
}
static ssize_t port_fops_write(struct file *filp, const char __user *ubuf,
size_t count, loff_t *offp)
{
struct port *port;
struct port_buffer *buf;
ssize_t ret;
bool nonblock;
struct scatterlist sg[1];
/* Userspace could be out to fool us */
if (!count)
return 0;
port = filp->private_data;
nonblock = filp->f_flags & O_NONBLOCK;
ret = wait_port_writable(port, nonblock);
if (ret < 0)
return ret;
count = min((size_t)(32 * 1024), count);
buf = alloc_buf(port->out_vq, count, 0);
if (!buf)
return -ENOMEM;
ret = copy_from_user(buf->buf, ubuf, count);
if (ret) {
ret = -EFAULT;
goto free_buf;
}
/*
* We now ask send_buf() to not spin for generic ports -- we
* can re-use the same code path that non-blocking file
* descriptors take for blocking file descriptors since the
* wait is already done and we're certain the write will go
* through to the host.
*/
nonblock = true;
sg_init_one(sg, buf->buf, count);
ret = __send_to_port(port, sg, 1, count, buf, nonblock);
if (nonblock && ret > 0)
goto out;
free_buf:
free_buf(buf, true);
out:
return ret;
}
struct sg_list {
unsigned int n;
unsigned int size;
size_t len;
struct scatterlist *sg;
};
static int pipe_to_sg(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
struct splice_desc *sd)
{
struct sg_list *sgl = sd->u.data;
unsigned int offset, len;
if (sgl->n == sgl->size)
return 0;
/* Try lock this page */
if (pipe_buf_steal(pipe, buf) == 0) {
/* Get reference and unlock page for moving */
get_page(buf->page);
unlock_page(buf->page);
len = min(buf->len, sd->len);
sg_set_page(&(sgl->sg[sgl->n]), buf->page, len, buf->offset);
} else {
/* Failback to copying a page */
struct page *page = alloc_page(GFP_KERNEL);
char *src;
if (!page)
return -ENOMEM;
offset = sd->pos & ~PAGE_MASK;
len = sd->len;
if (len + offset > PAGE_SIZE)
len = PAGE_SIZE - offset;
src = kmap_atomic(buf->page);
memcpy(page_address(page) + offset, src + buf->offset, len);
kunmap_atomic(src);
sg_set_page(&(sgl->sg[sgl->n]), page, len, offset);
}
sgl->n++;
sgl->len += len;
return len;
}
/* Faster zero-copy write by splicing */
static ssize_t port_fops_splice_write(struct pipe_inode_info *pipe,
struct file *filp, loff_t *ppos,
size_t len, unsigned int flags)
{
struct port *port = filp->private_data;
struct sg_list sgl;
ssize_t ret;
struct port_buffer *buf;
struct splice_desc sd = {
.total_len = len,
.flags = flags,
.pos = *ppos,
.u.data = &sgl,
};
/*
* Rproc_serial does not yet support splice. To support splice
* pipe_to_sg() must allocate dma-buffers and copy content from
* regular pages to dma pages. And alloc_buf and free_buf must
* support allocating and freeing such a list of dma-buffers.
*/
if (is_rproc_serial(port->out_vq->vdev))
return -EINVAL;
/*
* pipe->nrbufs == 0 means there are no data to transfer,
* so this returns just 0 for no data.
*/
pipe_lock(pipe);
if (!pipe->nrbufs) {
ret = 0;
goto error_out;
}
ret = wait_port_writable(port, filp->f_flags & O_NONBLOCK);
if (ret < 0)
goto error_out;
buf = alloc_buf(port->out_vq, 0, pipe->nrbufs);
if (!buf) {
ret = -ENOMEM;
goto error_out;
}
sgl.n = 0;
sgl.len = 0;
sgl.size = pipe->nrbufs;
sgl.sg = buf->sg;
sg_init_table(sgl.sg, sgl.size);
ret = __splice_from_pipe(pipe, &sd, pipe_to_sg);
pipe_unlock(pipe);
if (likely(ret > 0))
ret = __send_to_port(port, buf->sg, sgl.n, sgl.len, buf, true);
if (unlikely(ret <= 0))
free_buf(buf, true);
return ret;
error_out:
pipe_unlock(pipe);
return ret;
}
static unsigned int port_fops_poll(struct file *filp, poll_table *wait)
{
struct port *port;
unsigned int ret;
port = filp->private_data;
poll_wait(filp, &port->waitqueue, wait);
if (!port->guest_connected) {
/* Port got unplugged */
return POLLHUP;
}
ret = 0;
if (!will_read_block(port))
ret |= POLLIN | POLLRDNORM;
if (!will_write_block(port))
ret |= POLLOUT;
if (!port->host_connected)
ret |= POLLHUP;
return ret;
}
static void remove_port(struct kref *kref);
static int port_fops_release(struct inode *inode, struct file *filp)
{
struct port *port;
port = filp->private_data;
/* Notify host of port being closed */
send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 0);
spin_lock_irq(&port->inbuf_lock);
port->guest_connected = false;
discard_port_data(port);
spin_unlock_irq(&port->inbuf_lock);
spin_lock_irq(&port->outvq_lock);
reclaim_consumed_buffers(port);
spin_unlock_irq(&port->outvq_lock);
reclaim_dma_bufs();
/*
* Locks aren't necessary here as a port can't be opened after
* unplug, and if a port isn't unplugged, a kref would already
* exist for the port. Plus, taking ports_lock here would
* create a dependency on other locks taken by functions
* inside remove_port if we're the last holder of the port,
* creating many problems.
*/
kref_put(&port->kref, remove_port);
return 0;
}
static int port_fops_open(struct inode *inode, struct file *filp)
{
struct cdev *cdev = inode->i_cdev;
struct port *port;
int ret;
/* We get the port with a kref here */
port = find_port_by_devt(cdev->dev);
if (!port) {
/* Port was unplugged before we could proceed */
return -ENXIO;
}
filp->private_data = port;
/*
* Don't allow opening of console port devices -- that's done
* via /dev/hvc
*/
if (is_console_port(port)) {
ret = -ENXIO;
goto out;
}
/* Allow only one process to open a particular port at a time */
spin_lock_irq(&port->inbuf_lock);
if (port->guest_connected) {
spin_unlock_irq(&port->inbuf_lock);
ret = -EBUSY;
goto out;
}
port->guest_connected = true;
spin_unlock_irq(&port->inbuf_lock);
spin_lock_irq(&port->outvq_lock);
/*
* There might be a chance that we missed reclaiming a few
* buffers in the window of the port getting previously closed
* and opening now.
*/
reclaim_consumed_buffers(port);
spin_unlock_irq(&port->outvq_lock);
nonseekable_open(inode, filp);
/* Notify host of port being opened */
send_control_msg(filp->private_data, VIRTIO_CONSOLE_PORT_OPEN, 1);
return 0;
out:
kref_put(&port->kref, remove_port);
return ret;
}
static int port_fops_fasync(int fd, struct file *filp, int mode)
{
struct port *port;
port = filp->private_data;
return fasync_helper(fd, filp, mode, &port->async_queue);
}
/*
* The file operations that we support: programs in the guest can open
* a console device, read from it, write to it, poll for data and
* close it. The devices are at
* /dev/vport<device number>p<port number>
*/
static const struct file_operations port_fops = {
.owner = THIS_MODULE,
.open = port_fops_open,
.read = port_fops_read,
.write = port_fops_write,
.splice_write = port_fops_splice_write,
.poll = port_fops_poll,
.release = port_fops_release,
.fasync = port_fops_fasync,
.llseek = no_llseek,
};
/*
* The put_chars() callback is pretty straightforward.
*
* We turn the characters into a scatter-gather list, add it to the
* output queue and then kick the Host. Then we sit here waiting for
* it to finish: inefficient in theory, but in practice
* implementations will do it immediately (lguest's Launcher does).
*/
static int put_chars(u32 vtermno, const char *buf, int count)
{
struct port *port;
struct scatterlist sg[1];
if (unlikely(early_put_chars))
return early_put_chars(vtermno, buf, count);
port = find_port_by_vtermno(vtermno);
if (!port)
return -EPIPE;
sg_init_one(sg, buf, count);
return __send_to_port(port, sg, 1, count, (void *)buf, false);
}
/*
* get_chars() is the callback from the hvc_console infrastructure
* when an interrupt is received.
*
* We call out to fill_readbuf that gets us the required data from the
* buffers that are queued up.
*/
static int get_chars(u32 vtermno, char *buf, int count)
{
struct port *port;
/* If we've not set up the port yet, we have no input to give. */
if (unlikely(early_put_chars))
return 0;
port = find_port_by_vtermno(vtermno);
if (!port)
return -EPIPE;
/* If we don't have an input queue yet, we can't get input. */
BUG_ON(!port->in_vq);
return fill_readbuf(port, (__force char __user *)buf, count, false);
}
static void resize_console(struct port *port)
{
struct virtio_device *vdev;
/* The port could have been hot-unplugged */
if (!port || !is_console_port(port))
return;
vdev = port->portdev->vdev;
/* Don't test F_SIZE at all if we're rproc: not a valid feature! */
if (!is_rproc_serial(vdev) &&
virtio_has_feature(vdev, VIRTIO_CONSOLE_F_SIZE))
hvc_resize(port->cons.hvc, port->cons.ws);
}
/* We set the configuration at this point, since we now have a tty */
static int notifier_add_vio(struct hvc_struct *hp, int data)
{
struct port *port;
port = find_port_by_vtermno(hp->vtermno);
if (!port)
return -EINVAL;
hp->irq_requested = 1;
resize_console(port);
return 0;
}
static void notifier_del_vio(struct hvc_struct *hp, int data)
{
hp->irq_requested = 0;
}
/* The operations for console ports. */
static const struct hv_ops hv_ops = {
.get_chars = get_chars,
.put_chars = put_chars,
.notifier_add = notifier_add_vio,
.notifier_del = notifier_del_vio,
.notifier_hangup = notifier_del_vio,
};
/*
* Console drivers are initialized very early so boot messages can go
* out, so we do things slightly differently from the generic virtio
* initialization of the net and block drivers.
*
* At this stage, the console is output-only. It's too early to set
* up a virtqueue, so we let the drivers do some boutique early-output
* thing.
*/
int __init virtio_cons_early_init(int (*put_chars)(u32, const char *, int))
{
early_put_chars = put_chars;
return hvc_instantiate(0, 0, &hv_ops);
}
static int init_port_console(struct port *port)
{
int ret;
/*
* The Host's telling us this port is a console port. Hook it
* up with an hvc console.
*
* To set up and manage our virtual console, we call
* hvc_alloc().
*
* The first argument of hvc_alloc() is the virtual console
* number. The second argument is the parameter for the
* notification mechanism (like irq number). We currently
* leave this as zero, virtqueues have implicit notifications.
*
* The third argument is a "struct hv_ops" containing the
* put_chars() get_chars(), notifier_add() and notifier_del()
* pointers. The final argument is the output buffer size: we
* can do any size, so we put PAGE_SIZE here.
*/
port->cons.vtermno = pdrvdata.next_vtermno;
port->cons.hvc = hvc_alloc(port->cons.vtermno, 0, &hv_ops, PAGE_SIZE);
if (IS_ERR(port->cons.hvc)) {
ret = PTR_ERR(port->cons.hvc);
dev_err(port->dev,
"error %d allocating hvc for port\n", ret);
port->cons.hvc = NULL;
return ret;
}
spin_lock_irq(&pdrvdata_lock);
pdrvdata.next_vtermno++;
list_add_tail(&port->cons.list, &pdrvdata.consoles);
spin_unlock_irq(&pdrvdata_lock);
port->guest_connected = true;
/*
* Start using the new console output if this is the first
* console to come up.
*/
if (early_put_chars)
early_put_chars = NULL;
/* Notify host of port being opened */
send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
return 0;
}
static ssize_t show_port_name(struct device *dev,
struct device_attribute *attr, char *buffer)
{
struct port *port;
port = dev_get_drvdata(dev);
return sprintf(buffer, "%s\n", port->name);
}
static DEVICE_ATTR(name, S_IRUGO, show_port_name, NULL);
static struct attribute *port_sysfs_entries[] = {
&dev_attr_name.attr,
NULL
};
static struct attribute_group port_attribute_group = {
.name = NULL, /* put in device directory */
.attrs = port_sysfs_entries,
};
static ssize_t debugfs_read(struct file *filp, char __user *ubuf,
size_t count, loff_t *offp)
{
struct port *port;
char *buf;
ssize_t ret, out_offset, out_count;
out_count = 1024;
buf = kmalloc(out_count, GFP_KERNEL);
if (!buf)
return -ENOMEM;
port = filp->private_data;
out_offset = 0;
out_offset += snprintf(buf + out_offset, out_count,
"name: %s\n", port->name ? port->name : "");
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"guest_connected: %d\n", port->guest_connected);
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"host_connected: %d\n", port->host_connected);
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"outvq_full: %d\n", port->outvq_full);
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"bytes_sent: %lu\n", port->stats.bytes_sent);
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"bytes_received: %lu\n",
port->stats.bytes_received);
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"bytes_discarded: %lu\n",
port->stats.bytes_discarded);
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"is_console: %s\n",
is_console_port(port) ? "yes" : "no");
out_offset += snprintf(buf + out_offset, out_count - out_offset,
"console_vtermno: %u\n", port->cons.vtermno);
ret = simple_read_from_buffer(ubuf, count, offp, buf, out_offset);
kfree(buf);
return ret;
}
static const struct file_operations port_debugfs_ops = {
.owner = THIS_MODULE,
.open = simple_open,
.read = debugfs_read,
};
static void set_console_size(struct port *port, u16 rows, u16 cols)
{
if (!port || !is_console_port(port))
return;
port->cons.ws.ws_row = rows;
port->cons.ws.ws_col = cols;
}
static unsigned int fill_queue(struct virtqueue *vq, spinlock_t *lock)
{
struct port_buffer *buf;
unsigned int nr_added_bufs;
int ret;
nr_added_bufs = 0;
do {
buf = alloc_buf(vq, PAGE_SIZE, 0);
if (!buf)
break;
spin_lock_irq(lock);
ret = add_inbuf(vq, buf);
if (ret < 0) {
spin_unlock_irq(lock);
free_buf(buf, true);
break;
}
nr_added_bufs++;
spin_unlock_irq(lock);
} while (ret > 0);
return nr_added_bufs;
}
static void send_sigio_to_port(struct port *port)
{
if (port->async_queue && port->guest_connected)
kill_fasync(&port->async_queue, SIGIO, POLL_OUT);
}
static int add_port(struct ports_device *portdev, u32 id)
{
char debugfs_name[16];
struct port *port;
struct port_buffer *buf;
dev_t devt;
unsigned int nr_added_bufs;
int err;
port = kmalloc(sizeof(*port), GFP_KERNEL);
if (!port) {
err = -ENOMEM;
goto fail;
}
kref_init(&port->kref);
port->portdev = portdev;
port->id = id;
port->name = NULL;
port->inbuf = NULL;
port->cons.hvc = NULL;
port->async_queue = NULL;
port->cons.ws.ws_row = port->cons.ws.ws_col = 0;
port->host_connected = port->guest_connected = false;
port->stats = (struct port_stats) { 0 };
port->outvq_full = false;
port->in_vq = portdev->in_vqs[port->id];
port->out_vq = portdev->out_vqs[port->id];
port->cdev = cdev_alloc();
if (!port->cdev) {
dev_err(&port->portdev->vdev->dev, "Error allocating cdev\n");
err = -ENOMEM;
goto free_port;
}
port->cdev->ops = &port_fops;
devt = MKDEV(portdev->chr_major, id);
err = cdev_add(port->cdev, devt, 1);
if (err < 0) {
dev_err(&port->portdev->vdev->dev,
"Error %d adding cdev for port %u\n", err, id);
goto free_cdev;
}
port->dev = device_create(pdrvdata.class, &port->portdev->vdev->dev,
devt, port, "vport%up%u",
port->portdev->vdev->index, id);
if (IS_ERR(port->dev)) {
err = PTR_ERR(port->dev);
dev_err(&port->portdev->vdev->dev,
"Error %d creating device for port %u\n",
err, id);
goto free_cdev;
}
spin_lock_init(&port->inbuf_lock);
spin_lock_init(&port->outvq_lock);
init_waitqueue_head(&port->waitqueue);
/* Fill the in_vq with buffers so the host can send us data. */
nr_added_bufs = fill_queue(port->in_vq, &port->inbuf_lock);
if (!nr_added_bufs) {
dev_err(port->dev, "Error allocating inbufs\n");
err = -ENOMEM;
goto free_device;
}
if (is_rproc_serial(port->portdev->vdev))
/*
* For rproc_serial assume remote processor is connected.
* rproc_serial does not want the console port, only
* the generic port implementation.
*/
port->host_connected = true;
else if (!use_multiport(port->portdev)) {
/*
* If we're not using multiport support,
* this has to be a console port.
*/
err = init_port_console(port);
if (err)
goto free_inbufs;
}
spin_lock_irq(&portdev->ports_lock);
list_add_tail(&port->list, &port->portdev->ports);
spin_unlock_irq(&portdev->ports_lock);
/*
* Tell the Host we're set so that it can send us various
* configuration parameters for this port (eg, port name,
* caching, whether this is a console port, etc.)
*/
send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
if (pdrvdata.debugfs_dir) {
/*
* Finally, create the debugfs file that we can use to
* inspect a port's state at any time
*/
snprintf(debugfs_name, sizeof(debugfs_name), "vport%up%u",
port->portdev->vdev->index, id);
port->debugfs_file = debugfs_create_file(debugfs_name, 0444,
pdrvdata.debugfs_dir,
port,
&port_debugfs_ops);
}
return 0;
free_inbufs:
while ((buf = virtqueue_detach_unused_buf(port->in_vq)))
free_buf(buf, true);
free_device:
device_destroy(pdrvdata.class, port->dev->devt);
free_cdev:
cdev_del(port->cdev);
free_port:
kfree(port);
fail:
/* The host might want to notify management sw about port add failure */
__send_control_msg(portdev, id, VIRTIO_CONSOLE_PORT_READY, 0);
return err;
}
/* No users remain, remove all port-specific data. */
static void remove_port(struct kref *kref)
{
struct port *port;
port = container_of(kref, struct port, kref);
kfree(port);
}
static void remove_port_data(struct port *port)
{
struct port_buffer *buf;
spin_lock_irq(&port->inbuf_lock);
/* Remove unused data this port might have received. */
discard_port_data(port);
spin_unlock_irq(&port->inbuf_lock);
/* Remove buffers we queued up for the Host to send us data in. */
do {
spin_lock_irq(&port->inbuf_lock);
buf = virtqueue_detach_unused_buf(port->in_vq);
spin_unlock_irq(&port->inbuf_lock);
if (buf)
free_buf(buf, true);
} while (buf);
spin_lock_irq(&port->outvq_lock);
reclaim_consumed_buffers(port);
spin_unlock_irq(&port->outvq_lock);
/* Free pending buffers from the out-queue. */
do {
spin_lock_irq(&port->outvq_lock);
buf = virtqueue_detach_unused_buf(port->out_vq);
spin_unlock_irq(&port->outvq_lock);
if (buf)
free_buf(buf, true);
} while (buf);
}
/*
* Port got unplugged. Remove port from portdev's list and drop the
* kref reference. If no userspace has this port opened, it will
* result in immediate removal the port.
*/
static void unplug_port(struct port *port)
{
spin_lock_irq(&port->portdev->ports_lock);
list_del(&port->list);
spin_unlock_irq(&port->portdev->ports_lock);
spin_lock_irq(&port->inbuf_lock);
if (port->guest_connected) {
/* Let the app know the port is going down. */
send_sigio_to_port(port);
/* Do this after sigio is actually sent */
port->guest_connected = false;
port->host_connected = false;
wake_up_interruptible(&port->waitqueue);
}
spin_unlock_irq(&port->inbuf_lock);
if (is_console_port(port)) {
spin_lock_irq(&pdrvdata_lock);
list_del(&port->cons.list);
spin_unlock_irq(&pdrvdata_lock);
hvc_remove(port->cons.hvc);
}
remove_port_data(port);
/*
* We should just assume the device itself has gone off --
* else a close on an open port later will try to send out a
* control message.
*/
port->portdev = NULL;
sysfs_remove_group(&port->dev->kobj, &port_attribute_group);
device_destroy(pdrvdata.class, port->dev->devt);
cdev_del(port->cdev);
debugfs_remove(port->debugfs_file);
kfree(port->name);
/*
* Locks around here are not necessary - a port can't be
* opened after we removed the port struct from ports_list
* above.
*/
kref_put(&port->kref, remove_port);
}
/* Any private messages that the Host and Guest want to share */
static void handle_control_message(struct virtio_device *vdev,
struct ports_device *portdev,
struct port_buffer *buf)
{
struct virtio_console_control *cpkt;
struct port *port;
size_t name_size;
int err;
cpkt = (struct virtio_console_control *)(buf->buf + buf->offset);
port = find_port_by_id(portdev, virtio32_to_cpu(vdev, cpkt->id));
if (!port &&
cpkt->event != cpu_to_virtio16(vdev, VIRTIO_CONSOLE_PORT_ADD)) {
/* No valid header at start of buffer. Drop it. */
dev_dbg(&portdev->vdev->dev,
"Invalid index %u in control packet\n", cpkt->id);
return;
}
switch (virtio16_to_cpu(vdev, cpkt->event)) {
case VIRTIO_CONSOLE_PORT_ADD:
if (port) {
dev_dbg(&portdev->vdev->dev,
"Port %u already added\n", port->id);
send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
break;
}
if (virtio32_to_cpu(vdev, cpkt->id) >=
portdev->max_nr_ports) {
dev_warn(&portdev->vdev->dev,
"Request for adding port with "
"out-of-bound id %u, max. supported id: %u\n",
cpkt->id, portdev->max_nr_ports - 1);
break;
}
add_port(portdev, virtio32_to_cpu(vdev, cpkt->id));
break;
case VIRTIO_CONSOLE_PORT_REMOVE:
unplug_port(port);
break;
case VIRTIO_CONSOLE_CONSOLE_PORT:
if (!cpkt->value)
break;
if (is_console_port(port))
break;
init_port_console(port);
complete(&early_console_added);
/*
* Could remove the port here in case init fails - but
* have to notify the host first.
*/
break;
case VIRTIO_CONSOLE_RESIZE: {
struct {
__u16 rows;
__u16 cols;
} size;
if (!is_console_port(port))
break;
memcpy(&size, buf->buf + buf->offset + sizeof(*cpkt),
sizeof(size));
set_console_size(port, size.rows, size.cols);
port->cons.hvc->irq_requested = 1;
resize_console(port);
break;
}
case VIRTIO_CONSOLE_PORT_OPEN:
port->host_connected = virtio16_to_cpu(vdev, cpkt->value);
wake_up_interruptible(&port->waitqueue);
/*
* If the host port got closed and the host had any
* unconsumed buffers, we'll be able to reclaim them
* now.
*/
spin_lock_irq(&port->outvq_lock);
reclaim_consumed_buffers(port);
spin_unlock_irq(&port->outvq_lock);
/*
* If the guest is connected, it'll be interested in
* knowing the host connection state changed.
*/
spin_lock_irq(&port->inbuf_lock);
send_sigio_to_port(port);
spin_unlock_irq(&port->inbuf_lock);
break;
case VIRTIO_CONSOLE_PORT_NAME:
/*
* If we woke up after hibernation, we can get this
* again. Skip it in that case.
*/
if (port->name)
break;
/*
* Skip the size of the header and the cpkt to get the size
* of the name that was sent
*/
name_size = buf->len - buf->offset - sizeof(*cpkt) + 1;
port->name = kmalloc(name_size, GFP_KERNEL);
if (!port->name) {
dev_err(port->dev,
"Not enough space to store port name\n");
break;
}
strncpy(port->name, buf->buf + buf->offset + sizeof(*cpkt),
name_size - 1);
port->name[name_size - 1] = 0;
/*
* Since we only have one sysfs attribute, 'name',
* create it only if we have a name for the port.
*/
err = sysfs_create_group(&port->dev->kobj,
&port_attribute_group);
if (err) {
dev_err(port->dev,
"Error %d creating sysfs device attributes\n",
err);
} else {
/*
* Generate a udev event so that appropriate
* symlinks can be created based on udev
* rules.
*/
kobject_uevent(&port->dev->kobj, KOBJ_CHANGE);
}
break;
}
}
static void control_work_handler(struct work_struct *work)
{
struct ports_device *portdev;
struct virtqueue *vq;
struct port_buffer *buf;
unsigned int len;
portdev = container_of(work, struct ports_device, control_work);
vq = portdev->c_ivq;
spin_lock(&portdev->c_ivq_lock);
while ((buf = virtqueue_get_buf(vq, &len))) {
spin_unlock(&portdev->c_ivq_lock);
buf->len = len;
buf->offset = 0;
handle_control_message(vq->vdev, portdev, buf);
spin_lock(&portdev->c_ivq_lock);
if (add_inbuf(portdev->c_ivq, buf) < 0) {
dev_warn(&portdev->vdev->dev,
"Error adding buffer to queue\n");
free_buf(buf, false);
}
}
spin_unlock(&portdev->c_ivq_lock);
}
static void out_intr(struct virtqueue *vq)
{
struct port *port;
port = find_port_by_vq(vq->vdev->priv, vq);
if (!port)
return;
wake_up_interruptible(&port->waitqueue);
}
static void in_intr(struct virtqueue *vq)
{
struct port *port;
unsigned long flags;
port = find_port_by_vq(vq->vdev->priv, vq);
if (!port)
return;
spin_lock_irqsave(&port->inbuf_lock, flags);
port->inbuf = get_inbuf(port);
/*
* Normally the port should not accept data when the port is
* closed. For generic serial ports, the host won't (shouldn't)
* send data till the guest is connected. But this condition
* can be reached when a console port is not yet connected (no
* tty is spawned) and the other side sends out data over the
* vring, or when a remote devices start sending data before
* the ports are opened.
*
* A generic serial port will discard data if not connected,
* while console ports and rproc-serial ports accepts data at
* any time. rproc-serial is initiated with guest_connected to
* false because port_fops_open expects this. Console ports are
* hooked up with an HVC console and is initialized with
* guest_connected to true.
*/
if (!port->guest_connected && !is_rproc_serial(port->portdev->vdev))
discard_port_data(port);
/* Send a SIGIO indicating new data in case the process asked for it */
send_sigio_to_port(port);
spin_unlock_irqrestore(&port->inbuf_lock, flags);
wake_up_interruptible(&port->waitqueue);
if (is_console_port(port) && hvc_poll(port->cons.hvc))
hvc_kick();
}
static void control_intr(struct virtqueue *vq)
{
struct ports_device *portdev;
portdev = vq->vdev->priv;
schedule_work(&portdev->control_work);
}
static void config_intr(struct virtio_device *vdev)
{
struct ports_device *portdev;
portdev = vdev->priv;
if (!use_multiport(portdev))
schedule_work(&portdev->config_work);
}
static void config_work_handler(struct work_struct *work)
{
struct ports_device *portdev;
portdev = container_of(work, struct ports_device, config_work);
if (!use_multiport(portdev)) {
struct virtio_device *vdev;
struct port *port;
u16 rows, cols;
vdev = portdev->vdev;
virtio_cread(vdev, struct virtio_console_config, cols, &cols);
virtio_cread(vdev, struct virtio_console_config, rows, &rows);
port = find_port_by_id(portdev, 0);
set_console_size(port, rows, cols);
/*
* We'll use this way of resizing only for legacy
* support. For newer userspace
* (VIRTIO_CONSOLE_F_MULTPORT+), use control messages
* to indicate console size changes so that it can be
* done per-port.
*/
resize_console(port);
}
}
static int init_vqs(struct ports_device *portdev)
{
vq_callback_t **io_callbacks;
char **io_names;
struct virtqueue **vqs;
u32 i, j, nr_ports, nr_queues;
int err;
nr_ports = portdev->max_nr_ports;
nr_queues = use_multiport(portdev) ? (nr_ports + 1) * 2 : 2;
vqs = kmalloc(nr_queues * sizeof(struct virtqueue *), GFP_KERNEL);
io_callbacks = kmalloc(nr_queues * sizeof(vq_callback_t *), GFP_KERNEL);
io_names = kmalloc(nr_queues * sizeof(char *), GFP_KERNEL);
portdev->in_vqs = kmalloc(nr_ports * sizeof(struct virtqueue *),
GFP_KERNEL);
portdev->out_vqs = kmalloc(nr_ports * sizeof(struct virtqueue *),
GFP_KERNEL);
if (!vqs || !io_callbacks || !io_names || !portdev->in_vqs ||
!portdev->out_vqs) {
err = -ENOMEM;
goto free;
}
/*
* For backward compat (newer host but older guest), the host
* spawns a console port first and also inits the vqs for port
* 0 before others.
*/
j = 0;
io_callbacks[j] = in_intr;
io_callbacks[j + 1] = out_intr;
io_names[j] = "input";
io_names[j + 1] = "output";
j += 2;
if (use_multiport(portdev)) {
io_callbacks[j] = control_intr;
io_callbacks[j + 1] = NULL;
io_names[j] = "control-i";
io_names[j + 1] = "control-o";
for (i = 1; i < nr_ports; i++) {
j += 2;
io_callbacks[j] = in_intr;
io_callbacks[j + 1] = out_intr;
io_names[j] = "input";
io_names[j + 1] = "output";
}
}
/* Find the queues. */
err = portdev->vdev->config->find_vqs(portdev->vdev, nr_queues, vqs,
io_callbacks,
(const char **)io_names, NULL);
if (err)
goto free;
j = 0;
portdev->in_vqs[0] = vqs[0];
portdev->out_vqs[0] = vqs[1];
j += 2;
if (use_multiport(portdev)) {
portdev->c_ivq = vqs[j];
portdev->c_ovq = vqs[j + 1];
for (i = 1; i < nr_ports; i++) {
j += 2;
portdev->in_vqs[i] = vqs[j];
portdev->out_vqs[i] = vqs[j + 1];
}
}
kfree(io_names);
kfree(io_callbacks);
kfree(vqs);
return 0;
free:
kfree(portdev->out_vqs);
kfree(portdev->in_vqs);
kfree(io_names);
kfree(io_callbacks);
kfree(vqs);
return err;
}
static const struct file_operations portdev_fops = {
.owner = THIS_MODULE,
};
static void remove_vqs(struct ports_device *portdev)
{
portdev->vdev->config->del_vqs(portdev->vdev);
kfree(portdev->in_vqs);
kfree(portdev->out_vqs);
}
static void remove_controlq_data(struct ports_device *portdev)
{
struct port_buffer *buf;
unsigned int len;
if (!use_multiport(portdev))
return;
while ((buf = virtqueue_get_buf(portdev->c_ivq, &len)))
free_buf(buf, true);
while ((buf = virtqueue_detach_unused_buf(portdev->c_ivq)))
free_buf(buf, true);
}
/*
* Once we're further in boot, we get probed like any other virtio
* device.
*
* If the host also supports multiple console ports, we check the
* config space to see how many ports the host has spawned. We
* initialize each port found.
*/
static int virtcons_probe(struct virtio_device *vdev)
{
struct ports_device *portdev;
int err;
bool multiport;
bool early = early_put_chars != NULL;
/* We only need a config space if features are offered */
if (!vdev->config->get &&
(virtio_has_feature(vdev, VIRTIO_CONSOLE_F_SIZE)
|| virtio_has_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT))) {
dev_err(&vdev->dev, "%s failure: config access disabled\n",
__func__);
return -EINVAL;
}
/* Ensure to read early_put_chars now */
barrier();
portdev = kmalloc(sizeof(*portdev), GFP_KERNEL);
if (!portdev) {
err = -ENOMEM;
goto fail;
}
/* Attach this portdev to this virtio_device, and vice-versa. */
portdev->vdev = vdev;
vdev->priv = portdev;
portdev->chr_major = register_chrdev(0, "virtio-portsdev",
&portdev_fops);
if (portdev->chr_major < 0) {
dev_err(&vdev->dev,
"Error %d registering chrdev for device %u\n",
portdev->chr_major, vdev->index);
err = portdev->chr_major;
goto free;
}
multiport = false;
portdev->max_nr_ports = 1;
/* Don't test MULTIPORT at all if we're rproc: not a valid feature! */
if (!is_rproc_serial(vdev) &&
virtio_cread_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT,
struct virtio_console_config, max_nr_ports,
&portdev->max_nr_ports) == 0) {
multiport = true;
}
err = init_vqs(portdev);
if (err < 0) {
dev_err(&vdev->dev, "Error %d initializing vqs\n", err);
goto free_chrdev;
}
spin_lock_init(&portdev->ports_lock);
INIT_LIST_HEAD(&portdev->ports);
virtio_device_ready(portdev->vdev);
INIT_WORK(&portdev->config_work, &config_work_handler);
INIT_WORK(&portdev->control_work, &control_work_handler);
if (multiport) {
unsigned int nr_added_bufs;
spin_lock_init(&portdev->c_ivq_lock);
spin_lock_init(&portdev->c_ovq_lock);
nr_added_bufs = fill_queue(portdev->c_ivq,
&portdev->c_ivq_lock);
if (!nr_added_bufs) {
dev_err(&vdev->dev,
"Error allocating buffers for control queue\n");
err = -ENOMEM;
goto free_vqs;
}
} else {
/*
* For backward compatibility: Create a console port
* if we're running on older host.
*/
add_port(portdev, 0);
}
spin_lock_irq(&pdrvdata_lock);
list_add_tail(&portdev->list, &pdrvdata.portdevs);
spin_unlock_irq(&pdrvdata_lock);
__send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
VIRTIO_CONSOLE_DEVICE_READY, 1);
/*
* If there was an early virtio console, assume that there are no
* other consoles. We need to wait until the hvc_alloc matches the
* hvc_instantiate, otherwise tty_open will complain, resulting in
* a "Warning: unable to open an initial console" boot failure.
* Without multiport this is done in add_port above. With multiport
* this might take some host<->guest communication - thus we have to
* wait.
*/
if (multiport && early)
wait_for_completion(&early_console_added);
return 0;
free_vqs:
/* The host might want to notify mgmt sw about device add failure */
__send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
VIRTIO_CONSOLE_DEVICE_READY, 0);
remove_vqs(portdev);
free_chrdev:
unregister_chrdev(portdev->chr_major, "virtio-portsdev");
free:
kfree(portdev);
fail:
return err;
}
static void virtcons_remove(struct virtio_device *vdev)
{
struct ports_device *portdev;
struct port *port, *port2;
portdev = vdev->priv;
spin_lock_irq(&pdrvdata_lock);
list_del(&portdev->list);
spin_unlock_irq(&pdrvdata_lock);
/* Disable interrupts for vqs */
vdev->config->reset(vdev);
/* Finish up work that's lined up */
if (use_multiport(portdev))
cancel_work_sync(&portdev->control_work);
else
cancel_work_sync(&portdev->config_work);
list_for_each_entry_safe(port, port2, &portdev->ports, list)
unplug_port(port);
unregister_chrdev(portdev->chr_major, "virtio-portsdev");
/*
* When yanking out a device, we immediately lose the
* (device-side) queues. So there's no point in keeping the
* guest side around till we drop our final reference. This
* also means that any ports which are in an open state will
* have to just stop using the port, as the vqs are going
* away.
*/
remove_controlq_data(portdev);
remove_vqs(portdev);
kfree(portdev);
}
static struct virtio_device_id id_table[] = {
{ VIRTIO_ID_CONSOLE, VIRTIO_DEV_ANY_ID },
{ 0 },
};
static unsigned int features[] = {
VIRTIO_CONSOLE_F_SIZE,
VIRTIO_CONSOLE_F_MULTIPORT,
};
static struct virtio_device_id rproc_serial_id_table[] = {
#if IS_ENABLED(CONFIG_REMOTEPROC)
{ VIRTIO_ID_RPROC_SERIAL, VIRTIO_DEV_ANY_ID },
#endif
{ 0 },
};
static unsigned int rproc_serial_features[] = {
};
#ifdef CONFIG_PM_SLEEP
static int virtcons_freeze(struct virtio_device *vdev)
{
struct ports_device *portdev;
struct port *port;
portdev = vdev->priv;
vdev->config->reset(vdev);
virtqueue_disable_cb(portdev->c_ivq);
cancel_work_sync(&portdev->control_work);
cancel_work_sync(&portdev->config_work);
/*
* Once more: if control_work_handler() was running, it would
* enable the cb as the last step.
*/
virtqueue_disable_cb(portdev->c_ivq);
remove_controlq_data(portdev);
list_for_each_entry(port, &portdev->ports, list) {
virtqueue_disable_cb(port->in_vq);
virtqueue_disable_cb(port->out_vq);
/*
* We'll ask the host later if the new invocation has
* the port opened or closed.
*/
port->host_connected = false;
remove_port_data(port);
}
remove_vqs(portdev);
return 0;
}
static int virtcons_restore(struct virtio_device *vdev)
{
struct ports_device *portdev;
struct port *port;
int ret;
portdev = vdev->priv;
ret = init_vqs(portdev);
if (ret)
return ret;
virtio_device_ready(portdev->vdev);
if (use_multiport(portdev))
fill_queue(portdev->c_ivq, &portdev->c_ivq_lock);
list_for_each_entry(port, &portdev->ports, list) {
port->in_vq = portdev->in_vqs[port->id];
port->out_vq = portdev->out_vqs[port->id];
fill_queue(port->in_vq, &port->inbuf_lock);
/* Get port open/close status on the host */
send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
/*
* If a port was open at the time of suspending, we
* have to let the host know that it's still open.
*/
if (port->guest_connected)
send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
}
return 0;
}
#endif
static struct virtio_driver virtio_console = {
.feature_table = features,
.feature_table_size = ARRAY_SIZE(features),
.driver.name = KBUILD_MODNAME,
.driver.owner = THIS_MODULE,
.id_table = id_table,
.probe = virtcons_probe,
.remove = virtcons_remove,
.config_changed = config_intr,
#ifdef CONFIG_PM_SLEEP
.freeze = virtcons_freeze,
.restore = virtcons_restore,
#endif
};
static struct virtio_driver virtio_rproc_serial = {
.feature_table = rproc_serial_features,
.feature_table_size = ARRAY_SIZE(rproc_serial_features),
.driver.name = "virtio_rproc_serial",
.driver.owner = THIS_MODULE,
.id_table = rproc_serial_id_table,
.probe = virtcons_probe,
.remove = virtcons_remove,
};
static int __init init(void)
{
int err;
pdrvdata.class = class_create(THIS_MODULE, "virtio-ports");
if (IS_ERR(pdrvdata.class)) {
err = PTR_ERR(pdrvdata.class);
pr_err("Error %d creating virtio-ports class\n", err);
return err;
}
pdrvdata.debugfs_dir = debugfs_create_dir("virtio-ports", NULL);
if (!pdrvdata.debugfs_dir)
pr_warning("Error creating debugfs dir for virtio-ports\n");
INIT_LIST_HEAD(&pdrvdata.consoles);
INIT_LIST_HEAD(&pdrvdata.portdevs);
err = register_virtio_driver(&virtio_console);
if (err < 0) {
pr_err("Error %d registering virtio driver\n", err);
goto free;
}
err = register_virtio_driver(&virtio_rproc_serial);
if (err < 0) {
pr_err("Error %d registering virtio rproc serial driver\n",
err);
goto unregister;
}
return 0;
unregister:
unregister_virtio_driver(&virtio_console);
free:
debugfs_remove_recursive(pdrvdata.debugfs_dir);
class_destroy(pdrvdata.class);
return err;
}
static void __exit fini(void)
{
reclaim_dma_bufs();
unregister_virtio_driver(&virtio_console);
unregister_virtio_driver(&virtio_rproc_serial);
class_destroy(pdrvdata.class);
debugfs_remove_recursive(pdrvdata.debugfs_dir);
}
module_init(init);
module_exit(fini);
MODULE_DEVICE_TABLE(virtio, id_table);
MODULE_DESCRIPTION("Virtio console driver");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3316_0 |
crossvul-cpp_data_good_2143_1 | /*
* NET3 Protocol independent device support routines.
*
* 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.
*
* Derived from the non IP parts of dev.c 1.0.19
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Mark Evans, <evansmp@uhura.aston.ac.uk>
*
* Additional Authors:
* Florian la Roche <rzsfl@rz.uni-sb.de>
* Alan Cox <gw4pts@gw4pts.ampr.org>
* David Hinds <dahinds@users.sourceforge.net>
* Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
* Adam Sulmicki <adam@cfar.umd.edu>
* Pekka Riikonen <priikone@poesidon.pspt.fi>
*
* Changes:
* D.J. Barrow : Fixed bug where dev->refcnt gets set
* to 2 if register_netdev gets called
* before net_dev_init & also removed a
* few lines of code in the process.
* Alan Cox : device private ioctl copies fields back.
* Alan Cox : Transmit queue code does relevant
* stunts to keep the queue safe.
* Alan Cox : Fixed double lock.
* Alan Cox : Fixed promisc NULL pointer trap
* ???????? : Support the full private ioctl range
* Alan Cox : Moved ioctl permission check into
* drivers
* Tim Kordas : SIOCADDMULTI/SIOCDELMULTI
* Alan Cox : 100 backlog just doesn't cut it when
* you start doing multicast video 8)
* Alan Cox : Rewrote net_bh and list manager.
* Alan Cox : Fix ETH_P_ALL echoback lengths.
* Alan Cox : Took out transmit every packet pass
* Saved a few bytes in the ioctl handler
* Alan Cox : Network driver sets packet type before
* calling netif_rx. Saves a function
* call a packet.
* Alan Cox : Hashed net_bh()
* Richard Kooijman: Timestamp fixes.
* Alan Cox : Wrong field in SIOCGIFDSTADDR
* Alan Cox : Device lock protection.
* Alan Cox : Fixed nasty side effect of device close
* changes.
* Rudi Cilibrasi : Pass the right thing to
* set_mac_address()
* Dave Miller : 32bit quantity for the device lock to
* make it work out on a Sparc.
* Bjorn Ekwall : Added KERNELD hack.
* Alan Cox : Cleaned up the backlog initialise.
* Craig Metz : SIOCGIFCONF fix if space for under
* 1 device.
* Thomas Bogendoerfer : Return ENODEV for dev_open, if there
* is no device open function.
* Andi Kleen : Fix error reporting for SIOCGIFCONF
* Michael Chastain : Fix signed/unsigned for SIOCGIFCONF
* Cyrus Durgin : Cleaned for KMOD
* Adam Sulmicki : Bug Fix : Network Device Unload
* A network device unload needs to purge
* the backlog queue.
* Paul Rusty Russell : SIOCSIFNAME
* Pekka Riikonen : Netdev boot-time settings code
* Andrew Morton : Make unregister_netdevice wait
* indefinitely on dev->refcnt
* J Hadi Salim : - Backlog queue sampling
* - netif_rx() feedback
*/
#include <asm/uaccess.h>
#include <asm/system.h>
#include <linux/bitops.h>
#include <linux/capability.h>
#include <linux/cpu.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/hash.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/mutex.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/if_ether.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/notifier.h>
#include <linux/skbuff.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <linux/rtnetlink.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/stat.h>
#include <linux/if_bridge.h>
#include <linux/if_macvlan.h>
#include <net/dst.h>
#include <net/pkt_sched.h>
#include <net/checksum.h>
#include <net/xfrm.h>
#include <linux/highmem.h>
#include <linux/init.h>
#include <linux/kmod.h>
#include <linux/module.h>
#include <linux/netpoll.h>
#include <linux/rcupdate.h>
#include <linux/delay.h>
#include <net/wext.h>
#include <net/iw_handler.h>
#include <asm/current.h>
#include <linux/audit.h>
#include <linux/dmaengine.h>
#include <linux/err.h>
#include <linux/ctype.h>
#include <linux/if_arp.h>
#include <linux/if_vlan.h>
#include <linux/ip.h>
#include <net/ip.h>
#include <linux/ipv6.h>
#include <linux/in.h>
#include <linux/jhash.h>
#include <linux/random.h>
#include <trace/events/napi.h>
#include <linux/pci.h>
#include "net-sysfs.h"
/* Instead of increasing this, you should create a hash table. */
#define MAX_GRO_SKBS 8
/* This should be increased if a protocol with a bigger head is added. */
#define GRO_MAX_HEAD (MAX_HEADER + 128)
/*
* The list of packet types we will receive (as opposed to discard)
* and the routines to invoke.
*
* Why 16. Because with 16 the only overlap we get on a hash of the
* low nibble of the protocol value is RARP/SNAP/X.25.
*
* NOTE: That is no longer true with the addition of VLAN tags. Not
* sure which should go first, but I bet it won't make much
* difference if we are running VLANs. The good news is that
* this protocol won't be in the list unless compiled in, so
* the average user (w/out VLANs) will not be adversely affected.
* --BLG
*
* 0800 IP
* 8100 802.1Q VLAN
* 0001 802.3
* 0002 AX.25
* 0004 802.2
* 8035 RARP
* 0005 SNAP
* 0805 X.25
* 0806 ARP
* 8137 IPX
* 0009 Localtalk
* 86DD IPv6
*/
#define PTYPE_HASH_SIZE (16)
#define PTYPE_HASH_MASK (PTYPE_HASH_SIZE - 1)
static DEFINE_SPINLOCK(ptype_lock);
static struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
static struct list_head ptype_all __read_mostly; /* Taps */
/*
* The @dev_base_head list is protected by @dev_base_lock and the rtnl
* semaphore.
*
* Pure readers hold dev_base_lock for reading, or rcu_read_lock()
*
* Writers must hold the rtnl semaphore while they loop through the
* dev_base_head list, and hold dev_base_lock for writing when they do the
* actual updates. This allows pure readers to access the list even
* while a writer is preparing to update it.
*
* To put it another way, dev_base_lock is held for writing only to
* protect against pure readers; the rtnl semaphore provides the
* protection against other writers.
*
* See, for example usages, register_netdevice() and
* unregister_netdevice(), which must be called with the rtnl
* semaphore held.
*/
DEFINE_RWLOCK(dev_base_lock);
EXPORT_SYMBOL(dev_base_lock);
static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
{
unsigned hash = full_name_hash(name, strnlen(name, IFNAMSIZ));
return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
}
static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
{
return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
}
static inline void rps_lock(struct softnet_data *sd)
{
#ifdef CONFIG_RPS
spin_lock(&sd->input_pkt_queue.lock);
#endif
}
static inline void rps_unlock(struct softnet_data *sd)
{
#ifdef CONFIG_RPS
spin_unlock(&sd->input_pkt_queue.lock);
#endif
}
/* Device list insertion */
static int list_netdevice(struct net_device *dev)
{
struct net *net = dev_net(dev);
ASSERT_RTNL();
write_lock_bh(&dev_base_lock);
list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
hlist_add_head_rcu(&dev->index_hlist,
dev_index_hash(net, dev->ifindex));
write_unlock_bh(&dev_base_lock);
return 0;
}
/* Device list removal
* caller must respect a RCU grace period before freeing/reusing dev
*/
static void unlist_netdevice(struct net_device *dev)
{
ASSERT_RTNL();
/* Unlink dev from the device chain */
write_lock_bh(&dev_base_lock);
list_del_rcu(&dev->dev_list);
hlist_del_rcu(&dev->name_hlist);
hlist_del_rcu(&dev->index_hlist);
write_unlock_bh(&dev_base_lock);
}
/*
* Our notifier list
*/
static RAW_NOTIFIER_HEAD(netdev_chain);
/*
* Device drivers call our routines to queue packets here. We empty the
* queue in the local softnet handler.
*/
DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
EXPORT_PER_CPU_SYMBOL(softnet_data);
#ifdef CONFIG_LOCKDEP
/*
* register_netdevice() inits txq->_xmit_lock and sets lockdep class
* according to dev->type
*/
static const unsigned short netdev_lock_type[] =
{ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
ARPHRD_FCFABRIC, ARPHRD_IEEE802_TR, ARPHRD_IEEE80211,
ARPHRD_IEEE80211_PRISM, ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET,
ARPHRD_PHONET_PIPE, ARPHRD_IEEE802154,
ARPHRD_VOID, ARPHRD_NONE};
static const char *const netdev_lock_name[] =
{"_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
"_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
"_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
"_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
"_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
"_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
"_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
"_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
"_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
"_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
"_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
"_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
"_xmit_FCFABRIC", "_xmit_IEEE802_TR", "_xmit_IEEE80211",
"_xmit_IEEE80211_PRISM", "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET",
"_xmit_PHONET_PIPE", "_xmit_IEEE802154",
"_xmit_VOID", "_xmit_NONE"};
static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
static inline unsigned short netdev_lock_pos(unsigned short dev_type)
{
int i;
for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
if (netdev_lock_type[i] == dev_type)
return i;
/* the last key is used by default */
return ARRAY_SIZE(netdev_lock_type) - 1;
}
static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
unsigned short dev_type)
{
int i;
i = netdev_lock_pos(dev_type);
lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
netdev_lock_name[i]);
}
static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
{
int i;
i = netdev_lock_pos(dev->type);
lockdep_set_class_and_name(&dev->addr_list_lock,
&netdev_addr_lock_key[i],
netdev_lock_name[i]);
}
#else
static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
unsigned short dev_type)
{
}
static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
{
}
#endif
/*******************************************************************************
Protocol management and registration routines
*******************************************************************************/
/*
* Add a protocol ID to the list. Now that the input handler is
* smarter we can dispense with all the messy stuff that used to be
* here.
*
* BEWARE!!! Protocol handlers, mangling input packets,
* MUST BE last in hash buckets and checking protocol handlers
* MUST start from promiscuous ptype_all chain in net_bh.
* It is true now, do not change it.
* Explanation follows: if protocol handler, mangling packet, will
* be the first on list, it is not able to sense, that packet
* is cloned and should be copied-on-write, so that it will
* change it and subsequent readers will get broken packet.
* --ANK (980803)
*/
/**
* dev_add_pack - add packet handler
* @pt: packet type declaration
*
* Add a protocol handler to the networking stack. The passed &packet_type
* is linked into kernel lists and may not be freed until it has been
* removed from the kernel lists.
*
* This call does not sleep therefore it can not
* guarantee all CPU's that are in middle of receiving packets
* will see the new packet type (until the next received packet).
*/
void dev_add_pack(struct packet_type *pt)
{
int hash;
spin_lock_bh(&ptype_lock);
if (pt->type == htons(ETH_P_ALL))
list_add_rcu(&pt->list, &ptype_all);
else {
hash = ntohs(pt->type) & PTYPE_HASH_MASK;
list_add_rcu(&pt->list, &ptype_base[hash]);
}
spin_unlock_bh(&ptype_lock);
}
EXPORT_SYMBOL(dev_add_pack);
/**
* __dev_remove_pack - remove packet handler
* @pt: packet type declaration
*
* Remove a protocol handler that was previously added to the kernel
* protocol handlers by dev_add_pack(). The passed &packet_type is removed
* from the kernel lists and can be freed or reused once this function
* returns.
*
* The packet type might still be in use by receivers
* and must not be freed until after all the CPU's have gone
* through a quiescent state.
*/
void __dev_remove_pack(struct packet_type *pt)
{
struct list_head *head;
struct packet_type *pt1;
spin_lock_bh(&ptype_lock);
if (pt->type == htons(ETH_P_ALL))
head = &ptype_all;
else
head = &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
list_for_each_entry(pt1, head, list) {
if (pt == pt1) {
list_del_rcu(&pt->list);
goto out;
}
}
printk(KERN_WARNING "dev_remove_pack: %p not found.\n", pt);
out:
spin_unlock_bh(&ptype_lock);
}
EXPORT_SYMBOL(__dev_remove_pack);
/**
* dev_remove_pack - remove packet handler
* @pt: packet type declaration
*
* Remove a protocol handler that was previously added to the kernel
* protocol handlers by dev_add_pack(). The passed &packet_type is removed
* from the kernel lists and can be freed or reused once this function
* returns.
*
* This call sleeps to guarantee that no CPU is looking at the packet
* type after return.
*/
void dev_remove_pack(struct packet_type *pt)
{
__dev_remove_pack(pt);
synchronize_net();
}
EXPORT_SYMBOL(dev_remove_pack);
/******************************************************************************
Device Boot-time Settings Routines
*******************************************************************************/
/* Boot time configuration table */
static struct netdev_boot_setup dev_boot_setup[NETDEV_BOOT_SETUP_MAX];
/**
* netdev_boot_setup_add - add new setup entry
* @name: name of the device
* @map: configured settings for the device
*
* Adds new setup entry to the dev_boot_setup list. The function
* returns 0 on error and 1 on success. This is a generic routine to
* all netdevices.
*/
static int netdev_boot_setup_add(char *name, struct ifmap *map)
{
struct netdev_boot_setup *s;
int i;
s = dev_boot_setup;
for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
memset(s[i].name, 0, sizeof(s[i].name));
strlcpy(s[i].name, name, IFNAMSIZ);
memcpy(&s[i].map, map, sizeof(s[i].map));
break;
}
}
return i >= NETDEV_BOOT_SETUP_MAX ? 0 : 1;
}
/**
* netdev_boot_setup_check - check boot time settings
* @dev: the netdevice
*
* Check boot time settings for the device.
* The found settings are set for the device to be used
* later in the device probing.
* Returns 0 if no settings found, 1 if they are.
*/
int netdev_boot_setup_check(struct net_device *dev)
{
struct netdev_boot_setup *s = dev_boot_setup;
int i;
for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
!strcmp(dev->name, s[i].name)) {
dev->irq = s[i].map.irq;
dev->base_addr = s[i].map.base_addr;
dev->mem_start = s[i].map.mem_start;
dev->mem_end = s[i].map.mem_end;
return 1;
}
}
return 0;
}
EXPORT_SYMBOL(netdev_boot_setup_check);
/**
* netdev_boot_base - get address from boot time settings
* @prefix: prefix for network device
* @unit: id for network device
*
* Check boot time settings for the base address of device.
* The found settings are set for the device to be used
* later in the device probing.
* Returns 0 if no settings found.
*/
unsigned long netdev_boot_base(const char *prefix, int unit)
{
const struct netdev_boot_setup *s = dev_boot_setup;
char name[IFNAMSIZ];
int i;
sprintf(name, "%s%d", prefix, unit);
/*
* If device already registered then return base of 1
* to indicate not to probe for this interface
*/
if (__dev_get_by_name(&init_net, name))
return 1;
for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++)
if (!strcmp(name, s[i].name))
return s[i].map.base_addr;
return 0;
}
/*
* Saves at boot time configured settings for any netdevice.
*/
int __init netdev_boot_setup(char *str)
{
int ints[5];
struct ifmap map;
str = get_options(str, ARRAY_SIZE(ints), ints);
if (!str || !*str)
return 0;
/* Save settings */
memset(&map, 0, sizeof(map));
if (ints[0] > 0)
map.irq = ints[1];
if (ints[0] > 1)
map.base_addr = ints[2];
if (ints[0] > 2)
map.mem_start = ints[3];
if (ints[0] > 3)
map.mem_end = ints[4];
/* Add new entry to the list */
return netdev_boot_setup_add(str, &map);
}
__setup("netdev=", netdev_boot_setup);
/*******************************************************************************
Device Interface Subroutines
*******************************************************************************/
/**
* __dev_get_by_name - find a device by its name
* @net: the applicable net namespace
* @name: name to find
*
* Find an interface by name. Must be called under RTNL semaphore
* or @dev_base_lock. If the name is found a pointer to the device
* is returned. If the name is not found then %NULL is returned. The
* reference counters are not incremented so the caller must be
* careful with locks.
*/
struct net_device *__dev_get_by_name(struct net *net, const char *name)
{
struct hlist_node *p;
struct net_device *dev;
struct hlist_head *head = dev_name_hash(net, name);
hlist_for_each_entry(dev, p, head, name_hlist)
if (!strncmp(dev->name, name, IFNAMSIZ))
return dev;
return NULL;
}
EXPORT_SYMBOL(__dev_get_by_name);
/**
* dev_get_by_name_rcu - find a device by its name
* @net: the applicable net namespace
* @name: name to find
*
* Find an interface by name.
* If the name is found a pointer to the device is returned.
* If the name is not found then %NULL is returned.
* The reference counters are not incremented so the caller must be
* careful with locks. The caller must hold RCU lock.
*/
struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
{
struct hlist_node *p;
struct net_device *dev;
struct hlist_head *head = dev_name_hash(net, name);
hlist_for_each_entry_rcu(dev, p, head, name_hlist)
if (!strncmp(dev->name, name, IFNAMSIZ))
return dev;
return NULL;
}
EXPORT_SYMBOL(dev_get_by_name_rcu);
/**
* dev_get_by_name - find a device by its name
* @net: the applicable net namespace
* @name: name to find
*
* Find an interface by name. This can be called from any
* context and does its own locking. The returned handle has
* the usage count incremented and the caller must use dev_put() to
* release it when it is no longer needed. %NULL is returned if no
* matching device is found.
*/
struct net_device *dev_get_by_name(struct net *net, const char *name)
{
struct net_device *dev;
rcu_read_lock();
dev = dev_get_by_name_rcu(net, name);
if (dev)
dev_hold(dev);
rcu_read_unlock();
return dev;
}
EXPORT_SYMBOL(dev_get_by_name);
/**
* __dev_get_by_index - find a device by its ifindex
* @net: the applicable net namespace
* @ifindex: index of device
*
* Search for an interface by index. Returns %NULL if the device
* is not found or a pointer to the device. The device has not
* had its reference counter increased so the caller must be careful
* about locking. The caller must hold either the RTNL semaphore
* or @dev_base_lock.
*/
struct net_device *__dev_get_by_index(struct net *net, int ifindex)
{
struct hlist_node *p;
struct net_device *dev;
struct hlist_head *head = dev_index_hash(net, ifindex);
hlist_for_each_entry(dev, p, head, index_hlist)
if (dev->ifindex == ifindex)
return dev;
return NULL;
}
EXPORT_SYMBOL(__dev_get_by_index);
/**
* dev_get_by_index_rcu - find a device by its ifindex
* @net: the applicable net namespace
* @ifindex: index of device
*
* Search for an interface by index. Returns %NULL if the device
* is not found or a pointer to the device. The device has not
* had its reference counter increased so the caller must be careful
* about locking. The caller must hold RCU lock.
*/
struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
{
struct hlist_node *p;
struct net_device *dev;
struct hlist_head *head = dev_index_hash(net, ifindex);
hlist_for_each_entry_rcu(dev, p, head, index_hlist)
if (dev->ifindex == ifindex)
return dev;
return NULL;
}
EXPORT_SYMBOL(dev_get_by_index_rcu);
/**
* dev_get_by_index - find a device by its ifindex
* @net: the applicable net namespace
* @ifindex: index of device
*
* Search for an interface by index. Returns NULL if the device
* is not found or a pointer to the device. The device returned has
* had a reference added and the pointer is safe until the user calls
* dev_put to indicate they have finished with it.
*/
struct net_device *dev_get_by_index(struct net *net, int ifindex)
{
struct net_device *dev;
rcu_read_lock();
dev = dev_get_by_index_rcu(net, ifindex);
if (dev)
dev_hold(dev);
rcu_read_unlock();
return dev;
}
EXPORT_SYMBOL(dev_get_by_index);
/**
* dev_getbyhwaddr - find a device by its hardware address
* @net: the applicable net namespace
* @type: media type of device
* @ha: hardware address
*
* Search for an interface by MAC address. Returns NULL if the device
* is not found or a pointer to the device. The caller must hold the
* rtnl semaphore. The returned device has not had its ref count increased
* and the caller must therefore be careful about locking
*
* BUGS:
* If the API was consistent this would be __dev_get_by_hwaddr
*/
struct net_device *dev_getbyhwaddr(struct net *net, unsigned short type, char *ha)
{
struct net_device *dev;
ASSERT_RTNL();
for_each_netdev(net, dev)
if (dev->type == type &&
!memcmp(dev->dev_addr, ha, dev->addr_len))
return dev;
return NULL;
}
EXPORT_SYMBOL(dev_getbyhwaddr);
struct net_device *__dev_getfirstbyhwtype(struct net *net, unsigned short type)
{
struct net_device *dev;
ASSERT_RTNL();
for_each_netdev(net, dev)
if (dev->type == type)
return dev;
return NULL;
}
EXPORT_SYMBOL(__dev_getfirstbyhwtype);
struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
{
struct net_device *dev, *ret = NULL;
rcu_read_lock();
for_each_netdev_rcu(net, dev)
if (dev->type == type) {
dev_hold(dev);
ret = dev;
break;
}
rcu_read_unlock();
return ret;
}
EXPORT_SYMBOL(dev_getfirstbyhwtype);
/**
* dev_get_by_flags_rcu - find any device with given flags
* @net: the applicable net namespace
* @if_flags: IFF_* values
* @mask: bitmask of bits in if_flags to check
*
* Search for any interface with the given flags. Returns NULL if a device
* is not found or a pointer to the device. Must be called inside
* rcu_read_lock(), and result refcount is unchanged.
*/
struct net_device *dev_get_by_flags_rcu(struct net *net, unsigned short if_flags,
unsigned short mask)
{
struct net_device *dev, *ret;
ret = NULL;
for_each_netdev_rcu(net, dev) {
if (((dev->flags ^ if_flags) & mask) == 0) {
ret = dev;
break;
}
}
return ret;
}
EXPORT_SYMBOL(dev_get_by_flags_rcu);
/**
* dev_valid_name - check if name is okay for network device
* @name: name string
*
* Network device names need to be valid file names to
* to allow sysfs to work. We also disallow any kind of
* whitespace.
*/
int dev_valid_name(const char *name)
{
if (*name == '\0')
return 0;
if (strlen(name) >= IFNAMSIZ)
return 0;
if (!strcmp(name, ".") || !strcmp(name, ".."))
return 0;
while (*name) {
if (*name == '/' || isspace(*name))
return 0;
name++;
}
return 1;
}
EXPORT_SYMBOL(dev_valid_name);
/**
* __dev_alloc_name - allocate a name for a device
* @net: network namespace to allocate the device name in
* @name: name format string
* @buf: scratch buffer and result name string
*
* Passed a format string - eg "lt%d" it will try and find a suitable
* id. It scans list of devices to build up a free map, then chooses
* the first empty slot. The caller must hold the dev_base or rtnl lock
* while allocating the name and adding the device in order to avoid
* duplicates.
* Limited to bits_per_byte * page size devices (ie 32K on most platforms).
* Returns the number of the unit assigned or a negative errno code.
*/
static int __dev_alloc_name(struct net *net, const char *name, char *buf)
{
int i = 0;
const char *p;
const int max_netdevices = 8*PAGE_SIZE;
unsigned long *inuse;
struct net_device *d;
p = strnchr(name, IFNAMSIZ-1, '%');
if (p) {
/*
* Verify the string as this thing may have come from
* the user. There must be either one "%d" and no other "%"
* characters.
*/
if (p[1] != 'd' || strchr(p + 2, '%'))
return -EINVAL;
/* Use one page as a bit array of possible slots */
inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
if (!inuse)
return -ENOMEM;
for_each_netdev(net, d) {
if (!sscanf(d->name, name, &i))
continue;
if (i < 0 || i >= max_netdevices)
continue;
/* avoid cases where sscanf is not exact inverse of printf */
snprintf(buf, IFNAMSIZ, name, i);
if (!strncmp(buf, d->name, IFNAMSIZ))
set_bit(i, inuse);
}
i = find_first_zero_bit(inuse, max_netdevices);
free_page((unsigned long) inuse);
}
if (buf != name)
snprintf(buf, IFNAMSIZ, name, i);
if (!__dev_get_by_name(net, buf))
return i;
/* It is possible to run out of possible slots
* when the name is long and there isn't enough space left
* for the digits, or if all bits are used.
*/
return -ENFILE;
}
/**
* dev_alloc_name - allocate a name for a device
* @dev: device
* @name: name format string
*
* Passed a format string - eg "lt%d" it will try and find a suitable
* id. It scans list of devices to build up a free map, then chooses
* the first empty slot. The caller must hold the dev_base or rtnl lock
* while allocating the name and adding the device in order to avoid
* duplicates.
* Limited to bits_per_byte * page size devices (ie 32K on most platforms).
* Returns the number of the unit assigned or a negative errno code.
*/
int dev_alloc_name(struct net_device *dev, const char *name)
{
char buf[IFNAMSIZ];
struct net *net;
int ret;
BUG_ON(!dev_net(dev));
net = dev_net(dev);
ret = __dev_alloc_name(net, name, buf);
if (ret >= 0)
strlcpy(dev->name, buf, IFNAMSIZ);
return ret;
}
EXPORT_SYMBOL(dev_alloc_name);
static int dev_get_valid_name(struct net_device *dev, const char *name, bool fmt)
{
struct net *net;
BUG_ON(!dev_net(dev));
net = dev_net(dev);
if (!dev_valid_name(name))
return -EINVAL;
if (fmt && strchr(name, '%'))
return dev_alloc_name(dev, name);
else if (__dev_get_by_name(net, name))
return -EEXIST;
else if (dev->name != name)
strlcpy(dev->name, name, IFNAMSIZ);
return 0;
}
/**
* dev_change_name - change name of a device
* @dev: device
* @newname: name (or format string) must be at least IFNAMSIZ
*
* Change name of a device, can pass format strings "eth%d".
* for wildcarding.
*/
int dev_change_name(struct net_device *dev, const char *newname)
{
char oldname[IFNAMSIZ];
int err = 0;
int ret;
struct net *net;
ASSERT_RTNL();
BUG_ON(!dev_net(dev));
net = dev_net(dev);
if (dev->flags & IFF_UP)
return -EBUSY;
if (strncmp(newname, dev->name, IFNAMSIZ) == 0)
return 0;
memcpy(oldname, dev->name, IFNAMSIZ);
err = dev_get_valid_name(dev, newname, 1);
if (err < 0)
return err;
rollback:
ret = device_rename(&dev->dev, dev->name);
if (ret) {
memcpy(dev->name, oldname, IFNAMSIZ);
return ret;
}
write_lock_bh(&dev_base_lock);
hlist_del(&dev->name_hlist);
write_unlock_bh(&dev_base_lock);
synchronize_rcu();
write_lock_bh(&dev_base_lock);
hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
write_unlock_bh(&dev_base_lock);
ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
ret = notifier_to_errno(ret);
if (ret) {
/* err >= 0 after dev_alloc_name() or stores the first errno */
if (err >= 0) {
err = ret;
memcpy(dev->name, oldname, IFNAMSIZ);
goto rollback;
} else {
printk(KERN_ERR
"%s: name change rollback failed: %d.\n",
dev->name, ret);
}
}
return err;
}
/**
* dev_set_alias - change ifalias of a device
* @dev: device
* @alias: name up to IFALIASZ
* @len: limit of bytes to copy from info
*
* Set ifalias for a device,
*/
int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
{
ASSERT_RTNL();
if (len >= IFALIASZ)
return -EINVAL;
if (!len) {
if (dev->ifalias) {
kfree(dev->ifalias);
dev->ifalias = NULL;
}
return 0;
}
dev->ifalias = krealloc(dev->ifalias, len + 1, GFP_KERNEL);
if (!dev->ifalias)
return -ENOMEM;
strlcpy(dev->ifalias, alias, len+1);
return len;
}
/**
* netdev_features_change - device changes features
* @dev: device to cause notification
*
* Called to indicate a device has changed features.
*/
void netdev_features_change(struct net_device *dev)
{
call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
}
EXPORT_SYMBOL(netdev_features_change);
/**
* netdev_state_change - device changes state
* @dev: device to cause notification
*
* Called to indicate a device has changed state. This function calls
* the notifier chains for netdev_chain and sends a NEWLINK message
* to the routing socket.
*/
void netdev_state_change(struct net_device *dev)
{
if (dev->flags & IFF_UP) {
call_netdevice_notifiers(NETDEV_CHANGE, dev);
rtmsg_ifinfo(RTM_NEWLINK, dev, 0);
}
}
EXPORT_SYMBOL(netdev_state_change);
int netdev_bonding_change(struct net_device *dev, unsigned long event)
{
return call_netdevice_notifiers(event, dev);
}
EXPORT_SYMBOL(netdev_bonding_change);
/**
* dev_load - load a network module
* @net: the applicable net namespace
* @name: name of interface
*
* If a network interface is not present and the process has suitable
* privileges this function loads the module. If module loading is not
* available in this kernel then it becomes a nop.
*/
void dev_load(struct net *net, const char *name)
{
struct net_device *dev;
rcu_read_lock();
dev = dev_get_by_name_rcu(net, name);
rcu_read_unlock();
if (!dev && capable(CAP_NET_ADMIN))
request_module("%s", name);
}
EXPORT_SYMBOL(dev_load);
static int __dev_open(struct net_device *dev)
{
const struct net_device_ops *ops = dev->netdev_ops;
int ret;
ASSERT_RTNL();
/*
* Is it even present?
*/
if (!netif_device_present(dev))
return -ENODEV;
ret = call_netdevice_notifiers(NETDEV_PRE_UP, dev);
ret = notifier_to_errno(ret);
if (ret)
return ret;
/*
* Call device private open method
*/
set_bit(__LINK_STATE_START, &dev->state);
if (ops->ndo_validate_addr)
ret = ops->ndo_validate_addr(dev);
if (!ret && ops->ndo_open)
ret = ops->ndo_open(dev);
/*
* If it went open OK then:
*/
if (ret)
clear_bit(__LINK_STATE_START, &dev->state);
else {
/*
* Set the flags.
*/
dev->flags |= IFF_UP;
/*
* Enable NET_DMA
*/
net_dmaengine_get();
/*
* Initialize multicasting status
*/
dev_set_rx_mode(dev);
/*
* Wakeup transmit queue engine
*/
dev_activate(dev);
}
return ret;
}
/**
* dev_open - prepare an interface for use.
* @dev: device to open
*
* Takes a device from down to up state. The device's private open
* function is invoked and then the multicast lists are loaded. Finally
* the device is moved into the up state and a %NETDEV_UP message is
* sent to the netdev notifier chain.
*
* Calling this function on an active interface is a nop. On a failure
* a negative errno code is returned.
*/
int dev_open(struct net_device *dev)
{
int ret;
/*
* Is it already up?
*/
if (dev->flags & IFF_UP)
return 0;
/*
* Open device
*/
ret = __dev_open(dev);
if (ret < 0)
return ret;
/*
* ... and announce new interface.
*/
rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING);
call_netdevice_notifiers(NETDEV_UP, dev);
return ret;
}
EXPORT_SYMBOL(dev_open);
static int __dev_close(struct net_device *dev)
{
const struct net_device_ops *ops = dev->netdev_ops;
ASSERT_RTNL();
might_sleep();
/*
* Tell people we are going down, so that they can
* prepare to death, when device is still operating.
*/
call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
clear_bit(__LINK_STATE_START, &dev->state);
/* Synchronize to scheduled poll. We cannot touch poll list,
* it can be even on different cpu. So just clear netif_running().
*
* dev->stop() will invoke napi_disable() on all of it's
* napi_struct instances on this device.
*/
smp_mb__after_clear_bit(); /* Commit netif_running(). */
dev_deactivate(dev);
/*
* Call the device specific close. This cannot fail.
* Only if device is UP
*
* We allow it to be called even after a DETACH hot-plug
* event.
*/
if (ops->ndo_stop)
ops->ndo_stop(dev);
/*
* Device is now down.
*/
dev->flags &= ~IFF_UP;
/*
* Shutdown NET_DMA
*/
net_dmaengine_put();
return 0;
}
/**
* dev_close - shutdown an interface.
* @dev: device to shutdown
*
* This function moves an active device into down state. A
* %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
* is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
* chain.
*/
int dev_close(struct net_device *dev)
{
if (!(dev->flags & IFF_UP))
return 0;
__dev_close(dev);
/*
* Tell people we are down
*/
rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING);
call_netdevice_notifiers(NETDEV_DOWN, dev);
return 0;
}
EXPORT_SYMBOL(dev_close);
/**
* dev_disable_lro - disable Large Receive Offload on a device
* @dev: device
*
* Disable Large Receive Offload (LRO) on a net device. Must be
* called under RTNL. This is needed if received packets may be
* forwarded to another interface.
*/
void dev_disable_lro(struct net_device *dev)
{
if (dev->ethtool_ops && dev->ethtool_ops->get_flags &&
dev->ethtool_ops->set_flags) {
u32 flags = dev->ethtool_ops->get_flags(dev);
if (flags & ETH_FLAG_LRO) {
flags &= ~ETH_FLAG_LRO;
dev->ethtool_ops->set_flags(dev, flags);
}
}
WARN_ON(dev->features & NETIF_F_LRO);
}
EXPORT_SYMBOL(dev_disable_lro);
static int dev_boot_phase = 1;
/*
* Device change register/unregister. These are not inline or static
* as we export them to the world.
*/
/**
* register_netdevice_notifier - register a network notifier block
* @nb: notifier
*
* Register a notifier to be called when network device events occur.
* The notifier passed is linked into the kernel structures and must
* not be reused until it has been unregistered. A negative errno code
* is returned on a failure.
*
* When registered all registration and up events are replayed
* to the new notifier to allow device to have a race free
* view of the network device list.
*/
int register_netdevice_notifier(struct notifier_block *nb)
{
struct net_device *dev;
struct net_device *last;
struct net *net;
int err;
rtnl_lock();
err = raw_notifier_chain_register(&netdev_chain, nb);
if (err)
goto unlock;
if (dev_boot_phase)
goto unlock;
for_each_net(net) {
for_each_netdev(net, dev) {
err = nb->notifier_call(nb, NETDEV_REGISTER, dev);
err = notifier_to_errno(err);
if (err)
goto rollback;
if (!(dev->flags & IFF_UP))
continue;
nb->notifier_call(nb, NETDEV_UP, dev);
}
}
unlock:
rtnl_unlock();
return err;
rollback:
last = dev;
for_each_net(net) {
for_each_netdev(net, dev) {
if (dev == last)
break;
if (dev->flags & IFF_UP) {
nb->notifier_call(nb, NETDEV_GOING_DOWN, dev);
nb->notifier_call(nb, NETDEV_DOWN, dev);
}
nb->notifier_call(nb, NETDEV_UNREGISTER, dev);
nb->notifier_call(nb, NETDEV_UNREGISTER_BATCH, dev);
}
}
raw_notifier_chain_unregister(&netdev_chain, nb);
goto unlock;
}
EXPORT_SYMBOL(register_netdevice_notifier);
/**
* unregister_netdevice_notifier - unregister a network notifier block
* @nb: notifier
*
* Unregister a notifier previously registered by
* register_netdevice_notifier(). The notifier is unlinked into the
* kernel structures and may then be reused. A negative errno code
* is returned on a failure.
*/
int unregister_netdevice_notifier(struct notifier_block *nb)
{
int err;
rtnl_lock();
err = raw_notifier_chain_unregister(&netdev_chain, nb);
rtnl_unlock();
return err;
}
EXPORT_SYMBOL(unregister_netdevice_notifier);
/**
* call_netdevice_notifiers - call all network notifier blocks
* @val: value passed unmodified to notifier function
* @dev: net_device pointer passed unmodified to notifier function
*
* Call all network notifier blocks. Parameters and return value
* are as for raw_notifier_call_chain().
*/
int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
{
ASSERT_RTNL();
return raw_notifier_call_chain(&netdev_chain, val, dev);
}
/* When > 0 there are consumers of rx skb time stamps */
static atomic_t netstamp_needed = ATOMIC_INIT(0);
void net_enable_timestamp(void)
{
atomic_inc(&netstamp_needed);
}
EXPORT_SYMBOL(net_enable_timestamp);
void net_disable_timestamp(void)
{
atomic_dec(&netstamp_needed);
}
EXPORT_SYMBOL(net_disable_timestamp);
static inline void net_timestamp_set(struct sk_buff *skb)
{
if (atomic_read(&netstamp_needed))
__net_timestamp(skb);
else
skb->tstamp.tv64 = 0;
}
static inline void net_timestamp_check(struct sk_buff *skb)
{
if (!skb->tstamp.tv64 && atomic_read(&netstamp_needed))
__net_timestamp(skb);
}
/**
* dev_forward_skb - loopback an skb to another netif
*
* @dev: destination network device
* @skb: buffer to forward
*
* return values:
* NET_RX_SUCCESS (no congestion)
* NET_RX_DROP (packet was dropped, but freed)
*
* dev_forward_skb can be used for injecting an skb from the
* start_xmit function of one device into the receive queue
* of another device.
*
* The receiving device may be in another namespace, so
* we have to clear all information in the skb that could
* impact namespace isolation.
*/
int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
{
skb_orphan(skb);
if (!(dev->flags & IFF_UP) ||
(skb->len > (dev->mtu + dev->hard_header_len))) {
kfree_skb(skb);
return NET_RX_DROP;
}
skb_set_dev(skb, dev);
skb->tstamp.tv64 = 0;
skb->pkt_type = PACKET_HOST;
skb->protocol = eth_type_trans(skb, dev);
return netif_rx(skb);
}
EXPORT_SYMBOL_GPL(dev_forward_skb);
/*
* Support routine. Sends outgoing frames to any network
* taps currently in use.
*/
static void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
{
struct packet_type *ptype;
#ifdef CONFIG_NET_CLS_ACT
if (!(skb->tstamp.tv64 && (G_TC_FROM(skb->tc_verd) & AT_INGRESS)))
net_timestamp_set(skb);
#else
net_timestamp_set(skb);
#endif
rcu_read_lock();
list_for_each_entry_rcu(ptype, &ptype_all, list) {
/* Never send packets back to the socket
* they originated from - MvS (miquels@drinkel.ow.org)
*/
if ((ptype->dev == dev || !ptype->dev) &&
(ptype->af_packet_priv == NULL ||
(struct sock *)ptype->af_packet_priv != skb->sk)) {
struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
if (!skb2)
break;
/* skb->nh should be correctly
set by sender, so that the second statement is
just protection against buggy protocols.
*/
skb_reset_mac_header(skb2);
if (skb_network_header(skb2) < skb2->data ||
skb2->network_header > skb2->tail) {
if (net_ratelimit())
printk(KERN_CRIT "protocol %04x is "
"buggy, dev %s\n",
ntohs(skb2->protocol),
dev->name);
skb_reset_network_header(skb2);
}
skb2->transport_header = skb2->network_header;
skb2->pkt_type = PACKET_OUTGOING;
ptype->func(skb2, skb->dev, ptype, skb->dev);
}
}
rcu_read_unlock();
}
static inline void __netif_reschedule(struct Qdisc *q)
{
struct softnet_data *sd;
unsigned long flags;
local_irq_save(flags);
sd = &__get_cpu_var(softnet_data);
q->next_sched = NULL;
*sd->output_queue_tailp = q;
sd->output_queue_tailp = &q->next_sched;
raise_softirq_irqoff(NET_TX_SOFTIRQ);
local_irq_restore(flags);
}
void __netif_schedule(struct Qdisc *q)
{
if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
__netif_reschedule(q);
}
EXPORT_SYMBOL(__netif_schedule);
void dev_kfree_skb_irq(struct sk_buff *skb)
{
if (!skb->destructor)
dev_kfree_skb(skb);
else if (atomic_dec_and_test(&skb->users)) {
struct softnet_data *sd;
unsigned long flags;
local_irq_save(flags);
sd = &__get_cpu_var(softnet_data);
skb->next = sd->completion_queue;
sd->completion_queue = skb;
raise_softirq_irqoff(NET_TX_SOFTIRQ);
local_irq_restore(flags);
}
}
EXPORT_SYMBOL(dev_kfree_skb_irq);
void dev_kfree_skb_any(struct sk_buff *skb)
{
if (in_irq() || irqs_disabled())
dev_kfree_skb_irq(skb);
else
dev_kfree_skb(skb);
}
EXPORT_SYMBOL(dev_kfree_skb_any);
/**
* netif_device_detach - mark device as removed
* @dev: network device
*
* Mark device as removed from system and therefore no longer available.
*/
void netif_device_detach(struct net_device *dev)
{
if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
netif_running(dev)) {
netif_tx_stop_all_queues(dev);
}
}
EXPORT_SYMBOL(netif_device_detach);
/**
* netif_device_attach - mark device as attached
* @dev: network device
*
* Mark device as attached from system and restart if needed.
*/
void netif_device_attach(struct net_device *dev)
{
if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
netif_running(dev)) {
netif_tx_wake_all_queues(dev);
__netdev_watchdog_up(dev);
}
}
EXPORT_SYMBOL(netif_device_attach);
static bool can_checksum_protocol(unsigned long features, __be16 protocol)
{
return ((features & NETIF_F_GEN_CSUM) ||
((features & NETIF_F_IP_CSUM) &&
protocol == htons(ETH_P_IP)) ||
((features & NETIF_F_IPV6_CSUM) &&
protocol == htons(ETH_P_IPV6)) ||
((features & NETIF_F_FCOE_CRC) &&
protocol == htons(ETH_P_FCOE)));
}
static bool dev_can_checksum(struct net_device *dev, struct sk_buff *skb)
{
if (can_checksum_protocol(dev->features, skb->protocol))
return true;
if (skb->protocol == htons(ETH_P_8021Q)) {
struct vlan_ethhdr *veh = (struct vlan_ethhdr *)skb->data;
if (can_checksum_protocol(dev->features & dev->vlan_features,
veh->h_vlan_encapsulated_proto))
return true;
}
return false;
}
/**
* skb_dev_set -- assign a new device to a buffer
* @skb: buffer for the new device
* @dev: network device
*
* If an skb is owned by a device already, we have to reset
* all data private to the namespace a device belongs to
* before assigning it a new device.
*/
#ifdef CONFIG_NET_NS
void skb_set_dev(struct sk_buff *skb, struct net_device *dev)
{
skb_dst_drop(skb);
if (skb->dev && !net_eq(dev_net(skb->dev), dev_net(dev))) {
secpath_reset(skb);
nf_reset(skb);
skb_init_secmark(skb);
skb->mark = 0;
skb->priority = 0;
skb->nf_trace = 0;
skb->ipvs_property = 0;
#ifdef CONFIG_NET_SCHED
skb->tc_index = 0;
#endif
}
skb->dev = dev;
}
EXPORT_SYMBOL(skb_set_dev);
#endif /* CONFIG_NET_NS */
/*
* Invalidate hardware checksum when packet is to be mangled, and
* complete checksum manually on outgoing path.
*/
int skb_checksum_help(struct sk_buff *skb)
{
__wsum csum;
int ret = 0, offset;
if (skb->ip_summed == CHECKSUM_COMPLETE)
goto out_set_summed;
if (unlikely(skb_shinfo(skb)->gso_size)) {
/* Let GSO fix up the checksum. */
goto out_set_summed;
}
offset = skb->csum_start - skb_headroom(skb);
BUG_ON(offset >= skb_headlen(skb));
csum = skb_checksum(skb, offset, skb->len - offset, 0);
offset += skb->csum_offset;
BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
if (skb_cloned(skb) &&
!skb_clone_writable(skb, offset + sizeof(__sum16))) {
ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
if (ret)
goto out;
}
*(__sum16 *)(skb->data + offset) = csum_fold(csum);
out_set_summed:
skb->ip_summed = CHECKSUM_NONE;
out:
return ret;
}
EXPORT_SYMBOL(skb_checksum_help);
/**
* skb_gso_segment - Perform segmentation on skb.
* @skb: buffer to segment
* @features: features for the output path (see dev->features)
*
* This function segments the given skb and returns a list of segments.
*
* It may return NULL if the skb requires no segmentation. This is
* only possible when GSO is used for verifying header integrity.
*/
struct sk_buff *skb_gso_segment(struct sk_buff *skb, int features)
{
struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
struct packet_type *ptype;
__be16 type = skb->protocol;
int err;
skb_reset_mac_header(skb);
skb->mac_len = skb->network_header - skb->mac_header;
__skb_pull(skb, skb->mac_len);
if (unlikely(skb->ip_summed != CHECKSUM_PARTIAL)) {
struct net_device *dev = skb->dev;
struct ethtool_drvinfo info = {};
if (dev && dev->ethtool_ops && dev->ethtool_ops->get_drvinfo)
dev->ethtool_ops->get_drvinfo(dev, &info);
WARN(1, "%s: caps=(0x%lx, 0x%lx) len=%d data_len=%d "
"ip_summed=%d",
info.driver, dev ? dev->features : 0L,
skb->sk ? skb->sk->sk_route_caps : 0L,
skb->len, skb->data_len, skb->ip_summed);
if (skb_header_cloned(skb) &&
(err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC)))
return ERR_PTR(err);
}
rcu_read_lock();
list_for_each_entry_rcu(ptype,
&ptype_base[ntohs(type) & PTYPE_HASH_MASK], list) {
if (ptype->type == type && !ptype->dev && ptype->gso_segment) {
if (unlikely(skb->ip_summed != CHECKSUM_PARTIAL)) {
err = ptype->gso_send_check(skb);
segs = ERR_PTR(err);
if (err || skb_gso_ok(skb, features))
break;
__skb_push(skb, (skb->data -
skb_network_header(skb)));
}
segs = ptype->gso_segment(skb, features);
break;
}
}
rcu_read_unlock();
__skb_push(skb, skb->data - skb_mac_header(skb));
return segs;
}
EXPORT_SYMBOL(skb_gso_segment);
/* Take action when hardware reception checksum errors are detected. */
#ifdef CONFIG_BUG
void netdev_rx_csum_fault(struct net_device *dev)
{
if (net_ratelimit()) {
printk(KERN_ERR "%s: hw csum failure.\n",
dev ? dev->name : "<unknown>");
dump_stack();
}
}
EXPORT_SYMBOL(netdev_rx_csum_fault);
#endif
/* Actually, we should eliminate this check as soon as we know, that:
* 1. IOMMU is present and allows to map all the memory.
* 2. No high memory really exists on this machine.
*/
static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
{
#ifdef CONFIG_HIGHMEM
int i;
if (!(dev->features & NETIF_F_HIGHDMA)) {
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
if (PageHighMem(skb_shinfo(skb)->frags[i].page))
return 1;
}
if (PCI_DMA_BUS_IS_PHYS) {
struct device *pdev = dev->dev.parent;
if (!pdev)
return 0;
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
dma_addr_t addr = page_to_phys(skb_shinfo(skb)->frags[i].page);
if (!pdev->dma_mask || addr + PAGE_SIZE - 1 > *pdev->dma_mask)
return 1;
}
}
#endif
return 0;
}
struct dev_gso_cb {
void (*destructor)(struct sk_buff *skb);
};
#define DEV_GSO_CB(skb) ((struct dev_gso_cb *)(skb)->cb)
static void dev_gso_skb_destructor(struct sk_buff *skb)
{
struct dev_gso_cb *cb;
do {
struct sk_buff *nskb = skb->next;
skb->next = nskb->next;
nskb->next = NULL;
kfree_skb(nskb);
} while (skb->next);
cb = DEV_GSO_CB(skb);
if (cb->destructor)
cb->destructor(skb);
}
/**
* dev_gso_segment - Perform emulated hardware segmentation on skb.
* @skb: buffer to segment
*
* This function segments the given skb and stores the list of segments
* in skb->next.
*/
static int dev_gso_segment(struct sk_buff *skb)
{
struct net_device *dev = skb->dev;
struct sk_buff *segs;
int features = dev->features & ~(illegal_highdma(dev, skb) ?
NETIF_F_SG : 0);
segs = skb_gso_segment(skb, features);
/* Verifying header integrity only. */
if (!segs)
return 0;
if (IS_ERR(segs))
return PTR_ERR(segs);
skb->next = segs;
DEV_GSO_CB(skb)->destructor = skb->destructor;
skb->destructor = dev_gso_skb_destructor;
return 0;
}
/*
* Try to orphan skb early, right before transmission by the device.
* We cannot orphan skb if tx timestamp is requested, since
* drivers need to call skb_tstamp_tx() to send the timestamp.
*/
static inline void skb_orphan_try(struct sk_buff *skb)
{
if (!skb_tx(skb)->flags)
skb_orphan(skb);
}
/*
* Returns true if either:
* 1. skb has frag_list and the device doesn't support FRAGLIST, or
* 2. skb is fragmented and the device does not support SG, or if
* at least one of fragments is in highmem and device does not
* support DMA from it.
*/
static inline int skb_needs_linearize(struct sk_buff *skb,
struct net_device *dev)
{
return skb_is_nonlinear(skb) &&
((skb_has_frags(skb) && !(dev->features & NETIF_F_FRAGLIST)) ||
(skb_shinfo(skb)->nr_frags && (!(dev->features & NETIF_F_SG) ||
illegal_highdma(dev, skb))));
}
int dev_hard_start_xmit(struct sk_buff *skb, struct net_device *dev,
struct netdev_queue *txq)
{
const struct net_device_ops *ops = dev->netdev_ops;
int rc = NETDEV_TX_OK;
if (likely(!skb->next)) {
if (!list_empty(&ptype_all))
dev_queue_xmit_nit(skb, dev);
/*
* If device doesnt need skb->dst, release it right now while
* its hot in this cpu cache
*/
if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
skb_dst_drop(skb);
skb_orphan_try(skb);
if (netif_needs_gso(dev, skb)) {
if (unlikely(dev_gso_segment(skb)))
goto out_kfree_skb;
if (skb->next)
goto gso;
} else {
if (skb_needs_linearize(skb, dev) &&
__skb_linearize(skb))
goto out_kfree_skb;
/* If packet is not checksummed and device does not
* support checksumming for this protocol, complete
* checksumming here.
*/
if (skb->ip_summed == CHECKSUM_PARTIAL) {
skb_set_transport_header(skb, skb->csum_start -
skb_headroom(skb));
if (!dev_can_checksum(dev, skb) &&
skb_checksum_help(skb))
goto out_kfree_skb;
}
}
rc = ops->ndo_start_xmit(skb, dev);
if (rc == NETDEV_TX_OK)
txq_trans_update(txq);
return rc;
}
gso:
do {
struct sk_buff *nskb = skb->next;
skb->next = nskb->next;
nskb->next = NULL;
/*
* If device doesnt need nskb->dst, release it right now while
* its hot in this cpu cache
*/
if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
skb_dst_drop(nskb);
rc = ops->ndo_start_xmit(nskb, dev);
if (unlikely(rc != NETDEV_TX_OK)) {
if (rc & ~NETDEV_TX_MASK)
goto out_kfree_gso_skb;
nskb->next = skb->next;
skb->next = nskb;
return rc;
}
txq_trans_update(txq);
if (unlikely(netif_tx_queue_stopped(txq) && skb->next))
return NETDEV_TX_BUSY;
} while (skb->next);
out_kfree_gso_skb:
if (likely(skb->next == NULL))
skb->destructor = DEV_GSO_CB(skb)->destructor;
out_kfree_skb:
kfree_skb(skb);
return rc;
}
static u32 hashrnd __read_mostly;
u16 skb_tx_hash(const struct net_device *dev, const struct sk_buff *skb)
{
u32 hash;
if (skb_rx_queue_recorded(skb)) {
hash = skb_get_rx_queue(skb);
while (unlikely(hash >= dev->real_num_tx_queues))
hash -= dev->real_num_tx_queues;
return hash;
}
if (skb->sk && skb->sk->sk_hash)
hash = skb->sk->sk_hash;
else
hash = (__force u16) skb->protocol;
hash = jhash_1word(hash, hashrnd);
return (u16) (((u64) hash * dev->real_num_tx_queues) >> 32);
}
EXPORT_SYMBOL(skb_tx_hash);
static inline u16 dev_cap_txqueue(struct net_device *dev, u16 queue_index)
{
if (unlikely(queue_index >= dev->real_num_tx_queues)) {
if (net_ratelimit()) {
pr_warning("%s selects TX queue %d, but "
"real number of TX queues is %d\n",
dev->name, queue_index, dev->real_num_tx_queues);
}
return 0;
}
return queue_index;
}
static struct netdev_queue *dev_pick_tx(struct net_device *dev,
struct sk_buff *skb)
{
u16 queue_index;
struct sock *sk = skb->sk;
if (sk_tx_queue_recorded(sk)) {
queue_index = sk_tx_queue_get(sk);
} else {
const struct net_device_ops *ops = dev->netdev_ops;
if (ops->ndo_select_queue) {
queue_index = ops->ndo_select_queue(dev, skb);
queue_index = dev_cap_txqueue(dev, queue_index);
} else {
queue_index = 0;
if (dev->real_num_tx_queues > 1)
queue_index = skb_tx_hash(dev, skb);
if (sk) {
struct dst_entry *dst = rcu_dereference_check(sk->sk_dst_cache, 1);
if (dst && skb_dst(skb) == dst)
sk_tx_queue_set(sk, queue_index);
}
}
}
skb_set_queue_mapping(skb, queue_index);
return netdev_get_tx_queue(dev, queue_index);
}
static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
struct net_device *dev,
struct netdev_queue *txq)
{
spinlock_t *root_lock = qdisc_lock(q);
bool contended = qdisc_is_running(q);
int rc;
/*
* Heuristic to force contended enqueues to serialize on a
* separate lock before trying to get qdisc main lock.
* This permits __QDISC_STATE_RUNNING owner to get the lock more often
* and dequeue packets faster.
*/
if (unlikely(contended))
spin_lock(&q->busylock);
spin_lock(root_lock);
if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
kfree_skb(skb);
rc = NET_XMIT_DROP;
} else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
qdisc_run_begin(q)) {
/*
* This is a work-conserving queue; there are no old skbs
* waiting to be sent out; and the qdisc is not running -
* xmit the skb directly.
*/
if (!(dev->priv_flags & IFF_XMIT_DST_RELEASE))
skb_dst_force(skb);
__qdisc_update_bstats(q, skb->len);
if (sch_direct_xmit(skb, q, dev, txq, root_lock)) {
if (unlikely(contended)) {
spin_unlock(&q->busylock);
contended = false;
}
__qdisc_run(q);
} else
qdisc_run_end(q);
rc = NET_XMIT_SUCCESS;
} else {
skb_dst_force(skb);
rc = qdisc_enqueue_root(skb, q);
if (qdisc_run_begin(q)) {
if (unlikely(contended)) {
spin_unlock(&q->busylock);
contended = false;
}
__qdisc_run(q);
}
}
spin_unlock(root_lock);
if (unlikely(contended))
spin_unlock(&q->busylock);
return rc;
}
/**
* dev_queue_xmit - transmit a buffer
* @skb: buffer to transmit
*
* Queue a buffer for transmission to a network device. The caller must
* have set the device and priority and built the buffer before calling
* this function. The function can be called from an interrupt.
*
* A negative errno code is returned on a failure. A success does not
* guarantee the frame will be transmitted as it may be dropped due
* to congestion or traffic shaping.
*
* -----------------------------------------------------------------------------------
* I notice this method can also return errors from the queue disciplines,
* including NET_XMIT_DROP, which is a positive value. So, errors can also
* be positive.
*
* Regardless of the return value, the skb is consumed, so it is currently
* difficult to retry a send to this method. (You can bump the ref count
* before sending to hold a reference for retry if you are careful.)
*
* When calling this method, interrupts MUST be enabled. This is because
* the BH enable code must have IRQs enabled so that it will not deadlock.
* --BLG
*/
int dev_queue_xmit(struct sk_buff *skb)
{
struct net_device *dev = skb->dev;
struct netdev_queue *txq;
struct Qdisc *q;
int rc = -ENOMEM;
/* Disable soft irqs for various locks below. Also
* stops preemption for RCU.
*/
rcu_read_lock_bh();
txq = dev_pick_tx(dev, skb);
q = rcu_dereference_bh(txq->qdisc);
#ifdef CONFIG_NET_CLS_ACT
skb->tc_verd = SET_TC_AT(skb->tc_verd, AT_EGRESS);
#endif
if (q->enqueue) {
rc = __dev_xmit_skb(skb, q, dev, txq);
goto out;
}
/* The device has no queue. Common case for software devices:
loopback, all the sorts of tunnels...
Really, it is unlikely that netif_tx_lock protection is necessary
here. (f.e. loopback and IP tunnels are clean ignoring statistics
counters.)
However, it is possible, that they rely on protection
made by us here.
Check this and shot the lock. It is not prone from deadlocks.
Either shot noqueue qdisc, it is even simpler 8)
*/
if (dev->flags & IFF_UP) {
int cpu = smp_processor_id(); /* ok because BHs are off */
if (txq->xmit_lock_owner != cpu) {
HARD_TX_LOCK(dev, txq, cpu);
if (!netif_tx_queue_stopped(txq)) {
rc = dev_hard_start_xmit(skb, dev, txq);
if (dev_xmit_complete(rc)) {
HARD_TX_UNLOCK(dev, txq);
goto out;
}
}
HARD_TX_UNLOCK(dev, txq);
if (net_ratelimit())
printk(KERN_CRIT "Virtual device %s asks to "
"queue packet!\n", dev->name);
} else {
/* Recursion is detected! It is possible,
* unfortunately */
if (net_ratelimit())
printk(KERN_CRIT "Dead loop on virtual device "
"%s, fix it urgently!\n", dev->name);
}
}
rc = -ENETDOWN;
rcu_read_unlock_bh();
kfree_skb(skb);
return rc;
out:
rcu_read_unlock_bh();
return rc;
}
EXPORT_SYMBOL(dev_queue_xmit);
/*=======================================================================
Receiver routines
=======================================================================*/
int netdev_max_backlog __read_mostly = 1000;
int netdev_tstamp_prequeue __read_mostly = 1;
int netdev_budget __read_mostly = 300;
int weight_p __read_mostly = 64; /* old backlog weight */
/* Called with irq disabled */
static inline void ____napi_schedule(struct softnet_data *sd,
struct napi_struct *napi)
{
list_add_tail(&napi->poll_list, &sd->poll_list);
__raise_softirq_irqoff(NET_RX_SOFTIRQ);
}
#ifdef CONFIG_RPS
/* One global table that all flow-based protocols share. */
struct rps_sock_flow_table *rps_sock_flow_table __read_mostly;
EXPORT_SYMBOL(rps_sock_flow_table);
/*
* get_rps_cpu is called from netif_receive_skb and returns the target
* CPU from the RPS map of the receiving queue for a given skb.
* rcu_read_lock must be held on entry.
*/
static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
struct rps_dev_flow **rflowp)
{
struct ipv6hdr *ip6;
struct iphdr *ip;
struct netdev_rx_queue *rxqueue;
struct rps_map *map;
struct rps_dev_flow_table *flow_table;
struct rps_sock_flow_table *sock_flow_table;
int cpu = -1;
u8 ip_proto;
u16 tcpu;
u32 addr1, addr2, ihl;
union {
u32 v32;
u16 v16[2];
} ports;
if (skb_rx_queue_recorded(skb)) {
u16 index = skb_get_rx_queue(skb);
if (unlikely(index >= dev->num_rx_queues)) {
WARN_ONCE(dev->num_rx_queues > 1, "%s received packet "
"on queue %u, but number of RX queues is %u\n",
dev->name, index, dev->num_rx_queues);
goto done;
}
rxqueue = dev->_rx + index;
} else
rxqueue = dev->_rx;
if (!rxqueue->rps_map && !rxqueue->rps_flow_table)
goto done;
if (skb->rxhash)
goto got_hash; /* Skip hash computation on packet header */
switch (skb->protocol) {
case __constant_htons(ETH_P_IP):
if (!pskb_may_pull(skb, sizeof(*ip)))
goto done;
ip = (struct iphdr *) skb->data;
ip_proto = ip->protocol;
addr1 = (__force u32) ip->saddr;
addr2 = (__force u32) ip->daddr;
ihl = ip->ihl;
break;
case __constant_htons(ETH_P_IPV6):
if (!pskb_may_pull(skb, sizeof(*ip6)))
goto done;
ip6 = (struct ipv6hdr *) skb->data;
ip_proto = ip6->nexthdr;
addr1 = (__force u32) ip6->saddr.s6_addr32[3];
addr2 = (__force u32) ip6->daddr.s6_addr32[3];
ihl = (40 >> 2);
break;
default:
goto done;
}
switch (ip_proto) {
case IPPROTO_TCP:
case IPPROTO_UDP:
case IPPROTO_DCCP:
case IPPROTO_ESP:
case IPPROTO_AH:
case IPPROTO_SCTP:
case IPPROTO_UDPLITE:
if (pskb_may_pull(skb, (ihl * 4) + 4)) {
ports.v32 = * (__force u32 *) (skb->data + (ihl * 4));
if (ports.v16[1] < ports.v16[0])
swap(ports.v16[0], ports.v16[1]);
break;
}
default:
ports.v32 = 0;
break;
}
/* get a consistent hash (same value on both flow directions) */
if (addr2 < addr1)
swap(addr1, addr2);
skb->rxhash = jhash_3words(addr1, addr2, ports.v32, hashrnd);
if (!skb->rxhash)
skb->rxhash = 1;
got_hash:
flow_table = rcu_dereference(rxqueue->rps_flow_table);
sock_flow_table = rcu_dereference(rps_sock_flow_table);
if (flow_table && sock_flow_table) {
u16 next_cpu;
struct rps_dev_flow *rflow;
rflow = &flow_table->flows[skb->rxhash & flow_table->mask];
tcpu = rflow->cpu;
next_cpu = sock_flow_table->ents[skb->rxhash &
sock_flow_table->mask];
/*
* If the desired CPU (where last recvmsg was done) is
* different from current CPU (one in the rx-queue flow
* table entry), switch if one of the following holds:
* - Current CPU is unset (equal to RPS_NO_CPU).
* - Current CPU is offline.
* - The current CPU's queue tail has advanced beyond the
* last packet that was enqueued using this table entry.
* This guarantees that all previous packets for the flow
* have been dequeued, thus preserving in order delivery.
*/
if (unlikely(tcpu != next_cpu) &&
(tcpu == RPS_NO_CPU || !cpu_online(tcpu) ||
((int)(per_cpu(softnet_data, tcpu).input_queue_head -
rflow->last_qtail)) >= 0)) {
tcpu = rflow->cpu = next_cpu;
if (tcpu != RPS_NO_CPU)
rflow->last_qtail = per_cpu(softnet_data,
tcpu).input_queue_head;
}
if (tcpu != RPS_NO_CPU && cpu_online(tcpu)) {
*rflowp = rflow;
cpu = tcpu;
goto done;
}
}
map = rcu_dereference(rxqueue->rps_map);
if (map) {
tcpu = map->cpus[((u64) skb->rxhash * map->len) >> 32];
if (cpu_online(tcpu)) {
cpu = tcpu;
goto done;
}
}
done:
return cpu;
}
/* Called from hardirq (IPI) context */
static void rps_trigger_softirq(void *data)
{
struct softnet_data *sd = data;
____napi_schedule(sd, &sd->backlog);
sd->received_rps++;
}
#endif /* CONFIG_RPS */
/*
* Check if this softnet_data structure is another cpu one
* If yes, queue it to our IPI list and return 1
* If no, return 0
*/
static int rps_ipi_queued(struct softnet_data *sd)
{
#ifdef CONFIG_RPS
struct softnet_data *mysd = &__get_cpu_var(softnet_data);
if (sd != mysd) {
sd->rps_ipi_next = mysd->rps_ipi_list;
mysd->rps_ipi_list = sd;
__raise_softirq_irqoff(NET_RX_SOFTIRQ);
return 1;
}
#endif /* CONFIG_RPS */
return 0;
}
/*
* enqueue_to_backlog is called to queue an skb to a per CPU backlog
* queue (may be a remote CPU queue).
*/
static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
unsigned int *qtail)
{
struct softnet_data *sd;
unsigned long flags;
sd = &per_cpu(softnet_data, cpu);
local_irq_save(flags);
rps_lock(sd);
if (skb_queue_len(&sd->input_pkt_queue) <= netdev_max_backlog) {
if (skb_queue_len(&sd->input_pkt_queue)) {
enqueue:
__skb_queue_tail(&sd->input_pkt_queue, skb);
input_queue_tail_incr_save(sd, qtail);
rps_unlock(sd);
local_irq_restore(flags);
return NET_RX_SUCCESS;
}
/* Schedule NAPI for backlog device
* We can use non atomic operation since we own the queue lock
*/
if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
if (!rps_ipi_queued(sd))
____napi_schedule(sd, &sd->backlog);
}
goto enqueue;
}
sd->dropped++;
rps_unlock(sd);
local_irq_restore(flags);
kfree_skb(skb);
return NET_RX_DROP;
}
/**
* netif_rx - post buffer to the network code
* @skb: buffer to post
*
* This function receives a packet from a device driver and queues it for
* the upper (protocol) levels to process. It always succeeds. The buffer
* may be dropped during processing for congestion control or by the
* protocol layers.
*
* return values:
* NET_RX_SUCCESS (no congestion)
* NET_RX_DROP (packet was dropped)
*
*/
int netif_rx(struct sk_buff *skb)
{
int ret;
/* if netpoll wants it, pretend we never saw it */
if (netpoll_rx(skb))
return NET_RX_DROP;
if (netdev_tstamp_prequeue)
net_timestamp_check(skb);
#ifdef CONFIG_RPS
{
struct rps_dev_flow voidflow, *rflow = &voidflow;
int cpu;
rcu_read_lock();
cpu = get_rps_cpu(skb->dev, skb, &rflow);
if (cpu < 0)
cpu = smp_processor_id();
ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
rcu_read_unlock();
}
#else
{
unsigned int qtail;
ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
put_cpu();
}
#endif
return ret;
}
EXPORT_SYMBOL(netif_rx);
int netif_rx_ni(struct sk_buff *skb)
{
int err;
preempt_disable();
err = netif_rx(skb);
if (local_softirq_pending())
do_softirq();
preempt_enable();
return err;
}
EXPORT_SYMBOL(netif_rx_ni);
static void net_tx_action(struct softirq_action *h)
{
struct softnet_data *sd = &__get_cpu_var(softnet_data);
if (sd->completion_queue) {
struct sk_buff *clist;
local_irq_disable();
clist = sd->completion_queue;
sd->completion_queue = NULL;
local_irq_enable();
while (clist) {
struct sk_buff *skb = clist;
clist = clist->next;
WARN_ON(atomic_read(&skb->users));
__kfree_skb(skb);
}
}
if (sd->output_queue) {
struct Qdisc *head;
local_irq_disable();
head = sd->output_queue;
sd->output_queue = NULL;
sd->output_queue_tailp = &sd->output_queue;
local_irq_enable();
while (head) {
struct Qdisc *q = head;
spinlock_t *root_lock;
head = head->next_sched;
root_lock = qdisc_lock(q);
if (spin_trylock(root_lock)) {
smp_mb__before_clear_bit();
clear_bit(__QDISC_STATE_SCHED,
&q->state);
qdisc_run(q);
spin_unlock(root_lock);
} else {
if (!test_bit(__QDISC_STATE_DEACTIVATED,
&q->state)) {
__netif_reschedule(q);
} else {
smp_mb__before_clear_bit();
clear_bit(__QDISC_STATE_SCHED,
&q->state);
}
}
}
}
}
static inline int deliver_skb(struct sk_buff *skb,
struct packet_type *pt_prev,
struct net_device *orig_dev)
{
atomic_inc(&skb->users);
return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
}
#if (defined(CONFIG_BRIDGE) || defined(CONFIG_BRIDGE_MODULE)) && \
(defined(CONFIG_ATM_LANE) || defined(CONFIG_ATM_LANE_MODULE))
/* This hook is defined here for ATM LANE */
int (*br_fdb_test_addr_hook)(struct net_device *dev,
unsigned char *addr) __read_mostly;
EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
#endif
#ifdef CONFIG_NET_CLS_ACT
/* TODO: Maybe we should just force sch_ingress to be compiled in
* when CONFIG_NET_CLS_ACT is? otherwise some useless instructions
* a compare and 2 stores extra right now if we dont have it on
* but have CONFIG_NET_CLS_ACT
* NOTE: This doesnt stop any functionality; if you dont have
* the ingress scheduler, you just cant add policies on ingress.
*
*/
static int ing_filter(struct sk_buff *skb)
{
struct net_device *dev = skb->dev;
u32 ttl = G_TC_RTTL(skb->tc_verd);
struct netdev_queue *rxq;
int result = TC_ACT_OK;
struct Qdisc *q;
if (MAX_RED_LOOP < ttl++) {
printk(KERN_WARNING
"Redir loop detected Dropping packet (%d->%d)\n",
skb->skb_iif, dev->ifindex);
return TC_ACT_SHOT;
}
skb->tc_verd = SET_TC_RTTL(skb->tc_verd, ttl);
skb->tc_verd = SET_TC_AT(skb->tc_verd, AT_INGRESS);
rxq = &dev->rx_queue;
q = rxq->qdisc;
if (q != &noop_qdisc) {
spin_lock(qdisc_lock(q));
if (likely(!test_bit(__QDISC_STATE_DEACTIVATED, &q->state)))
result = qdisc_enqueue_root(skb, q);
spin_unlock(qdisc_lock(q));
}
return result;
}
static inline struct sk_buff *handle_ing(struct sk_buff *skb,
struct packet_type **pt_prev,
int *ret, struct net_device *orig_dev)
{
if (skb->dev->rx_queue.qdisc == &noop_qdisc)
goto out;
if (*pt_prev) {
*ret = deliver_skb(skb, *pt_prev, orig_dev);
*pt_prev = NULL;
}
switch (ing_filter(skb)) {
case TC_ACT_SHOT:
case TC_ACT_STOLEN:
kfree_skb(skb);
return NULL;
}
out:
skb->tc_verd = 0;
return skb;
}
#endif
/*
* netif_nit_deliver - deliver received packets to network taps
* @skb: buffer
*
* This function is used to deliver incoming packets to network
* taps. It should be used when the normal netif_receive_skb path
* is bypassed, for example because of VLAN acceleration.
*/
void netif_nit_deliver(struct sk_buff *skb)
{
struct packet_type *ptype;
if (list_empty(&ptype_all))
return;
skb_reset_network_header(skb);
skb_reset_transport_header(skb);
skb->mac_len = skb->network_header - skb->mac_header;
rcu_read_lock();
list_for_each_entry_rcu(ptype, &ptype_all, list) {
if (!ptype->dev || ptype->dev == skb->dev)
deliver_skb(skb, ptype, skb->dev);
}
rcu_read_unlock();
}
/**
* netdev_rx_handler_register - register receive handler
* @dev: device to register a handler for
* @rx_handler: receive handler to register
* @rx_handler_data: data pointer that is used by rx handler
*
* Register a receive hander for a device. This handler will then be
* called from __netif_receive_skb. A negative errno code is returned
* on a failure.
*
* The caller must hold the rtnl_mutex.
*/
int netdev_rx_handler_register(struct net_device *dev,
rx_handler_func_t *rx_handler,
void *rx_handler_data)
{
ASSERT_RTNL();
if (dev->rx_handler)
return -EBUSY;
rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
rcu_assign_pointer(dev->rx_handler, rx_handler);
return 0;
}
EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
/**
* netdev_rx_handler_unregister - unregister receive handler
* @dev: device to unregister a handler from
*
* Unregister a receive hander from a device.
*
* The caller must hold the rtnl_mutex.
*/
void netdev_rx_handler_unregister(struct net_device *dev)
{
ASSERT_RTNL();
rcu_assign_pointer(dev->rx_handler, NULL);
rcu_assign_pointer(dev->rx_handler_data, NULL);
}
EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
static inline void skb_bond_set_mac_by_master(struct sk_buff *skb,
struct net_device *master)
{
if (skb->pkt_type == PACKET_HOST) {
u16 *dest = (u16 *) eth_hdr(skb)->h_dest;
memcpy(dest, master->dev_addr, ETH_ALEN);
}
}
/* On bonding slaves other than the currently active slave, suppress
* duplicates except for 802.3ad ETH_P_SLOW, alb non-mcast/bcast, and
* ARP on active-backup slaves with arp_validate enabled.
*/
int __skb_bond_should_drop(struct sk_buff *skb, struct net_device *master)
{
struct net_device *dev = skb->dev;
if (master->priv_flags & IFF_MASTER_ARPMON)
dev->last_rx = jiffies;
if ((master->priv_flags & IFF_MASTER_ALB) &&
(master->priv_flags & IFF_BRIDGE_PORT)) {
/* Do address unmangle. The local destination address
* will be always the one master has. Provides the right
* functionality in a bridge.
*/
skb_bond_set_mac_by_master(skb, master);
}
if (dev->priv_flags & IFF_SLAVE_INACTIVE) {
if ((dev->priv_flags & IFF_SLAVE_NEEDARP) &&
skb->protocol == __cpu_to_be16(ETH_P_ARP))
return 0;
if (master->priv_flags & IFF_MASTER_ALB) {
if (skb->pkt_type != PACKET_BROADCAST &&
skb->pkt_type != PACKET_MULTICAST)
return 0;
}
if (master->priv_flags & IFF_MASTER_8023AD &&
skb->protocol == __cpu_to_be16(ETH_P_SLOW))
return 0;
return 1;
}
return 0;
}
EXPORT_SYMBOL(__skb_bond_should_drop);
static int __netif_receive_skb(struct sk_buff *skb)
{
struct packet_type *ptype, *pt_prev;
rx_handler_func_t *rx_handler;
struct net_device *orig_dev;
struct net_device *master;
struct net_device *null_or_orig;
struct net_device *orig_or_bond;
int ret = NET_RX_DROP;
__be16 type;
if (!netdev_tstamp_prequeue)
net_timestamp_check(skb);
if (vlan_tx_tag_present(skb) && vlan_hwaccel_do_receive(skb))
return NET_RX_SUCCESS;
/* if we've gotten here through NAPI, check netpoll */
if (netpoll_receive_skb(skb))
return NET_RX_DROP;
if (!skb->skb_iif)
skb->skb_iif = skb->dev->ifindex;
/*
* bonding note: skbs received on inactive slaves should only
* be delivered to pkt handlers that are exact matches. Also
* the deliver_no_wcard flag will be set. If packet handlers
* are sensitive to duplicate packets these skbs will need to
* be dropped at the handler. The vlan accel path may have
* already set the deliver_no_wcard flag.
*/
null_or_orig = NULL;
orig_dev = skb->dev;
master = ACCESS_ONCE(orig_dev->master);
if (skb->deliver_no_wcard)
null_or_orig = orig_dev;
else if (master) {
if (skb_bond_should_drop(skb, master)) {
skb->deliver_no_wcard = 1;
null_or_orig = orig_dev; /* deliver only exact match */
} else
skb->dev = master;
}
__this_cpu_inc(softnet_data.processed);
skb_reset_network_header(skb);
skb_reset_transport_header(skb);
skb->mac_len = skb->network_header - skb->mac_header;
pt_prev = NULL;
rcu_read_lock();
#ifdef CONFIG_NET_CLS_ACT
if (skb->tc_verd & TC_NCLS) {
skb->tc_verd = CLR_TC_NCLS(skb->tc_verd);
goto ncls;
}
#endif
list_for_each_entry_rcu(ptype, &ptype_all, list) {
if (ptype->dev == null_or_orig || ptype->dev == skb->dev ||
ptype->dev == orig_dev) {
if (pt_prev)
ret = deliver_skb(skb, pt_prev, orig_dev);
pt_prev = ptype;
}
}
#ifdef CONFIG_NET_CLS_ACT
skb = handle_ing(skb, &pt_prev, &ret, orig_dev);
if (!skb)
goto out;
ncls:
#endif
/* Handle special case of bridge or macvlan */
rx_handler = rcu_dereference(skb->dev->rx_handler);
if (rx_handler) {
if (pt_prev) {
ret = deliver_skb(skb, pt_prev, orig_dev);
pt_prev = NULL;
}
skb = rx_handler(skb);
if (!skb)
goto out;
}
/*
* Make sure frames received on VLAN interfaces stacked on
* bonding interfaces still make their way to any base bonding
* device that may have registered for a specific ptype. The
* handler may have to adjust skb->dev and orig_dev.
*/
orig_or_bond = orig_dev;
if ((skb->dev->priv_flags & IFF_802_1Q_VLAN) &&
(vlan_dev_real_dev(skb->dev)->priv_flags & IFF_BONDING)) {
orig_or_bond = vlan_dev_real_dev(skb->dev);
}
type = skb->protocol;
list_for_each_entry_rcu(ptype,
&ptype_base[ntohs(type) & PTYPE_HASH_MASK], list) {
if (ptype->type == type && (ptype->dev == null_or_orig ||
ptype->dev == skb->dev || ptype->dev == orig_dev ||
ptype->dev == orig_or_bond)) {
if (pt_prev)
ret = deliver_skb(skb, pt_prev, orig_dev);
pt_prev = ptype;
}
}
if (pt_prev) {
ret = pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
} else {
kfree_skb(skb);
/* Jamal, now you will not able to escape explaining
* me how you were going to use this. :-)
*/
ret = NET_RX_DROP;
}
out:
rcu_read_unlock();
return ret;
}
/**
* netif_receive_skb - process receive buffer from network
* @skb: buffer to process
*
* netif_receive_skb() is the main receive data processing function.
* It always succeeds. The buffer may be dropped during processing
* for congestion control or by the protocol layers.
*
* This function may only be called from softirq context and interrupts
* should be enabled.
*
* Return values (usually ignored):
* NET_RX_SUCCESS: no congestion
* NET_RX_DROP: packet was dropped
*/
int netif_receive_skb(struct sk_buff *skb)
{
if (netdev_tstamp_prequeue)
net_timestamp_check(skb);
#ifdef CONFIG_RPS
{
struct rps_dev_flow voidflow, *rflow = &voidflow;
int cpu, ret;
rcu_read_lock();
cpu = get_rps_cpu(skb->dev, skb, &rflow);
if (cpu >= 0) {
ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
rcu_read_unlock();
} else {
rcu_read_unlock();
ret = __netif_receive_skb(skb);
}
return ret;
}
#else
return __netif_receive_skb(skb);
#endif
}
EXPORT_SYMBOL(netif_receive_skb);
/* Network device is going away, flush any packets still pending
* Called with irqs disabled.
*/
static void flush_backlog(void *arg)
{
struct net_device *dev = arg;
struct softnet_data *sd = &__get_cpu_var(softnet_data);
struct sk_buff *skb, *tmp;
rps_lock(sd);
skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
if (skb->dev == dev) {
__skb_unlink(skb, &sd->input_pkt_queue);
kfree_skb(skb);
input_queue_head_incr(sd);
}
}
rps_unlock(sd);
skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
if (skb->dev == dev) {
__skb_unlink(skb, &sd->process_queue);
kfree_skb(skb);
input_queue_head_incr(sd);
}
}
}
static int napi_gro_complete(struct sk_buff *skb)
{
struct packet_type *ptype;
__be16 type = skb->protocol;
struct list_head *head = &ptype_base[ntohs(type) & PTYPE_HASH_MASK];
int err = -ENOENT;
if (NAPI_GRO_CB(skb)->count == 1) {
skb_shinfo(skb)->gso_size = 0;
goto out;
}
rcu_read_lock();
list_for_each_entry_rcu(ptype, head, list) {
if (ptype->type != type || ptype->dev || !ptype->gro_complete)
continue;
err = ptype->gro_complete(skb);
break;
}
rcu_read_unlock();
if (err) {
WARN_ON(&ptype->list == head);
kfree_skb(skb);
return NET_RX_SUCCESS;
}
out:
return netif_receive_skb(skb);
}
static void napi_gro_flush(struct napi_struct *napi)
{
struct sk_buff *skb, *next;
for (skb = napi->gro_list; skb; skb = next) {
next = skb->next;
skb->next = NULL;
napi_gro_complete(skb);
}
napi->gro_count = 0;
napi->gro_list = NULL;
}
enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
{
struct sk_buff **pp = NULL;
struct packet_type *ptype;
__be16 type = skb->protocol;
struct list_head *head = &ptype_base[ntohs(type) & PTYPE_HASH_MASK];
int same_flow;
int mac_len;
enum gro_result ret;
if (!(skb->dev->features & NETIF_F_GRO))
goto normal;
if (skb_is_gso(skb) || skb_has_frags(skb))
goto normal;
rcu_read_lock();
list_for_each_entry_rcu(ptype, head, list) {
if (ptype->type != type || ptype->dev || !ptype->gro_receive)
continue;
skb_set_network_header(skb, skb_gro_offset(skb));
mac_len = skb->network_header - skb->mac_header;
skb->mac_len = mac_len;
NAPI_GRO_CB(skb)->same_flow = 0;
NAPI_GRO_CB(skb)->flush = 0;
NAPI_GRO_CB(skb)->free = 0;
pp = ptype->gro_receive(&napi->gro_list, skb);
break;
}
rcu_read_unlock();
if (&ptype->list == head)
goto normal;
same_flow = NAPI_GRO_CB(skb)->same_flow;
ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
if (pp) {
struct sk_buff *nskb = *pp;
*pp = nskb->next;
nskb->next = NULL;
napi_gro_complete(nskb);
napi->gro_count--;
}
if (same_flow)
goto ok;
if (NAPI_GRO_CB(skb)->flush || napi->gro_count >= MAX_GRO_SKBS)
goto normal;
napi->gro_count++;
NAPI_GRO_CB(skb)->count = 1;
skb_shinfo(skb)->gso_size = skb_gro_len(skb);
skb->next = napi->gro_list;
napi->gro_list = skb;
ret = GRO_HELD;
pull:
if (skb_headlen(skb) < skb_gro_offset(skb)) {
int grow = skb_gro_offset(skb) - skb_headlen(skb);
BUG_ON(skb->end - skb->tail < grow);
memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
skb->tail += grow;
skb->data_len -= grow;
skb_shinfo(skb)->frags[0].page_offset += grow;
skb_shinfo(skb)->frags[0].size -= grow;
if (unlikely(!skb_shinfo(skb)->frags[0].size)) {
put_page(skb_shinfo(skb)->frags[0].page);
memmove(skb_shinfo(skb)->frags,
skb_shinfo(skb)->frags + 1,
--skb_shinfo(skb)->nr_frags);
}
}
ok:
return ret;
normal:
ret = GRO_NORMAL;
goto pull;
}
EXPORT_SYMBOL(dev_gro_receive);
static gro_result_t
__napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
{
struct sk_buff *p;
if (netpoll_rx_on(skb))
return GRO_NORMAL;
for (p = napi->gro_list; p; p = p->next) {
NAPI_GRO_CB(p)->same_flow =
(p->dev == skb->dev) &&
!compare_ether_header(skb_mac_header(p),
skb_gro_mac_header(skb));
NAPI_GRO_CB(p)->flush = 0;
}
return dev_gro_receive(napi, skb);
}
gro_result_t napi_skb_finish(gro_result_t ret, struct sk_buff *skb)
{
switch (ret) {
case GRO_NORMAL:
if (netif_receive_skb(skb))
ret = GRO_DROP;
break;
case GRO_DROP:
case GRO_MERGED_FREE:
kfree_skb(skb);
break;
case GRO_HELD:
case GRO_MERGED:
break;
}
return ret;
}
EXPORT_SYMBOL(napi_skb_finish);
void skb_gro_reset_offset(struct sk_buff *skb)
{
NAPI_GRO_CB(skb)->data_offset = 0;
NAPI_GRO_CB(skb)->frag0 = NULL;
NAPI_GRO_CB(skb)->frag0_len = 0;
if (skb->mac_header == skb->tail &&
!PageHighMem(skb_shinfo(skb)->frags[0].page)) {
NAPI_GRO_CB(skb)->frag0 =
page_address(skb_shinfo(skb)->frags[0].page) +
skb_shinfo(skb)->frags[0].page_offset;
NAPI_GRO_CB(skb)->frag0_len = skb_shinfo(skb)->frags[0].size;
}
}
EXPORT_SYMBOL(skb_gro_reset_offset);
gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
{
skb_gro_reset_offset(skb);
return napi_skb_finish(__napi_gro_receive(napi, skb), skb);
}
EXPORT_SYMBOL(napi_gro_receive);
void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
{
__skb_pull(skb, skb_headlen(skb));
skb_reserve(skb, NET_IP_ALIGN - skb_headroom(skb));
napi->skb = skb;
}
EXPORT_SYMBOL(napi_reuse_skb);
struct sk_buff *napi_get_frags(struct napi_struct *napi)
{
struct sk_buff *skb = napi->skb;
if (!skb) {
skb = netdev_alloc_skb_ip_align(napi->dev, GRO_MAX_HEAD);
if (skb)
napi->skb = skb;
}
return skb;
}
EXPORT_SYMBOL(napi_get_frags);
gro_result_t napi_frags_finish(struct napi_struct *napi, struct sk_buff *skb,
gro_result_t ret)
{
switch (ret) {
case GRO_NORMAL:
case GRO_HELD:
skb->protocol = eth_type_trans(skb, skb->dev);
if (ret == GRO_HELD)
skb_gro_pull(skb, -ETH_HLEN);
else if (netif_receive_skb(skb))
ret = GRO_DROP;
break;
case GRO_DROP:
case GRO_MERGED_FREE:
napi_reuse_skb(napi, skb);
break;
case GRO_MERGED:
break;
}
return ret;
}
EXPORT_SYMBOL(napi_frags_finish);
struct sk_buff *napi_frags_skb(struct napi_struct *napi)
{
struct sk_buff *skb = napi->skb;
struct ethhdr *eth;
unsigned int hlen;
unsigned int off;
napi->skb = NULL;
skb_reset_mac_header(skb);
skb_gro_reset_offset(skb);
off = skb_gro_offset(skb);
hlen = off + sizeof(*eth);
eth = skb_gro_header_fast(skb, off);
if (skb_gro_header_hard(skb, hlen)) {
eth = skb_gro_header_slow(skb, hlen, off);
if (unlikely(!eth)) {
napi_reuse_skb(napi, skb);
skb = NULL;
goto out;
}
}
skb_gro_pull(skb, sizeof(*eth));
/*
* This works because the only protocols we care about don't require
* special handling. We'll fix it up properly at the end.
*/
skb->protocol = eth->h_proto;
out:
return skb;
}
EXPORT_SYMBOL(napi_frags_skb);
gro_result_t napi_gro_frags(struct napi_struct *napi)
{
struct sk_buff *skb = napi_frags_skb(napi);
if (!skb)
return GRO_DROP;
return napi_frags_finish(napi, skb, __napi_gro_receive(napi, skb));
}
EXPORT_SYMBOL(napi_gro_frags);
/*
* net_rps_action sends any pending IPI's for rps.
* Note: called with local irq disabled, but exits with local irq enabled.
*/
static void net_rps_action_and_irq_enable(struct softnet_data *sd)
{
#ifdef CONFIG_RPS
struct softnet_data *remsd = sd->rps_ipi_list;
if (remsd) {
sd->rps_ipi_list = NULL;
local_irq_enable();
/* Send pending IPI's to kick RPS processing on remote cpus. */
while (remsd) {
struct softnet_data *next = remsd->rps_ipi_next;
if (cpu_online(remsd->cpu))
__smp_call_function_single(remsd->cpu,
&remsd->csd, 0);
remsd = next;
}
} else
#endif
local_irq_enable();
}
static int process_backlog(struct napi_struct *napi, int quota)
{
int work = 0;
struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
#ifdef CONFIG_RPS
/* Check if we have pending ipi, its better to send them now,
* not waiting net_rx_action() end.
*/
if (sd->rps_ipi_list) {
local_irq_disable();
net_rps_action_and_irq_enable(sd);
}
#endif
napi->weight = weight_p;
local_irq_disable();
while (work < quota) {
struct sk_buff *skb;
unsigned int qlen;
while ((skb = __skb_dequeue(&sd->process_queue))) {
local_irq_enable();
__netif_receive_skb(skb);
local_irq_disable();
input_queue_head_incr(sd);
if (++work >= quota) {
local_irq_enable();
return work;
}
}
rps_lock(sd);
qlen = skb_queue_len(&sd->input_pkt_queue);
if (qlen)
skb_queue_splice_tail_init(&sd->input_pkt_queue,
&sd->process_queue);
if (qlen < quota - work) {
/*
* Inline a custom version of __napi_complete().
* only current cpu owns and manipulates this napi,
* and NAPI_STATE_SCHED is the only possible flag set on backlog.
* we can use a plain write instead of clear_bit(),
* and we dont need an smp_mb() memory barrier.
*/
list_del(&napi->poll_list);
napi->state = 0;
quota = work + qlen;
}
rps_unlock(sd);
}
local_irq_enable();
return work;
}
/**
* __napi_schedule - schedule for receive
* @n: entry to schedule
*
* The entry's receive function will be scheduled to run
*/
void __napi_schedule(struct napi_struct *n)
{
unsigned long flags;
local_irq_save(flags);
____napi_schedule(&__get_cpu_var(softnet_data), n);
local_irq_restore(flags);
}
EXPORT_SYMBOL(__napi_schedule);
void __napi_complete(struct napi_struct *n)
{
BUG_ON(!test_bit(NAPI_STATE_SCHED, &n->state));
BUG_ON(n->gro_list);
list_del(&n->poll_list);
smp_mb__before_clear_bit();
clear_bit(NAPI_STATE_SCHED, &n->state);
}
EXPORT_SYMBOL(__napi_complete);
void napi_complete(struct napi_struct *n)
{
unsigned long flags;
/*
* don't let napi dequeue from the cpu poll list
* just in case its running on a different cpu
*/
if (unlikely(test_bit(NAPI_STATE_NPSVC, &n->state)))
return;
napi_gro_flush(n);
local_irq_save(flags);
__napi_complete(n);
local_irq_restore(flags);
}
EXPORT_SYMBOL(napi_complete);
void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
int (*poll)(struct napi_struct *, int), int weight)
{
INIT_LIST_HEAD(&napi->poll_list);
napi->gro_count = 0;
napi->gro_list = NULL;
napi->skb = NULL;
napi->poll = poll;
napi->weight = weight;
list_add(&napi->dev_list, &dev->napi_list);
napi->dev = dev;
#ifdef CONFIG_NETPOLL
spin_lock_init(&napi->poll_lock);
napi->poll_owner = -1;
#endif
set_bit(NAPI_STATE_SCHED, &napi->state);
}
EXPORT_SYMBOL(netif_napi_add);
void netif_napi_del(struct napi_struct *napi)
{
struct sk_buff *skb, *next;
list_del_init(&napi->dev_list);
napi_free_frags(napi);
for (skb = napi->gro_list; skb; skb = next) {
next = skb->next;
skb->next = NULL;
kfree_skb(skb);
}
napi->gro_list = NULL;
napi->gro_count = 0;
}
EXPORT_SYMBOL(netif_napi_del);
static void net_rx_action(struct softirq_action *h)
{
struct softnet_data *sd = &__get_cpu_var(softnet_data);
unsigned long time_limit = jiffies + 2;
int budget = netdev_budget;
void *have;
local_irq_disable();
while (!list_empty(&sd->poll_list)) {
struct napi_struct *n;
int work, weight;
/* If softirq window is exhuasted then punt.
* Allow this to run for 2 jiffies since which will allow
* an average latency of 1.5/HZ.
*/
if (unlikely(budget <= 0 || time_after(jiffies, time_limit)))
goto softnet_break;
local_irq_enable();
/* Even though interrupts have been re-enabled, this
* access is safe because interrupts can only add new
* entries to the tail of this list, and only ->poll()
* calls can remove this head entry from the list.
*/
n = list_first_entry(&sd->poll_list, struct napi_struct, poll_list);
have = netpoll_poll_lock(n);
weight = n->weight;
/* This NAPI_STATE_SCHED test is for avoiding a race
* with netpoll's poll_napi(). Only the entity which
* obtains the lock and sees NAPI_STATE_SCHED set will
* actually make the ->poll() call. Therefore we avoid
* accidently calling ->poll() when NAPI is not scheduled.
*/
work = 0;
if (test_bit(NAPI_STATE_SCHED, &n->state)) {
work = n->poll(n, weight);
trace_napi_poll(n);
}
WARN_ON_ONCE(work > weight);
budget -= work;
local_irq_disable();
/* Drivers must not modify the NAPI state if they
* consume the entire weight. In such cases this code
* still "owns" the NAPI instance and therefore can
* move the instance around on the list at-will.
*/
if (unlikely(work == weight)) {
if (unlikely(napi_disable_pending(n))) {
local_irq_enable();
napi_complete(n);
local_irq_disable();
} else
list_move_tail(&n->poll_list, &sd->poll_list);
}
netpoll_poll_unlock(have);
}
out:
net_rps_action_and_irq_enable(sd);
#ifdef CONFIG_NET_DMA
/*
* There may not be any more sk_buffs coming right now, so push
* any pending DMA copies to hardware
*/
dma_issue_pending_all();
#endif
return;
softnet_break:
sd->time_squeeze++;
__raise_softirq_irqoff(NET_RX_SOFTIRQ);
goto out;
}
static gifconf_func_t *gifconf_list[NPROTO];
/**
* register_gifconf - register a SIOCGIF handler
* @family: Address family
* @gifconf: Function handler
*
* Register protocol dependent address dumping routines. The handler
* that is passed must not be freed or reused until it has been replaced
* by another handler.
*/
int register_gifconf(unsigned int family, gifconf_func_t *gifconf)
{
if (family >= NPROTO)
return -EINVAL;
gifconf_list[family] = gifconf;
return 0;
}
EXPORT_SYMBOL(register_gifconf);
/*
* Map an interface index to its name (SIOCGIFNAME)
*/
/*
* We need this ioctl for efficient implementation of the
* if_indextoname() function required by the IPv6 API. Without
* it, we would have to search all the interfaces to find a
* match. --pb
*/
static int dev_ifname(struct net *net, struct ifreq __user *arg)
{
struct net_device *dev;
struct ifreq ifr;
/*
* Fetch the caller's info block.
*/
if (copy_from_user(&ifr, arg, sizeof(struct ifreq)))
return -EFAULT;
rcu_read_lock();
dev = dev_get_by_index_rcu(net, ifr.ifr_ifindex);
if (!dev) {
rcu_read_unlock();
return -ENODEV;
}
strcpy(ifr.ifr_name, dev->name);
rcu_read_unlock();
if (copy_to_user(arg, &ifr, sizeof(struct ifreq)))
return -EFAULT;
return 0;
}
/*
* Perform a SIOCGIFCONF call. This structure will change
* size eventually, and there is nothing I can do about it.
* Thus we will need a 'compatibility mode'.
*/
static int dev_ifconf(struct net *net, char __user *arg)
{
struct ifconf ifc;
struct net_device *dev;
char __user *pos;
int len;
int total;
int i;
/*
* Fetch the caller's info block.
*/
if (copy_from_user(&ifc, arg, sizeof(struct ifconf)))
return -EFAULT;
pos = ifc.ifc_buf;
len = ifc.ifc_len;
/*
* Loop over the interfaces, and write an info block for each.
*/
total = 0;
for_each_netdev(net, dev) {
for (i = 0; i < NPROTO; i++) {
if (gifconf_list[i]) {
int done;
if (!pos)
done = gifconf_list[i](dev, NULL, 0);
else
done = gifconf_list[i](dev, pos + total,
len - total);
if (done < 0)
return -EFAULT;
total += done;
}
}
}
/*
* All done. Write the updated control block back to the caller.
*/
ifc.ifc_len = total;
/*
* Both BSD and Solaris return 0 here, so we do too.
*/
return copy_to_user(arg, &ifc, sizeof(struct ifconf)) ? -EFAULT : 0;
}
#ifdef CONFIG_PROC_FS
/*
* This is invoked by the /proc filesystem handler to display a device
* in detail.
*/
void *dev_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU)
{
struct net *net = seq_file_net(seq);
loff_t off;
struct net_device *dev;
rcu_read_lock();
if (!*pos)
return SEQ_START_TOKEN;
off = 1;
for_each_netdev_rcu(net, dev)
if (off++ == *pos)
return dev;
return NULL;
}
void *dev_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct net_device *dev = (v == SEQ_START_TOKEN) ?
first_net_device(seq_file_net(seq)) :
next_net_device((struct net_device *)v);
++*pos;
return rcu_dereference(dev);
}
void dev_seq_stop(struct seq_file *seq, void *v)
__releases(RCU)
{
rcu_read_unlock();
}
static void dev_seq_printf_stats(struct seq_file *seq, struct net_device *dev)
{
const struct rtnl_link_stats64 *stats = dev_get_stats(dev);
seq_printf(seq, "%6s: %7llu %7llu %4llu %4llu %4llu %5llu %10llu %9llu "
"%8llu %7llu %4llu %4llu %4llu %5llu %7llu %10llu\n",
dev->name, stats->rx_bytes, stats->rx_packets,
stats->rx_errors,
stats->rx_dropped + stats->rx_missed_errors,
stats->rx_fifo_errors,
stats->rx_length_errors + stats->rx_over_errors +
stats->rx_crc_errors + stats->rx_frame_errors,
stats->rx_compressed, stats->multicast,
stats->tx_bytes, stats->tx_packets,
stats->tx_errors, stats->tx_dropped,
stats->tx_fifo_errors, stats->collisions,
stats->tx_carrier_errors +
stats->tx_aborted_errors +
stats->tx_window_errors +
stats->tx_heartbeat_errors,
stats->tx_compressed);
}
/*
* Called from the PROCfs module. This now uses the new arbitrary sized
* /proc/net interface to create /proc/net/dev
*/
static int dev_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq, "Inter-| Receive "
" | Transmit\n"
" face |bytes packets errs drop fifo frame "
"compressed multicast|bytes packets errs "
"drop fifo colls carrier compressed\n");
else
dev_seq_printf_stats(seq, v);
return 0;
}
static struct softnet_data *softnet_get_online(loff_t *pos)
{
struct softnet_data *sd = NULL;
while (*pos < nr_cpu_ids)
if (cpu_online(*pos)) {
sd = &per_cpu(softnet_data, *pos);
break;
} else
++*pos;
return sd;
}
static void *softnet_seq_start(struct seq_file *seq, loff_t *pos)
{
return softnet_get_online(pos);
}
static void *softnet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
++*pos;
return softnet_get_online(pos);
}
static void softnet_seq_stop(struct seq_file *seq, void *v)
{
}
static int softnet_seq_show(struct seq_file *seq, void *v)
{
struct softnet_data *sd = v;
seq_printf(seq, "%08x %08x %08x %08x %08x %08x %08x %08x %08x %08x\n",
sd->processed, sd->dropped, sd->time_squeeze, 0,
0, 0, 0, 0, /* was fastroute */
sd->cpu_collision, sd->received_rps);
return 0;
}
static const struct seq_operations dev_seq_ops = {
.start = dev_seq_start,
.next = dev_seq_next,
.stop = dev_seq_stop,
.show = dev_seq_show,
};
static int dev_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &dev_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations dev_seq_fops = {
.owner = THIS_MODULE,
.open = dev_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static const struct seq_operations softnet_seq_ops = {
.start = softnet_seq_start,
.next = softnet_seq_next,
.stop = softnet_seq_stop,
.show = softnet_seq_show,
};
static int softnet_seq_open(struct inode *inode, struct file *file)
{
return seq_open(file, &softnet_seq_ops);
}
static const struct file_operations softnet_seq_fops = {
.owner = THIS_MODULE,
.open = softnet_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static void *ptype_get_idx(loff_t pos)
{
struct packet_type *pt = NULL;
loff_t i = 0;
int t;
list_for_each_entry_rcu(pt, &ptype_all, list) {
if (i == pos)
return pt;
++i;
}
for (t = 0; t < PTYPE_HASH_SIZE; t++) {
list_for_each_entry_rcu(pt, &ptype_base[t], list) {
if (i == pos)
return pt;
++i;
}
}
return NULL;
}
static void *ptype_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU)
{
rcu_read_lock();
return *pos ? ptype_get_idx(*pos - 1) : SEQ_START_TOKEN;
}
static void *ptype_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct packet_type *pt;
struct list_head *nxt;
int hash;
++*pos;
if (v == SEQ_START_TOKEN)
return ptype_get_idx(0);
pt = v;
nxt = pt->list.next;
if (pt->type == htons(ETH_P_ALL)) {
if (nxt != &ptype_all)
goto found;
hash = 0;
nxt = ptype_base[0].next;
} else
hash = ntohs(pt->type) & PTYPE_HASH_MASK;
while (nxt == &ptype_base[hash]) {
if (++hash >= PTYPE_HASH_SIZE)
return NULL;
nxt = ptype_base[hash].next;
}
found:
return list_entry(nxt, struct packet_type, list);
}
static void ptype_seq_stop(struct seq_file *seq, void *v)
__releases(RCU)
{
rcu_read_unlock();
}
static int ptype_seq_show(struct seq_file *seq, void *v)
{
struct packet_type *pt = v;
if (v == SEQ_START_TOKEN)
seq_puts(seq, "Type Device Function\n");
else if (pt->dev == NULL || dev_net(pt->dev) == seq_file_net(seq)) {
if (pt->type == htons(ETH_P_ALL))
seq_puts(seq, "ALL ");
else
seq_printf(seq, "%04x", ntohs(pt->type));
seq_printf(seq, " %-8s %pF\n",
pt->dev ? pt->dev->name : "", pt->func);
}
return 0;
}
static const struct seq_operations ptype_seq_ops = {
.start = ptype_seq_start,
.next = ptype_seq_next,
.stop = ptype_seq_stop,
.show = ptype_seq_show,
};
static int ptype_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &ptype_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations ptype_seq_fops = {
.owner = THIS_MODULE,
.open = ptype_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static int __net_init dev_proc_net_init(struct net *net)
{
int rc = -ENOMEM;
if (!proc_net_fops_create(net, "dev", S_IRUGO, &dev_seq_fops))
goto out;
if (!proc_net_fops_create(net, "softnet_stat", S_IRUGO, &softnet_seq_fops))
goto out_dev;
if (!proc_net_fops_create(net, "ptype", S_IRUGO, &ptype_seq_fops))
goto out_softnet;
if (wext_proc_init(net))
goto out_ptype;
rc = 0;
out:
return rc;
out_ptype:
proc_net_remove(net, "ptype");
out_softnet:
proc_net_remove(net, "softnet_stat");
out_dev:
proc_net_remove(net, "dev");
goto out;
}
static void __net_exit dev_proc_net_exit(struct net *net)
{
wext_proc_exit(net);
proc_net_remove(net, "ptype");
proc_net_remove(net, "softnet_stat");
proc_net_remove(net, "dev");
}
static struct pernet_operations __net_initdata dev_proc_ops = {
.init = dev_proc_net_init,
.exit = dev_proc_net_exit,
};
static int __init dev_proc_init(void)
{
return register_pernet_subsys(&dev_proc_ops);
}
#else
#define dev_proc_init() 0
#endif /* CONFIG_PROC_FS */
/**
* netdev_set_master - set up master/slave pair
* @slave: slave device
* @master: new master device
*
* Changes the master device of the slave. Pass %NULL to break the
* bonding. The caller must hold the RTNL semaphore. On a failure
* a negative errno code is returned. On success the reference counts
* are adjusted, %RTM_NEWLINK is sent to the routing socket and the
* function returns zero.
*/
int netdev_set_master(struct net_device *slave, struct net_device *master)
{
struct net_device *old = slave->master;
ASSERT_RTNL();
if (master) {
if (old)
return -EBUSY;
dev_hold(master);
}
slave->master = master;
if (old) {
synchronize_net();
dev_put(old);
}
if (master)
slave->flags |= IFF_SLAVE;
else
slave->flags &= ~IFF_SLAVE;
rtmsg_ifinfo(RTM_NEWLINK, slave, IFF_SLAVE);
return 0;
}
EXPORT_SYMBOL(netdev_set_master);
static void dev_change_rx_flags(struct net_device *dev, int flags)
{
const struct net_device_ops *ops = dev->netdev_ops;
if ((dev->flags & IFF_UP) && ops->ndo_change_rx_flags)
ops->ndo_change_rx_flags(dev, flags);
}
static int __dev_set_promiscuity(struct net_device *dev, int inc)
{
unsigned short old_flags = dev->flags;
uid_t uid;
gid_t gid;
ASSERT_RTNL();
dev->flags |= IFF_PROMISC;
dev->promiscuity += inc;
if (dev->promiscuity == 0) {
/*
* Avoid overflow.
* If inc causes overflow, untouch promisc and return error.
*/
if (inc < 0)
dev->flags &= ~IFF_PROMISC;
else {
dev->promiscuity -= inc;
printk(KERN_WARNING "%s: promiscuity touches roof, "
"set promiscuity failed, promiscuity feature "
"of device might be broken.\n", dev->name);
return -EOVERFLOW;
}
}
if (dev->flags != old_flags) {
printk(KERN_INFO "device %s %s promiscuous mode\n",
dev->name, (dev->flags & IFF_PROMISC) ? "entered" :
"left");
if (audit_enabled) {
current_uid_gid(&uid, &gid);
audit_log(current->audit_context, GFP_ATOMIC,
AUDIT_ANOM_PROMISCUOUS,
"dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
dev->name, (dev->flags & IFF_PROMISC),
(old_flags & IFF_PROMISC),
audit_get_loginuid(current),
uid, gid,
audit_get_sessionid(current));
}
dev_change_rx_flags(dev, IFF_PROMISC);
}
return 0;
}
/**
* dev_set_promiscuity - update promiscuity count on a device
* @dev: device
* @inc: modifier
*
* Add or remove promiscuity from a device. While the count in the device
* remains above zero the interface remains promiscuous. Once it hits zero
* the device reverts back to normal filtering operation. A negative inc
* value is used to drop promiscuity on the device.
* Return 0 if successful or a negative errno code on error.
*/
int dev_set_promiscuity(struct net_device *dev, int inc)
{
unsigned short old_flags = dev->flags;
int err;
err = __dev_set_promiscuity(dev, inc);
if (err < 0)
return err;
if (dev->flags != old_flags)
dev_set_rx_mode(dev);
return err;
}
EXPORT_SYMBOL(dev_set_promiscuity);
/**
* dev_set_allmulti - update allmulti count on a device
* @dev: device
* @inc: modifier
*
* Add or remove reception of all multicast frames to a device. While the
* count in the device remains above zero the interface remains listening
* to all interfaces. Once it hits zero the device reverts back to normal
* filtering operation. A negative @inc value is used to drop the counter
* when releasing a resource needing all multicasts.
* Return 0 if successful or a negative errno code on error.
*/
int dev_set_allmulti(struct net_device *dev, int inc)
{
unsigned short old_flags = dev->flags;
ASSERT_RTNL();
dev->flags |= IFF_ALLMULTI;
dev->allmulti += inc;
if (dev->allmulti == 0) {
/*
* Avoid overflow.
* If inc causes overflow, untouch allmulti and return error.
*/
if (inc < 0)
dev->flags &= ~IFF_ALLMULTI;
else {
dev->allmulti -= inc;
printk(KERN_WARNING "%s: allmulti touches roof, "
"set allmulti failed, allmulti feature of "
"device might be broken.\n", dev->name);
return -EOVERFLOW;
}
}
if (dev->flags ^ old_flags) {
dev_change_rx_flags(dev, IFF_ALLMULTI);
dev_set_rx_mode(dev);
}
return 0;
}
EXPORT_SYMBOL(dev_set_allmulti);
/*
* Upload unicast and multicast address lists to device and
* configure RX filtering. When the device doesn't support unicast
* filtering it is put in promiscuous mode while unicast addresses
* are present.
*/
void __dev_set_rx_mode(struct net_device *dev)
{
const struct net_device_ops *ops = dev->netdev_ops;
/* dev_open will call this function so the list will stay sane. */
if (!(dev->flags&IFF_UP))
return;
if (!netif_device_present(dev))
return;
if (ops->ndo_set_rx_mode)
ops->ndo_set_rx_mode(dev);
else {
/* Unicast addresses changes may only happen under the rtnl,
* therefore calling __dev_set_promiscuity here is safe.
*/
if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
__dev_set_promiscuity(dev, 1);
dev->uc_promisc = 1;
} else if (netdev_uc_empty(dev) && dev->uc_promisc) {
__dev_set_promiscuity(dev, -1);
dev->uc_promisc = 0;
}
if (ops->ndo_set_multicast_list)
ops->ndo_set_multicast_list(dev);
}
}
void dev_set_rx_mode(struct net_device *dev)
{
netif_addr_lock_bh(dev);
__dev_set_rx_mode(dev);
netif_addr_unlock_bh(dev);
}
/**
* dev_get_flags - get flags reported to userspace
* @dev: device
*
* Get the combination of flag bits exported through APIs to userspace.
*/
unsigned dev_get_flags(const struct net_device *dev)
{
unsigned flags;
flags = (dev->flags & ~(IFF_PROMISC |
IFF_ALLMULTI |
IFF_RUNNING |
IFF_LOWER_UP |
IFF_DORMANT)) |
(dev->gflags & (IFF_PROMISC |
IFF_ALLMULTI));
if (netif_running(dev)) {
if (netif_oper_up(dev))
flags |= IFF_RUNNING;
if (netif_carrier_ok(dev))
flags |= IFF_LOWER_UP;
if (netif_dormant(dev))
flags |= IFF_DORMANT;
}
return flags;
}
EXPORT_SYMBOL(dev_get_flags);
int __dev_change_flags(struct net_device *dev, unsigned int flags)
{
int old_flags = dev->flags;
int ret;
ASSERT_RTNL();
/*
* Set the flags on our device.
*/
dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
IFF_AUTOMEDIA)) |
(dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
IFF_ALLMULTI));
/*
* Load in the correct multicast list now the flags have changed.
*/
if ((old_flags ^ flags) & IFF_MULTICAST)
dev_change_rx_flags(dev, IFF_MULTICAST);
dev_set_rx_mode(dev);
/*
* Have we downed the interface. We handle IFF_UP ourselves
* according to user attempts to set it, rather than blindly
* setting it.
*/
ret = 0;
if ((old_flags ^ flags) & IFF_UP) { /* Bit is different ? */
ret = ((old_flags & IFF_UP) ? __dev_close : __dev_open)(dev);
if (!ret)
dev_set_rx_mode(dev);
}
if ((flags ^ dev->gflags) & IFF_PROMISC) {
int inc = (flags & IFF_PROMISC) ? 1 : -1;
dev->gflags ^= IFF_PROMISC;
dev_set_promiscuity(dev, inc);
}
/* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
is important. Some (broken) drivers set IFF_PROMISC, when
IFF_ALLMULTI is requested not asking us and not reporting.
*/
if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
dev->gflags ^= IFF_ALLMULTI;
dev_set_allmulti(dev, inc);
}
return ret;
}
void __dev_notify_flags(struct net_device *dev, unsigned int old_flags)
{
unsigned int changes = dev->flags ^ old_flags;
if (changes & IFF_UP) {
if (dev->flags & IFF_UP)
call_netdevice_notifiers(NETDEV_UP, dev);
else
call_netdevice_notifiers(NETDEV_DOWN, dev);
}
if (dev->flags & IFF_UP &&
(changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE)))
call_netdevice_notifiers(NETDEV_CHANGE, dev);
}
/**
* dev_change_flags - change device settings
* @dev: device
* @flags: device state flags
*
* Change settings on device based state flags. The flags are
* in the userspace exported format.
*/
int dev_change_flags(struct net_device *dev, unsigned flags)
{
int ret, changes;
int old_flags = dev->flags;
ret = __dev_change_flags(dev, flags);
if (ret < 0)
return ret;
changes = old_flags ^ dev->flags;
if (changes)
rtmsg_ifinfo(RTM_NEWLINK, dev, changes);
__dev_notify_flags(dev, old_flags);
return ret;
}
EXPORT_SYMBOL(dev_change_flags);
/**
* dev_set_mtu - Change maximum transfer unit
* @dev: device
* @new_mtu: new transfer unit
*
* Change the maximum transfer size of the network device.
*/
int dev_set_mtu(struct net_device *dev, int new_mtu)
{
const struct net_device_ops *ops = dev->netdev_ops;
int err;
if (new_mtu == dev->mtu)
return 0;
/* MTU must be positive. */
if (new_mtu < 0)
return -EINVAL;
if (!netif_device_present(dev))
return -ENODEV;
err = 0;
if (ops->ndo_change_mtu)
err = ops->ndo_change_mtu(dev, new_mtu);
else
dev->mtu = new_mtu;
if (!err && dev->flags & IFF_UP)
call_netdevice_notifiers(NETDEV_CHANGEMTU, dev);
return err;
}
EXPORT_SYMBOL(dev_set_mtu);
/**
* dev_set_mac_address - Change Media Access Control Address
* @dev: device
* @sa: new address
*
* Change the hardware (MAC) address of the device
*/
int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa)
{
const struct net_device_ops *ops = dev->netdev_ops;
int err;
if (!ops->ndo_set_mac_address)
return -EOPNOTSUPP;
if (sa->sa_family != dev->type)
return -EINVAL;
if (!netif_device_present(dev))
return -ENODEV;
err = ops->ndo_set_mac_address(dev, sa);
if (!err)
call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
return err;
}
EXPORT_SYMBOL(dev_set_mac_address);
/*
* Perform the SIOCxIFxxx calls, inside rcu_read_lock()
*/
static int dev_ifsioc_locked(struct net *net, struct ifreq *ifr, unsigned int cmd)
{
int err;
struct net_device *dev = dev_get_by_name_rcu(net, ifr->ifr_name);
if (!dev)
return -ENODEV;
switch (cmd) {
case SIOCGIFFLAGS: /* Get interface flags */
ifr->ifr_flags = (short) dev_get_flags(dev);
return 0;
case SIOCGIFMETRIC: /* Get the metric on the interface
(currently unused) */
ifr->ifr_metric = 0;
return 0;
case SIOCGIFMTU: /* Get the MTU of a device */
ifr->ifr_mtu = dev->mtu;
return 0;
case SIOCGIFHWADDR:
if (!dev->addr_len)
memset(ifr->ifr_hwaddr.sa_data, 0, sizeof ifr->ifr_hwaddr.sa_data);
else
memcpy(ifr->ifr_hwaddr.sa_data, dev->dev_addr,
min(sizeof ifr->ifr_hwaddr.sa_data, (size_t) dev->addr_len));
ifr->ifr_hwaddr.sa_family = dev->type;
return 0;
case SIOCGIFSLAVE:
err = -EINVAL;
break;
case SIOCGIFMAP:
ifr->ifr_map.mem_start = dev->mem_start;
ifr->ifr_map.mem_end = dev->mem_end;
ifr->ifr_map.base_addr = dev->base_addr;
ifr->ifr_map.irq = dev->irq;
ifr->ifr_map.dma = dev->dma;
ifr->ifr_map.port = dev->if_port;
return 0;
case SIOCGIFINDEX:
ifr->ifr_ifindex = dev->ifindex;
return 0;
case SIOCGIFTXQLEN:
ifr->ifr_qlen = dev->tx_queue_len;
return 0;
default:
/* dev_ioctl() should ensure this case
* is never reached
*/
WARN_ON(1);
err = -EINVAL;
break;
}
return err;
}
/*
* Perform the SIOCxIFxxx calls, inside rtnl_lock()
*/
static int dev_ifsioc(struct net *net, struct ifreq *ifr, unsigned int cmd)
{
int err;
struct net_device *dev = __dev_get_by_name(net, ifr->ifr_name);
const struct net_device_ops *ops;
if (!dev)
return -ENODEV;
ops = dev->netdev_ops;
switch (cmd) {
case SIOCSIFFLAGS: /* Set interface flags */
return dev_change_flags(dev, ifr->ifr_flags);
case SIOCSIFMETRIC: /* Set the metric on the interface
(currently unused) */
return -EOPNOTSUPP;
case SIOCSIFMTU: /* Set the MTU of a device */
return dev_set_mtu(dev, ifr->ifr_mtu);
case SIOCSIFHWADDR:
return dev_set_mac_address(dev, &ifr->ifr_hwaddr);
case SIOCSIFHWBROADCAST:
if (ifr->ifr_hwaddr.sa_family != dev->type)
return -EINVAL;
memcpy(dev->broadcast, ifr->ifr_hwaddr.sa_data,
min(sizeof ifr->ifr_hwaddr.sa_data, (size_t) dev->addr_len));
call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
return 0;
case SIOCSIFMAP:
if (ops->ndo_set_config) {
if (!netif_device_present(dev))
return -ENODEV;
return ops->ndo_set_config(dev, &ifr->ifr_map);
}
return -EOPNOTSUPP;
case SIOCADDMULTI:
if ((!ops->ndo_set_multicast_list && !ops->ndo_set_rx_mode) ||
ifr->ifr_hwaddr.sa_family != AF_UNSPEC)
return -EINVAL;
if (!netif_device_present(dev))
return -ENODEV;
return dev_mc_add_global(dev, ifr->ifr_hwaddr.sa_data);
case SIOCDELMULTI:
if ((!ops->ndo_set_multicast_list && !ops->ndo_set_rx_mode) ||
ifr->ifr_hwaddr.sa_family != AF_UNSPEC)
return -EINVAL;
if (!netif_device_present(dev))
return -ENODEV;
return dev_mc_del_global(dev, ifr->ifr_hwaddr.sa_data);
case SIOCSIFTXQLEN:
if (ifr->ifr_qlen < 0)
return -EINVAL;
dev->tx_queue_len = ifr->ifr_qlen;
return 0;
case SIOCSIFNAME:
ifr->ifr_newname[IFNAMSIZ-1] = '\0';
return dev_change_name(dev, ifr->ifr_newname);
/*
* Unknown or private ioctl
*/
default:
if ((cmd >= SIOCDEVPRIVATE &&
cmd <= SIOCDEVPRIVATE + 15) ||
cmd == SIOCBONDENSLAVE ||
cmd == SIOCBONDRELEASE ||
cmd == SIOCBONDSETHWADDR ||
cmd == SIOCBONDSLAVEINFOQUERY ||
cmd == SIOCBONDINFOQUERY ||
cmd == SIOCBONDCHANGEACTIVE ||
cmd == SIOCGMIIPHY ||
cmd == SIOCGMIIREG ||
cmd == SIOCSMIIREG ||
cmd == SIOCBRADDIF ||
cmd == SIOCBRDELIF ||
cmd == SIOCSHWTSTAMP ||
cmd == SIOCWANDEV) {
err = -EOPNOTSUPP;
if (ops->ndo_do_ioctl) {
if (netif_device_present(dev))
err = ops->ndo_do_ioctl(dev, ifr, cmd);
else
err = -ENODEV;
}
} else
err = -EINVAL;
}
return err;
}
/*
* This function handles all "interface"-type I/O control requests. The actual
* 'doing' part of this is dev_ifsioc above.
*/
/**
* dev_ioctl - network device ioctl
* @net: the applicable net namespace
* @cmd: command to issue
* @arg: pointer to a struct ifreq in user space
*
* Issue ioctl functions to devices. This is normally called by the
* user space syscall interfaces but can sometimes be useful for
* other purposes. The return value is the return from the syscall if
* positive or a negative errno code on error.
*/
int dev_ioctl(struct net *net, unsigned int cmd, void __user *arg)
{
struct ifreq ifr;
int ret;
char *colon;
/* One special case: SIOCGIFCONF takes ifconf argument
and requires shared lock, because it sleeps writing
to user space.
*/
if (cmd == SIOCGIFCONF) {
rtnl_lock();
ret = dev_ifconf(net, (char __user *) arg);
rtnl_unlock();
return ret;
}
if (cmd == SIOCGIFNAME)
return dev_ifname(net, (struct ifreq __user *)arg);
if (copy_from_user(&ifr, arg, sizeof(struct ifreq)))
return -EFAULT;
ifr.ifr_name[IFNAMSIZ-1] = 0;
colon = strchr(ifr.ifr_name, ':');
if (colon)
*colon = 0;
/*
* See which interface the caller is talking about.
*/
switch (cmd) {
/*
* These ioctl calls:
* - can be done by all.
* - atomic and do not require locking.
* - return a value
*/
case SIOCGIFFLAGS:
case SIOCGIFMETRIC:
case SIOCGIFMTU:
case SIOCGIFHWADDR:
case SIOCGIFSLAVE:
case SIOCGIFMAP:
case SIOCGIFINDEX:
case SIOCGIFTXQLEN:
dev_load(net, ifr.ifr_name);
rcu_read_lock();
ret = dev_ifsioc_locked(net, &ifr, cmd);
rcu_read_unlock();
if (!ret) {
if (colon)
*colon = ':';
if (copy_to_user(arg, &ifr,
sizeof(struct ifreq)))
ret = -EFAULT;
}
return ret;
case SIOCETHTOOL:
dev_load(net, ifr.ifr_name);
rtnl_lock();
ret = dev_ethtool(net, &ifr);
rtnl_unlock();
if (!ret) {
if (colon)
*colon = ':';
if (copy_to_user(arg, &ifr,
sizeof(struct ifreq)))
ret = -EFAULT;
}
return ret;
/*
* These ioctl calls:
* - require superuser power.
* - require strict serialization.
* - return a value
*/
case SIOCGMIIPHY:
case SIOCGMIIREG:
case SIOCSIFNAME:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
dev_load(net, ifr.ifr_name);
rtnl_lock();
ret = dev_ifsioc(net, &ifr, cmd);
rtnl_unlock();
if (!ret) {
if (colon)
*colon = ':';
if (copy_to_user(arg, &ifr,
sizeof(struct ifreq)))
ret = -EFAULT;
}
return ret;
/*
* These ioctl calls:
* - require superuser power.
* - require strict serialization.
* - do not return a value
*/
case SIOCSIFFLAGS:
case SIOCSIFMETRIC:
case SIOCSIFMTU:
case SIOCSIFMAP:
case SIOCSIFHWADDR:
case SIOCSIFSLAVE:
case SIOCADDMULTI:
case SIOCDELMULTI:
case SIOCSIFHWBROADCAST:
case SIOCSIFTXQLEN:
case SIOCSMIIREG:
case SIOCBONDENSLAVE:
case SIOCBONDRELEASE:
case SIOCBONDSETHWADDR:
case SIOCBONDCHANGEACTIVE:
case SIOCBRADDIF:
case SIOCBRDELIF:
case SIOCSHWTSTAMP:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
/* fall through */
case SIOCBONDSLAVEINFOQUERY:
case SIOCBONDINFOQUERY:
dev_load(net, ifr.ifr_name);
rtnl_lock();
ret = dev_ifsioc(net, &ifr, cmd);
rtnl_unlock();
return ret;
case SIOCGIFMEM:
/* Get the per device memory space. We can add this but
* currently do not support it */
case SIOCSIFMEM:
/* Set the per device memory buffer space.
* Not applicable in our case */
case SIOCSIFLINK:
return -EINVAL;
/*
* Unknown or private ioctl.
*/
default:
if (cmd == SIOCWANDEV ||
(cmd >= SIOCDEVPRIVATE &&
cmd <= SIOCDEVPRIVATE + 15)) {
dev_load(net, ifr.ifr_name);
rtnl_lock();
ret = dev_ifsioc(net, &ifr, cmd);
rtnl_unlock();
if (!ret && copy_to_user(arg, &ifr,
sizeof(struct ifreq)))
ret = -EFAULT;
return ret;
}
/* Take care of Wireless Extensions */
if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST)
return wext_handle_ioctl(net, &ifr, cmd, arg);
return -EINVAL;
}
}
/**
* dev_new_index - allocate an ifindex
* @net: the applicable net namespace
*
* Returns a suitable unique value for a new device interface
* number. The caller must hold the rtnl semaphore or the
* dev_base_lock to be sure it remains unique.
*/
static int dev_new_index(struct net *net)
{
static int ifindex;
for (;;) {
if (++ifindex <= 0)
ifindex = 1;
if (!__dev_get_by_index(net, ifindex))
return ifindex;
}
}
/* Delayed registration/unregisteration */
static LIST_HEAD(net_todo_list);
static void net_set_todo(struct net_device *dev)
{
list_add_tail(&dev->todo_list, &net_todo_list);
}
static void rollback_registered_many(struct list_head *head)
{
struct net_device *dev, *tmp;
BUG_ON(dev_boot_phase);
ASSERT_RTNL();
list_for_each_entry_safe(dev, tmp, head, unreg_list) {
/* Some devices call without registering
* for initialization unwind. Remove those
* devices and proceed with the remaining.
*/
if (dev->reg_state == NETREG_UNINITIALIZED) {
pr_debug("unregister_netdevice: device %s/%p never "
"was registered\n", dev->name, dev);
WARN_ON(1);
list_del(&dev->unreg_list);
continue;
}
BUG_ON(dev->reg_state != NETREG_REGISTERED);
/* If device is running, close it first. */
dev_close(dev);
/* And unlink it from device chain. */
unlist_netdevice(dev);
dev->reg_state = NETREG_UNREGISTERING;
}
synchronize_net();
list_for_each_entry(dev, head, unreg_list) {
/* Shutdown queueing discipline. */
dev_shutdown(dev);
/* Notify protocols, that we are about to destroy
this device. They should clean all the things.
*/
call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
if (!dev->rtnl_link_ops ||
dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
rtmsg_ifinfo(RTM_DELLINK, dev, ~0U);
/*
* Flush the unicast and multicast chains
*/
dev_uc_flush(dev);
dev_mc_flush(dev);
if (dev->netdev_ops->ndo_uninit)
dev->netdev_ops->ndo_uninit(dev);
/* Notifier chain MUST detach us from master device. */
WARN_ON(dev->master);
/* Remove entries from kobject tree */
netdev_unregister_kobject(dev);
}
/* Process any work delayed until the end of the batch */
dev = list_first_entry(head, struct net_device, unreg_list);
call_netdevice_notifiers(NETDEV_UNREGISTER_BATCH, dev);
synchronize_net();
list_for_each_entry(dev, head, unreg_list)
dev_put(dev);
}
static void rollback_registered(struct net_device *dev)
{
LIST_HEAD(single);
list_add(&dev->unreg_list, &single);
rollback_registered_many(&single);
}
static void __netdev_init_queue_locks_one(struct net_device *dev,
struct netdev_queue *dev_queue,
void *_unused)
{
spin_lock_init(&dev_queue->_xmit_lock);
netdev_set_xmit_lockdep_class(&dev_queue->_xmit_lock, dev->type);
dev_queue->xmit_lock_owner = -1;
}
static void netdev_init_queue_locks(struct net_device *dev)
{
netdev_for_each_tx_queue(dev, __netdev_init_queue_locks_one, NULL);
__netdev_init_queue_locks_one(dev, &dev->rx_queue, NULL);
}
unsigned long netdev_fix_features(unsigned long features, const char *name)
{
/* Fix illegal SG+CSUM combinations. */
if ((features & NETIF_F_SG) &&
!(features & NETIF_F_ALL_CSUM)) {
if (name)
printk(KERN_NOTICE "%s: Dropping NETIF_F_SG since no "
"checksum feature.\n", name);
features &= ~NETIF_F_SG;
}
/* TSO requires that SG is present as well. */
if ((features & NETIF_F_TSO) && !(features & NETIF_F_SG)) {
if (name)
printk(KERN_NOTICE "%s: Dropping NETIF_F_TSO since no "
"SG feature.\n", name);
features &= ~NETIF_F_TSO;
}
if (features & NETIF_F_UFO) {
if (!(features & NETIF_F_GEN_CSUM)) {
if (name)
printk(KERN_ERR "%s: Dropping NETIF_F_UFO "
"since no NETIF_F_HW_CSUM feature.\n",
name);
features &= ~NETIF_F_UFO;
}
if (!(features & NETIF_F_SG)) {
if (name)
printk(KERN_ERR "%s: Dropping NETIF_F_UFO "
"since no NETIF_F_SG feature.\n", name);
features &= ~NETIF_F_UFO;
}
}
return features;
}
EXPORT_SYMBOL(netdev_fix_features);
/**
* netif_stacked_transfer_operstate - transfer operstate
* @rootdev: the root or lower level device to transfer state from
* @dev: the device to transfer operstate to
*
* Transfer operational state from root to device. This is normally
* called when a stacking relationship exists between the root
* device and the device(a leaf device).
*/
void netif_stacked_transfer_operstate(const struct net_device *rootdev,
struct net_device *dev)
{
if (rootdev->operstate == IF_OPER_DORMANT)
netif_dormant_on(dev);
else
netif_dormant_off(dev);
if (netif_carrier_ok(rootdev)) {
if (!netif_carrier_ok(dev))
netif_carrier_on(dev);
} else {
if (netif_carrier_ok(dev))
netif_carrier_off(dev);
}
}
EXPORT_SYMBOL(netif_stacked_transfer_operstate);
/**
* register_netdevice - register a network device
* @dev: device to register
*
* Take a completed network device structure and add it to the kernel
* interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
* chain. 0 is returned on success. A negative errno code is returned
* on a failure to set up the device, or if the name is a duplicate.
*
* Callers must hold the rtnl semaphore. You may want
* register_netdev() instead of this.
*
* BUGS:
* The locking appears insufficient to guarantee two parallel registers
* will not get the same name.
*/
int register_netdevice(struct net_device *dev)
{
int ret;
struct net *net = dev_net(dev);
BUG_ON(dev_boot_phase);
ASSERT_RTNL();
might_sleep();
/* When net_device's are persistent, this will be fatal. */
BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
BUG_ON(!net);
spin_lock_init(&dev->addr_list_lock);
netdev_set_addr_lockdep_class(dev);
netdev_init_queue_locks(dev);
dev->iflink = -1;
#ifdef CONFIG_RPS
if (!dev->num_rx_queues) {
/*
* Allocate a single RX queue if driver never called
* alloc_netdev_mq
*/
dev->_rx = kzalloc(sizeof(struct netdev_rx_queue), GFP_KERNEL);
if (!dev->_rx) {
ret = -ENOMEM;
goto out;
}
dev->_rx->first = dev->_rx;
atomic_set(&dev->_rx->count, 1);
dev->num_rx_queues = 1;
}
#endif
/* Init, if this function is available */
if (dev->netdev_ops->ndo_init) {
ret = dev->netdev_ops->ndo_init(dev);
if (ret) {
if (ret > 0)
ret = -EIO;
goto out;
}
}
ret = dev_get_valid_name(dev, dev->name, 0);
if (ret)
goto err_uninit;
dev->ifindex = dev_new_index(net);
if (dev->iflink == -1)
dev->iflink = dev->ifindex;
/* Fix illegal checksum combinations */
if ((dev->features & NETIF_F_HW_CSUM) &&
(dev->features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
printk(KERN_NOTICE "%s: mixed HW and IP checksum settings.\n",
dev->name);
dev->features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
}
if ((dev->features & NETIF_F_NO_CSUM) &&
(dev->features & (NETIF_F_HW_CSUM|NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
printk(KERN_NOTICE "%s: mixed no checksumming and other settings.\n",
dev->name);
dev->features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM|NETIF_F_HW_CSUM);
}
dev->features = netdev_fix_features(dev->features, dev->name);
/* Enable software GSO if SG is supported. */
if (dev->features & NETIF_F_SG)
dev->features |= NETIF_F_GSO;
ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
ret = notifier_to_errno(ret);
if (ret)
goto err_uninit;
ret = netdev_register_kobject(dev);
if (ret)
goto err_uninit;
dev->reg_state = NETREG_REGISTERED;
/*
* Default initial state at registry is that the
* device is present.
*/
set_bit(__LINK_STATE_PRESENT, &dev->state);
dev_init_scheduler(dev);
dev_hold(dev);
list_netdevice(dev);
/* Notify protocols, that a new device appeared. */
ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
ret = notifier_to_errno(ret);
if (ret) {
rollback_registered(dev);
dev->reg_state = NETREG_UNREGISTERED;
}
/*
* Prevent userspace races by waiting until the network
* device is fully setup before sending notifications.
*/
if (!dev->rtnl_link_ops ||
dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U);
out:
return ret;
err_uninit:
if (dev->netdev_ops->ndo_uninit)
dev->netdev_ops->ndo_uninit(dev);
goto out;
}
EXPORT_SYMBOL(register_netdevice);
/**
* init_dummy_netdev - init a dummy network device for NAPI
* @dev: device to init
*
* This takes a network device structure and initialize the minimum
* amount of fields so it can be used to schedule NAPI polls without
* registering a full blown interface. This is to be used by drivers
* that need to tie several hardware interfaces to a single NAPI
* poll scheduler due to HW limitations.
*/
int init_dummy_netdev(struct net_device *dev)
{
/* Clear everything. Note we don't initialize spinlocks
* are they aren't supposed to be taken by any of the
* NAPI code and this dummy netdev is supposed to be
* only ever used for NAPI polls
*/
memset(dev, 0, sizeof(struct net_device));
/* make sure we BUG if trying to hit standard
* register/unregister code path
*/
dev->reg_state = NETREG_DUMMY;
/* initialize the ref count */
atomic_set(&dev->refcnt, 1);
/* NAPI wants this */
INIT_LIST_HEAD(&dev->napi_list);
/* a dummy interface is started by default */
set_bit(__LINK_STATE_PRESENT, &dev->state);
set_bit(__LINK_STATE_START, &dev->state);
return 0;
}
EXPORT_SYMBOL_GPL(init_dummy_netdev);
/**
* register_netdev - register a network device
* @dev: device to register
*
* Take a completed network device structure and add it to the kernel
* interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
* chain. 0 is returned on success. A negative errno code is returned
* on a failure to set up the device, or if the name is a duplicate.
*
* This is a wrapper around register_netdevice that takes the rtnl semaphore
* and expands the device name if you passed a format string to
* alloc_netdev.
*/
int register_netdev(struct net_device *dev)
{
int err;
rtnl_lock();
/*
* If the name is a format string the caller wants us to do a
* name allocation.
*/
if (strchr(dev->name, '%')) {
err = dev_alloc_name(dev, dev->name);
if (err < 0)
goto out;
}
err = register_netdevice(dev);
out:
rtnl_unlock();
return err;
}
EXPORT_SYMBOL(register_netdev);
/*
* netdev_wait_allrefs - wait until all references are gone.
*
* This is called when unregistering network devices.
*
* Any protocol or device that holds a reference should register
* for netdevice notification, and cleanup and put back the
* reference if they receive an UNREGISTER event.
* We can get stuck here if buggy protocols don't correctly
* call dev_put.
*/
static void netdev_wait_allrefs(struct net_device *dev)
{
unsigned long rebroadcast_time, warning_time;
linkwatch_forget_dev(dev);
rebroadcast_time = warning_time = jiffies;
while (atomic_read(&dev->refcnt) != 0) {
if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
rtnl_lock();
/* Rebroadcast unregister notification */
call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
/* don't resend NETDEV_UNREGISTER_BATCH, _BATCH users
* should have already handle it the first time */
if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
&dev->state)) {
/* We must not have linkwatch events
* pending on unregister. If this
* happens, we simply run the queue
* unscheduled, resulting in a noop
* for this device.
*/
linkwatch_run_queue();
}
__rtnl_unlock();
rebroadcast_time = jiffies;
}
msleep(250);
if (time_after(jiffies, warning_time + 10 * HZ)) {
printk(KERN_EMERG "unregister_netdevice: "
"waiting for %s to become free. Usage "
"count = %d\n",
dev->name, atomic_read(&dev->refcnt));
warning_time = jiffies;
}
}
}
/* The sequence is:
*
* rtnl_lock();
* ...
* register_netdevice(x1);
* register_netdevice(x2);
* ...
* unregister_netdevice(y1);
* unregister_netdevice(y2);
* ...
* rtnl_unlock();
* free_netdev(y1);
* free_netdev(y2);
*
* We are invoked by rtnl_unlock().
* This allows us to deal with problems:
* 1) We can delete sysfs objects which invoke hotplug
* without deadlocking with linkwatch via keventd.
* 2) Since we run with the RTNL semaphore not held, we can sleep
* safely in order to wait for the netdev refcnt to drop to zero.
*
* We must not return until all unregister events added during
* the interval the lock was held have been completed.
*/
void netdev_run_todo(void)
{
struct list_head list;
/* Snapshot list, allow later requests */
list_replace_init(&net_todo_list, &list);
__rtnl_unlock();
while (!list_empty(&list)) {
struct net_device *dev
= list_first_entry(&list, struct net_device, todo_list);
list_del(&dev->todo_list);
if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
printk(KERN_ERR "network todo '%s' but state %d\n",
dev->name, dev->reg_state);
dump_stack();
continue;
}
dev->reg_state = NETREG_UNREGISTERED;
on_each_cpu(flush_backlog, dev, 1);
netdev_wait_allrefs(dev);
/* paranoia */
BUG_ON(atomic_read(&dev->refcnt));
WARN_ON(dev->ip_ptr);
WARN_ON(dev->ip6_ptr);
WARN_ON(dev->dn_ptr);
if (dev->destructor)
dev->destructor(dev);
/* Free network device */
kobject_put(&dev->dev.kobj);
}
}
/**
* dev_txq_stats_fold - fold tx_queues stats
* @dev: device to get statistics from
* @stats: struct net_device_stats to hold results
*/
void dev_txq_stats_fold(const struct net_device *dev,
struct net_device_stats *stats)
{
unsigned long tx_bytes = 0, tx_packets = 0, tx_dropped = 0;
unsigned int i;
struct netdev_queue *txq;
for (i = 0; i < dev->num_tx_queues; i++) {
txq = netdev_get_tx_queue(dev, i);
tx_bytes += txq->tx_bytes;
tx_packets += txq->tx_packets;
tx_dropped += txq->tx_dropped;
}
if (tx_bytes || tx_packets || tx_dropped) {
stats->tx_bytes = tx_bytes;
stats->tx_packets = tx_packets;
stats->tx_dropped = tx_dropped;
}
}
EXPORT_SYMBOL(dev_txq_stats_fold);
/**
* dev_get_stats - get network device statistics
* @dev: device to get statistics from
*
* Get network statistics from device. The device driver may provide
* its own method by setting dev->netdev_ops->get_stats64 or
* dev->netdev_ops->get_stats; otherwise the internal statistics
* structure is used.
*/
const struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev)
{
const struct net_device_ops *ops = dev->netdev_ops;
if (ops->ndo_get_stats64)
return ops->ndo_get_stats64(dev);
if (ops->ndo_get_stats)
return (struct rtnl_link_stats64 *)ops->ndo_get_stats(dev);
dev_txq_stats_fold(dev, &dev->stats);
return &dev->stats64;
}
EXPORT_SYMBOL(dev_get_stats);
static void netdev_init_one_queue(struct net_device *dev,
struct netdev_queue *queue,
void *_unused)
{
queue->dev = dev;
}
static void netdev_init_queues(struct net_device *dev)
{
netdev_init_one_queue(dev, &dev->rx_queue, NULL);
netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
spin_lock_init(&dev->tx_global_lock);
}
/**
* alloc_netdev_mq - allocate network device
* @sizeof_priv: size of private data to allocate space for
* @name: device name format string
* @setup: callback to initialize device
* @queue_count: the number of subqueues to allocate
*
* Allocates a struct net_device with private data area for driver use
* and performs basic initialization. Also allocates subquue structs
* for each queue on the device at the end of the netdevice.
*/
struct net_device *alloc_netdev_mq(int sizeof_priv, const char *name,
void (*setup)(struct net_device *), unsigned int queue_count)
{
struct netdev_queue *tx;
struct net_device *dev;
size_t alloc_size;
struct net_device *p;
#ifdef CONFIG_RPS
struct netdev_rx_queue *rx;
int i;
#endif
BUG_ON(strlen(name) >= sizeof(dev->name));
alloc_size = sizeof(struct net_device);
if (sizeof_priv) {
/* ensure 32-byte alignment of private area */
alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
alloc_size += sizeof_priv;
}
/* ensure 32-byte alignment of whole construct */
alloc_size += NETDEV_ALIGN - 1;
p = kzalloc(alloc_size, GFP_KERNEL);
if (!p) {
printk(KERN_ERR "alloc_netdev: Unable to allocate device.\n");
return NULL;
}
tx = kcalloc(queue_count, sizeof(struct netdev_queue), GFP_KERNEL);
if (!tx) {
printk(KERN_ERR "alloc_netdev: Unable to allocate "
"tx qdiscs.\n");
goto free_p;
}
#ifdef CONFIG_RPS
rx = kcalloc(queue_count, sizeof(struct netdev_rx_queue), GFP_KERNEL);
if (!rx) {
printk(KERN_ERR "alloc_netdev: Unable to allocate "
"rx queues.\n");
goto free_tx;
}
atomic_set(&rx->count, queue_count);
/*
* Set a pointer to first element in the array which holds the
* reference count.
*/
for (i = 0; i < queue_count; i++)
rx[i].first = rx;
#endif
dev = PTR_ALIGN(p, NETDEV_ALIGN);
dev->padded = (char *)dev - (char *)p;
if (dev_addr_init(dev))
goto free_rx;
dev_mc_init(dev);
dev_uc_init(dev);
dev_net_set(dev, &init_net);
dev->_tx = tx;
dev->num_tx_queues = queue_count;
dev->real_num_tx_queues = queue_count;
#ifdef CONFIG_RPS
dev->_rx = rx;
dev->num_rx_queues = queue_count;
#endif
dev->gso_max_size = GSO_MAX_SIZE;
netdev_init_queues(dev);
INIT_LIST_HEAD(&dev->ethtool_ntuple_list.list);
dev->ethtool_ntuple_list.count = 0;
INIT_LIST_HEAD(&dev->napi_list);
INIT_LIST_HEAD(&dev->unreg_list);
INIT_LIST_HEAD(&dev->link_watch_list);
dev->priv_flags = IFF_XMIT_DST_RELEASE;
setup(dev);
strcpy(dev->name, name);
return dev;
free_rx:
#ifdef CONFIG_RPS
kfree(rx);
free_tx:
#endif
kfree(tx);
free_p:
kfree(p);
return NULL;
}
EXPORT_SYMBOL(alloc_netdev_mq);
/**
* free_netdev - free network device
* @dev: device
*
* This function does the last stage of destroying an allocated device
* interface. The reference to the device object is released.
* If this is the last reference then it will be freed.
*/
void free_netdev(struct net_device *dev)
{
struct napi_struct *p, *n;
release_net(dev_net(dev));
kfree(dev->_tx);
/* Flush device addresses */
dev_addr_flush(dev);
/* Clear ethtool n-tuple list */
ethtool_ntuple_flush(dev);
list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
netif_napi_del(p);
/* Compatibility with error handling in drivers */
if (dev->reg_state == NETREG_UNINITIALIZED) {
kfree((char *)dev - dev->padded);
return;
}
BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
dev->reg_state = NETREG_RELEASED;
/* will free via device release */
put_device(&dev->dev);
}
EXPORT_SYMBOL(free_netdev);
/**
* synchronize_net - Synchronize with packet receive processing
*
* Wait for packets currently being received to be done.
* Does not block later packets from starting.
*/
void synchronize_net(void)
{
might_sleep();
synchronize_rcu();
}
EXPORT_SYMBOL(synchronize_net);
/**
* unregister_netdevice_queue - remove device from the kernel
* @dev: device
* @head: list
*
* This function shuts down a device interface and removes it
* from the kernel tables.
* If head not NULL, device is queued to be unregistered later.
*
* Callers must hold the rtnl semaphore. You may want
* unregister_netdev() instead of this.
*/
void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
{
ASSERT_RTNL();
if (head) {
list_move_tail(&dev->unreg_list, head);
} else {
rollback_registered(dev);
/* Finish processing unregister after unlock */
net_set_todo(dev);
}
}
EXPORT_SYMBOL(unregister_netdevice_queue);
/**
* unregister_netdevice_many - unregister many devices
* @head: list of devices
*/
void unregister_netdevice_many(struct list_head *head)
{
struct net_device *dev;
if (!list_empty(head)) {
rollback_registered_many(head);
list_for_each_entry(dev, head, unreg_list)
net_set_todo(dev);
}
}
EXPORT_SYMBOL(unregister_netdevice_many);
/**
* unregister_netdev - remove device from the kernel
* @dev: device
*
* This function shuts down a device interface and removes it
* from the kernel tables.
*
* This is just a wrapper for unregister_netdevice that takes
* the rtnl semaphore. In general you want to use this and not
* unregister_netdevice.
*/
void unregister_netdev(struct net_device *dev)
{
rtnl_lock();
unregister_netdevice(dev);
rtnl_unlock();
}
EXPORT_SYMBOL(unregister_netdev);
/**
* dev_change_net_namespace - move device to different nethost namespace
* @dev: device
* @net: network namespace
* @pat: If not NULL name pattern to try if the current device name
* is already taken in the destination network namespace.
*
* This function shuts down a device interface and moves it
* to a new network namespace. On success 0 is returned, on
* a failure a netagive errno code is returned.
*
* Callers must hold the rtnl semaphore.
*/
int dev_change_net_namespace(struct net_device *dev, struct net *net, const char *pat)
{
int err;
ASSERT_RTNL();
/* Don't allow namespace local devices to be moved. */
err = -EINVAL;
if (dev->features & NETIF_F_NETNS_LOCAL)
goto out;
/* Ensure the device has been registrered */
err = -EINVAL;
if (dev->reg_state != NETREG_REGISTERED)
goto out;
/* Get out if there is nothing todo */
err = 0;
if (net_eq(dev_net(dev), net))
goto out;
/* Pick the destination device name, and ensure
* we can use it in the destination network namespace.
*/
err = -EEXIST;
if (__dev_get_by_name(net, dev->name)) {
/* We get here if we can't use the current device name */
if (!pat)
goto out;
if (dev_get_valid_name(dev, pat, 1))
goto out;
}
/*
* And now a mini version of register_netdevice unregister_netdevice.
*/
/* If device is running close it first. */
dev_close(dev);
/* And unlink it from device chain */
err = -ENODEV;
unlist_netdevice(dev);
synchronize_net();
/* Shutdown queueing discipline. */
dev_shutdown(dev);
/* Notify protocols, that we are about to destroy
this device. They should clean all the things.
*/
call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
call_netdevice_notifiers(NETDEV_UNREGISTER_BATCH, dev);
/*
* Flush the unicast and multicast chains
*/
dev_uc_flush(dev);
dev_mc_flush(dev);
/* Actually switch the network namespace */
dev_net_set(dev, net);
/* If there is an ifindex conflict assign a new one */
if (__dev_get_by_index(net, dev->ifindex)) {
int iflink = (dev->iflink == dev->ifindex);
dev->ifindex = dev_new_index(net);
if (iflink)
dev->iflink = dev->ifindex;
}
/* Fixup kobjects */
err = device_rename(&dev->dev, dev->name);
WARN_ON(err);
/* Add the device back in the hashes */
list_netdevice(dev);
/* Notify protocols, that a new device appeared. */
call_netdevice_notifiers(NETDEV_REGISTER, dev);
/*
* Prevent userspace races by waiting until the network
* device is fully setup before sending notifications.
*/
rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U);
synchronize_net();
err = 0;
out:
return err;
}
EXPORT_SYMBOL_GPL(dev_change_net_namespace);
static int dev_cpu_callback(struct notifier_block *nfb,
unsigned long action,
void *ocpu)
{
struct sk_buff **list_skb;
struct sk_buff *skb;
unsigned int cpu, oldcpu = (unsigned long)ocpu;
struct softnet_data *sd, *oldsd;
if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
return NOTIFY_OK;
local_irq_disable();
cpu = smp_processor_id();
sd = &per_cpu(softnet_data, cpu);
oldsd = &per_cpu(softnet_data, oldcpu);
/* Find end of our completion_queue. */
list_skb = &sd->completion_queue;
while (*list_skb)
list_skb = &(*list_skb)->next;
/* Append completion queue from offline CPU. */
*list_skb = oldsd->completion_queue;
oldsd->completion_queue = NULL;
/* Append output queue from offline CPU. */
if (oldsd->output_queue) {
*sd->output_queue_tailp = oldsd->output_queue;
sd->output_queue_tailp = oldsd->output_queue_tailp;
oldsd->output_queue = NULL;
oldsd->output_queue_tailp = &oldsd->output_queue;
}
raise_softirq_irqoff(NET_TX_SOFTIRQ);
local_irq_enable();
/* Process offline CPU's input_pkt_queue */
while ((skb = __skb_dequeue(&oldsd->process_queue))) {
netif_rx(skb);
input_queue_head_incr(oldsd);
}
while ((skb = __skb_dequeue(&oldsd->input_pkt_queue))) {
netif_rx(skb);
input_queue_head_incr(oldsd);
}
return NOTIFY_OK;
}
/**
* netdev_increment_features - increment feature set by one
* @all: current feature set
* @one: new feature set
* @mask: mask feature set
*
* Computes a new feature set after adding a device with feature set
* @one to the master device with current feature set @all. Will not
* enable anything that is off in @mask. Returns the new feature set.
*/
unsigned long netdev_increment_features(unsigned long all, unsigned long one,
unsigned long mask)
{
/* If device needs checksumming, downgrade to it. */
if (all & NETIF_F_NO_CSUM && !(one & NETIF_F_NO_CSUM))
all ^= NETIF_F_NO_CSUM | (one & NETIF_F_ALL_CSUM);
else if (mask & NETIF_F_ALL_CSUM) {
/* If one device supports v4/v6 checksumming, set for all. */
if (one & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM) &&
!(all & NETIF_F_GEN_CSUM)) {
all &= ~NETIF_F_ALL_CSUM;
all |= one & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM);
}
/* If one device supports hw checksumming, set for all. */
if (one & NETIF_F_GEN_CSUM && !(all & NETIF_F_GEN_CSUM)) {
all &= ~NETIF_F_ALL_CSUM;
all |= NETIF_F_HW_CSUM;
}
}
one |= NETIF_F_ALL_CSUM;
one |= all & NETIF_F_ONE_FOR_ALL;
all &= one | NETIF_F_LLTX | NETIF_F_GSO | NETIF_F_UFO;
all |= one & mask & NETIF_F_ONE_FOR_ALL;
return all;
}
EXPORT_SYMBOL(netdev_increment_features);
static struct hlist_head *netdev_create_hash(void)
{
int i;
struct hlist_head *hash;
hash = kmalloc(sizeof(*hash) * NETDEV_HASHENTRIES, GFP_KERNEL);
if (hash != NULL)
for (i = 0; i < NETDEV_HASHENTRIES; i++)
INIT_HLIST_HEAD(&hash[i]);
return hash;
}
/* Initialize per network namespace state */
static int __net_init netdev_init(struct net *net)
{
INIT_LIST_HEAD(&net->dev_base_head);
net->dev_name_head = netdev_create_hash();
if (net->dev_name_head == NULL)
goto err_name;
net->dev_index_head = netdev_create_hash();
if (net->dev_index_head == NULL)
goto err_idx;
return 0;
err_idx:
kfree(net->dev_name_head);
err_name:
return -ENOMEM;
}
/**
* netdev_drivername - network driver for the device
* @dev: network device
* @buffer: buffer for resulting name
* @len: size of buffer
*
* Determine network driver for device.
*/
char *netdev_drivername(const struct net_device *dev, char *buffer, int len)
{
const struct device_driver *driver;
const struct device *parent;
if (len <= 0 || !buffer)
return buffer;
buffer[0] = 0;
parent = dev->dev.parent;
if (!parent)
return buffer;
driver = parent->driver;
if (driver && driver->name)
strlcpy(buffer, driver->name, len);
return buffer;
}
static int __netdev_printk(const char *level, const struct net_device *dev,
struct va_format *vaf)
{
int r;
if (dev && dev->dev.parent)
r = dev_printk(level, dev->dev.parent, "%s: %pV",
netdev_name(dev), vaf);
else if (dev)
r = printk("%s%s: %pV", level, netdev_name(dev), vaf);
else
r = printk("%s(NULL net_device): %pV", level, vaf);
return r;
}
int netdev_printk(const char *level, const struct net_device *dev,
const char *format, ...)
{
struct va_format vaf;
va_list args;
int r;
va_start(args, format);
vaf.fmt = format;
vaf.va = &args;
r = __netdev_printk(level, dev, &vaf);
va_end(args);
return r;
}
EXPORT_SYMBOL(netdev_printk);
#define define_netdev_printk_level(func, level) \
int func(const struct net_device *dev, const char *fmt, ...) \
{ \
int r; \
struct va_format vaf; \
va_list args; \
\
va_start(args, fmt); \
\
vaf.fmt = fmt; \
vaf.va = &args; \
\
r = __netdev_printk(level, dev, &vaf); \
va_end(args); \
\
return r; \
} \
EXPORT_SYMBOL(func);
define_netdev_printk_level(netdev_emerg, KERN_EMERG);
define_netdev_printk_level(netdev_alert, KERN_ALERT);
define_netdev_printk_level(netdev_crit, KERN_CRIT);
define_netdev_printk_level(netdev_err, KERN_ERR);
define_netdev_printk_level(netdev_warn, KERN_WARNING);
define_netdev_printk_level(netdev_notice, KERN_NOTICE);
define_netdev_printk_level(netdev_info, KERN_INFO);
static void __net_exit netdev_exit(struct net *net)
{
kfree(net->dev_name_head);
kfree(net->dev_index_head);
}
static struct pernet_operations __net_initdata netdev_net_ops = {
.init = netdev_init,
.exit = netdev_exit,
};
static void __net_exit default_device_exit(struct net *net)
{
struct net_device *dev, *aux;
/*
* Push all migratable network devices back to the
* initial network namespace
*/
rtnl_lock();
for_each_netdev_safe(net, dev, aux) {
int err;
char fb_name[IFNAMSIZ];
/* Ignore unmoveable devices (i.e. loopback) */
if (dev->features & NETIF_F_NETNS_LOCAL)
continue;
/* Leave virtual devices for the generic cleanup */
if (dev->rtnl_link_ops)
continue;
/* Push remaing network devices to init_net */
snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
err = dev_change_net_namespace(dev, &init_net, fb_name);
if (err) {
printk(KERN_EMERG "%s: failed to move %s to init_net: %d\n",
__func__, dev->name, err);
BUG();
}
}
rtnl_unlock();
}
static void __net_exit default_device_exit_batch(struct list_head *net_list)
{
/* At exit all network devices most be removed from a network
* namespace. Do this in the reverse order of registeration.
* Do this across as many network namespaces as possible to
* improve batching efficiency.
*/
struct net_device *dev;
struct net *net;
LIST_HEAD(dev_kill_list);
rtnl_lock();
list_for_each_entry(net, net_list, exit_list) {
for_each_netdev_reverse(net, dev) {
if (dev->rtnl_link_ops)
dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
else
unregister_netdevice_queue(dev, &dev_kill_list);
}
}
unregister_netdevice_many(&dev_kill_list);
rtnl_unlock();
}
static struct pernet_operations __net_initdata default_device_ops = {
.exit = default_device_exit,
.exit_batch = default_device_exit_batch,
};
/*
* Initialize the DEV module. At boot time this walks the device list and
* unhooks any devices that fail to initialise (normally hardware not
* present) and leaves us with a valid list of present and active devices.
*
*/
/*
* This is called single threaded during boot, so no need
* to take the rtnl semaphore.
*/
static int __init net_dev_init(void)
{
int i, rc = -ENOMEM;
BUG_ON(!dev_boot_phase);
if (dev_proc_init())
goto out;
if (netdev_kobject_init())
goto out;
INIT_LIST_HEAD(&ptype_all);
for (i = 0; i < PTYPE_HASH_SIZE; i++)
INIT_LIST_HEAD(&ptype_base[i]);
if (register_pernet_subsys(&netdev_net_ops))
goto out;
/*
* Initialise the packet receive queues.
*/
for_each_possible_cpu(i) {
struct softnet_data *sd = &per_cpu(softnet_data, i);
memset(sd, 0, sizeof(*sd));
skb_queue_head_init(&sd->input_pkt_queue);
skb_queue_head_init(&sd->process_queue);
sd->completion_queue = NULL;
INIT_LIST_HEAD(&sd->poll_list);
sd->output_queue = NULL;
sd->output_queue_tailp = &sd->output_queue;
#ifdef CONFIG_RPS
sd->csd.func = rps_trigger_softirq;
sd->csd.info = sd;
sd->csd.flags = 0;
sd->cpu = i;
#endif
sd->backlog.poll = process_backlog;
sd->backlog.weight = weight_p;
sd->backlog.gro_list = NULL;
sd->backlog.gro_count = 0;
}
dev_boot_phase = 0;
/* The loopback device is special if any other network devices
* is present in a network namespace the loopback device must
* be present. Since we now dynamically allocate and free the
* loopback device ensure this invariant is maintained by
* keeping the loopback device as the first device on the
* list of network devices. Ensuring the loopback devices
* is the first device that appears and the last network device
* that disappears.
*/
if (register_pernet_device(&loopback_net_ops))
goto out;
if (register_pernet_device(&default_device_ops))
goto out;
open_softirq(NET_TX_SOFTIRQ, net_tx_action);
open_softirq(NET_RX_SOFTIRQ, net_rx_action);
hotcpu_notifier(dev_cpu_callback, 0);
dst_init();
dev_mcast_init();
rc = 0;
out:
return rc;
}
subsys_initcall(net_dev_init);
static int __init initialize_hashrnd(void)
{
get_random_bytes(&hashrnd, sizeof(hashrnd));
return 0;
}
late_initcall_sync(initialize_hashrnd);
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2143_1 |
crossvul-cpp_data_good_346_5 | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Initially written by David Mattes <david.mattes@boeing.com> */
/* Support for multiple key containers by Lukas Wunner <lukas@wunner.de> */
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "internal.h"
#include "pkcs15.h"
#define MANU_ID "Gemplus"
#define APPLET_NAME "GemSAFE V1"
#define DRIVER_SERIAL_NUMBER "v0.9"
#define GEMSAFE_APP_PATH "3F001600"
#define GEMSAFE_PATH "3F0016000004"
/* Apparently, the Applet max read "quanta" is 248 bytes
* Gemalto ClassicClient reads files in chunks of 238 bytes
*/
#define GEMSAFE_READ_QUANTUM 248
#define GEMSAFE_MAX_OBJLEN 28672
int sc_pkcs15emu_gemsafeV1_init_ex(sc_pkcs15_card_t *, struct sc_aid *,sc_pkcs15emu_opt_t *);
static int
sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card,
int type, int authority,
const sc_path_t *path,
const sc_pkcs15_id_t *id,
const char *label, int obj_flags);
static int
sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id, const char *label,
const sc_path_t *path, int ref, int type,
unsigned int min_length,
unsigned int max_length,
int flags, int tries_left, const char pad_char, int obj_flags);
static int
sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id,
const char *label,
int type, unsigned int modulus_length, int usage,
const sc_path_t *path, int ref,
const sc_pkcs15_id_t *auth_id, int obj_flags);
typedef struct cdata_st {
char *label;
int authority;
const char *path;
size_t index;
size_t count;
const char *id;
int obj_flags;
} cdata;
const unsigned int gemsafe_cert_max = 12;
cdata gemsafe_cert[] = {
{"DS certificate #1", 0, GEMSAFE_PATH, 0, 0, "45", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #2", 0, GEMSAFE_PATH, 0, 0, "46", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #3", 0, GEMSAFE_PATH, 0, 0, "47", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #4", 0, GEMSAFE_PATH, 0, 0, "48", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #5", 0, GEMSAFE_PATH, 0, 0, "49", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #6", 0, GEMSAFE_PATH, 0, 0, "50", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #7", 0, GEMSAFE_PATH, 0, 0, "51", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #8", 0, GEMSAFE_PATH, 0, 0, "52", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #9", 0, GEMSAFE_PATH, 0, 0, "53", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #10", 0, GEMSAFE_PATH, 0, 0, "54", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #11", 0, GEMSAFE_PATH, 0, 0, "55", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #12", 0, GEMSAFE_PATH, 0, 0, "56", SC_PKCS15_CO_FLAG_MODIFIABLE},
};
typedef struct pdata_st {
const u8 atr[SC_MAX_ATR_SIZE];
const size_t atr_len;
const char *id;
const char *label;
const char *path;
const int ref;
const int type;
const unsigned int maxlen;
const unsigned int minlen;
const int flags;
const int tries_left;
const char pad_char;
const int obj_flags;
} pindata;
const unsigned int gemsafe_pin_max = 2;
const pindata gemsafe_pin[] = {
/* ATR-specific PIN policies, first match found is used: */
{ {0x3B, 0x7D, 0x96, 0x00, 0x00, 0x80, 0x31, 0x80, 0x65,
0xB0, 0x83, 0x11, 0x48, 0xC8, 0x83, 0x00, 0x90, 0x00}, 18,
"01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_ASCII_NUMERIC,
8, 4, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL,
3, 0x00, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE },
/* default PIN policy comes last: */
{ { 0 }, 0,
"01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_BCD,
16, 6, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL,
3, 0xFF, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE }
};
typedef struct prdata_st {
const char *id;
char *label;
unsigned int modulus_len;
int usage;
const char *path;
int ref;
const char *auth_id;
int obj_flags;
} prdata;
#define USAGE_NONREP SC_PKCS15_PRKEY_USAGE_NONREPUDIATION
#define USAGE_KE SC_PKCS15_PRKEY_USAGE_ENCRYPT | \
SC_PKCS15_PRKEY_USAGE_DECRYPT | \
SC_PKCS15_PRKEY_USAGE_WRAP | \
SC_PKCS15_PRKEY_USAGE_UNWRAP
#define USAGE_AUT SC_PKCS15_PRKEY_USAGE_ENCRYPT | \
SC_PKCS15_PRKEY_USAGE_DECRYPT | \
SC_PKCS15_PRKEY_USAGE_WRAP | \
SC_PKCS15_PRKEY_USAGE_UNWRAP | \
SC_PKCS15_PRKEY_USAGE_SIGN
prdata gemsafe_prkeys[] = {
{ "45", "DS key #1", 1024, USAGE_AUT, GEMSAFE_PATH, 0x03, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "46", "DS key #2", 1024, USAGE_AUT, GEMSAFE_PATH, 0x04, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "47", "DS key #3", 1024, USAGE_AUT, GEMSAFE_PATH, 0x05, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "48", "DS key #4", 1024, USAGE_AUT, GEMSAFE_PATH, 0x06, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "49", "DS key #5", 1024, USAGE_AUT, GEMSAFE_PATH, 0x07, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "50", "DS key #6", 1024, USAGE_AUT, GEMSAFE_PATH, 0x08, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "51", "DS key #7", 1024, USAGE_AUT, GEMSAFE_PATH, 0x09, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "52", "DS key #8", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0a, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "53", "DS key #9", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0b, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "54", "DS key #10", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0c, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "55", "DS key #11", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0d, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "56", "DS key #12", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0e, "01", SC_PKCS15_CO_FLAG_PRIVATE},
};
static int gemsafe_get_cert_len(sc_card_t *card)
{
int r;
u8 ibuf[GEMSAFE_MAX_OBJLEN];
u8 *iptr;
struct sc_path path;
struct sc_file *file;
size_t objlen, certlen;
unsigned int ind, i=0;
sc_format_path(GEMSAFE_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* Initial read */
r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0);
if (r < 0)
return SC_ERROR_INTERNAL;
/* Actual stored object size is encoded in first 2 bytes
* (allocated EF space is much greater!)
*/
objlen = (((size_t) ibuf[0]) << 8) | ibuf[1];
sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) {
sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
return SC_ERROR_INTERNAL;
}
/* It looks like the first thing in the block is a table of
* which keys are allocated. The table is small and is in the
* first 248 bytes. Example for a card with 10 key containers:
* 01 f0 00 03 03 b0 00 03 <= 1st key unallocated
* 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated
* 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated
* 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated
* 01 f0 00 07 03 b0 00 07 <= 5th key unallocated
* ...
* 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated
* For allocated keys, the fourth byte seems to indicate the
* default key and the fifth byte indicates the key_ref of
* the private key.
*/
ind = 2; /* skip length */
while (ibuf[ind] == 0x01 && i < gemsafe_cert_max) {
if (ibuf[ind+1] == 0xFE) {
gemsafe_prkeys[i].ref = ibuf[ind+4];
sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d",
i+1, gemsafe_prkeys[i].ref);
ind += 9;
}
else {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
sc_log(card->ctx, "Key container %d is unallocated", i+1);
ind += 8;
}
i++;
}
/* Delete additional key containers from the data structures if
* this card can't accommodate them.
*/
for (; i < gemsafe_cert_max; i++) {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
/* Read entire file, then dissect in memory.
* Gemalto ClassicClient seems to do it the same way.
*/
iptr = ibuf + GEMSAFE_READ_QUANTUM;
while ((size_t)(iptr - ibuf) < objlen) {
r = sc_read_binary(card, iptr - ibuf, iptr,
MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0);
if (r < 0) {
sc_log(card->ctx, "Could not read cert object");
return SC_ERROR_INTERNAL;
}
iptr += GEMSAFE_READ_QUANTUM;
}
/* Search buffer for certificates, they start with 0x3082. */
i = 0;
while (ind < objlen - 1) {
if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) {
/* Find next allocated key container */
while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL)
i++;
if (i == gemsafe_cert_max) {
sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind);
return SC_SUCCESS;
}
/* DER cert len is encoded this way */
if (ind+3 >= sizeof ibuf)
return SC_ERROR_INVALID_DATA;
certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4;
sc_log(card->ctx,
"Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u",
i+1, ind, certlen);
gemsafe_cert[i].index = ind;
gemsafe_cert[i].count = certlen;
ind += certlen;
i++;
} else
ind++;
}
/* Delete additional key containers from the data structures if
* they're missing on the card.
*/
for (; i < gemsafe_cert_max; i++) {
if (gemsafe_cert[i].label) {
sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1);
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
}
return SC_SUCCESS;
}
static int gemsafe_detect_card( sc_pkcs15_card_t *p15card)
{
if (strcmp(p15card->card->name, "GemSAFE V1"))
return SC_ERROR_WRONG_CARD;
return SC_SUCCESS;
}
static int sc_pkcs15emu_gemsafeV1_init( sc_pkcs15_card_t *p15card)
{
int r;
unsigned int i;
struct sc_path path;
struct sc_file *file = NULL;
struct sc_card *card = p15card->card;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_log(p15card->card->ctx, "Setting pkcs15 parameters");
if (p15card->tokeninfo->label)
free(p15card->tokeninfo->label);
p15card->tokeninfo->label = malloc(strlen(APPLET_NAME) + 1);
if (!p15card->tokeninfo->label)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->label, APPLET_NAME);
if (p15card->tokeninfo->serial_number)
free(p15card->tokeninfo->serial_number);
p15card->tokeninfo->serial_number = malloc(strlen(DRIVER_SERIAL_NUMBER) + 1);
if (!p15card->tokeninfo->serial_number)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->serial_number, DRIVER_SERIAL_NUMBER);
/* the GemSAFE applet version number */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0xdf, 0x03);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
/* Manual says Le=0x05, but should be 0x08 to return full version number */
apdu.le = 0x08;
apdu.lc = 0;
apdu.datalen = 0;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00)
return SC_ERROR_INTERNAL;
if (r != SC_SUCCESS)
return SC_ERROR_INTERNAL;
/* the manufacturer ID, in this case GemPlus */
if (p15card->tokeninfo->manufacturer_id)
free(p15card->tokeninfo->manufacturer_id);
p15card->tokeninfo->manufacturer_id = malloc(strlen(MANU_ID) + 1);
if (!p15card->tokeninfo->manufacturer_id)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->manufacturer_id, MANU_ID);
/* determine allocated key containers and length of certificates */
r = gemsafe_get_cert_len(card);
if (r != SC_SUCCESS)
return SC_ERROR_INTERNAL;
/* set certs */
sc_log(p15card->card->ctx, "Setting certificates");
for (i = 0; i < gemsafe_cert_max; i++) {
struct sc_pkcs15_id p15Id;
struct sc_path path;
if (gemsafe_cert[i].label == NULL)
continue;
sc_format_path(gemsafe_cert[i].path, &path);
sc_pkcs15_format_id(gemsafe_cert[i].id, &p15Id);
path.index = gemsafe_cert[i].index;
path.count = gemsafe_cert[i].count;
sc_pkcs15emu_add_cert(p15card, SC_PKCS15_TYPE_CERT_X509,
gemsafe_cert[i].authority, &path, &p15Id,
gemsafe_cert[i].label, gemsafe_cert[i].obj_flags);
}
/* set gemsafe_pin */
sc_log(p15card->card->ctx, "Setting PIN");
for (i=0; i < gemsafe_pin_max; i++) {
struct sc_pkcs15_id p15Id;
struct sc_path path;
sc_pkcs15_format_id(gemsafe_pin[i].id, &p15Id);
sc_format_path(gemsafe_pin[i].path, &path);
if (gemsafe_pin[i].atr_len == 0 ||
(gemsafe_pin[i].atr_len == p15card->card->atr.len &&
memcmp(p15card->card->atr.value, gemsafe_pin[i].atr,
p15card->card->atr.len) == 0)) {
sc_pkcs15emu_add_pin(p15card, &p15Id, gemsafe_pin[i].label,
&path, gemsafe_pin[i].ref, gemsafe_pin[i].type,
gemsafe_pin[i].minlen, gemsafe_pin[i].maxlen,
gemsafe_pin[i].flags, gemsafe_pin[i].tries_left,
gemsafe_pin[i].pad_char, gemsafe_pin[i].obj_flags);
break;
}
};
/* set private keys */
sc_log(p15card->card->ctx, "Setting private keys");
for (i = 0; i < gemsafe_cert_max; i++) {
struct sc_pkcs15_id p15Id, authId, *pauthId;
struct sc_path path;
int key_ref = 0x03;
if (gemsafe_prkeys[i].label == NULL)
continue;
sc_pkcs15_format_id(gemsafe_prkeys[i].id, &p15Id);
if (gemsafe_prkeys[i].auth_id) {
sc_pkcs15_format_id(gemsafe_prkeys[i].auth_id, &authId);
pauthId = &authId;
} else
pauthId = NULL;
sc_format_path(gemsafe_prkeys[i].path, &path);
/*
* The key ref may be different for different sites;
* by adding flags=n where the low order 4 bits can be
* the key ref we can force it.
*/
if ( p15card->card->flags & 0x0F) {
key_ref = p15card->card->flags & 0x0F;
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Overriding key_ref %d with %d\n",
gemsafe_prkeys[i].ref, key_ref);
} else
key_ref = gemsafe_prkeys[i].ref;
sc_pkcs15emu_add_prkey(p15card, &p15Id, gemsafe_prkeys[i].label,
SC_PKCS15_TYPE_PRKEY_RSA,
gemsafe_prkeys[i].modulus_len, gemsafe_prkeys[i].usage,
&path, key_ref, pauthId,
gemsafe_prkeys[i].obj_flags);
}
/* select the application DF */
sc_log(p15card->card->ctx, "Selecting application DF");
sc_format_path(GEMSAFE_APP_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* set the application DF */
if (p15card->file_app)
free(p15card->file_app);
p15card->file_app = file;
return SC_SUCCESS;
}
int sc_pkcs15emu_gemsafeV1_init_ex( sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)
return sc_pkcs15emu_gemsafeV1_init(p15card);
else {
int r = gemsafe_detect_card(p15card);
if (r)
return SC_ERROR_WRONG_CARD;
return sc_pkcs15emu_gemsafeV1_init(p15card);
}
}
static sc_pkcs15_df_t *
sc_pkcs15emu_get_df(sc_pkcs15_card_t *p15card, unsigned int type)
{
sc_pkcs15_df_t *df;
sc_file_t *file;
int created = 0;
while (1) {
for (df = p15card->df_list; df; df = df->next) {
if (df->type == type) {
if (created)
df->enumerated = 1;
return df;
}
}
assert(created == 0);
file = sc_file_new();
if (!file)
return NULL;
sc_format_path("11001101", &file->path);
sc_pkcs15_add_df(p15card, type, &file->path);
sc_file_free(file);
created++;
}
}
static int
sc_pkcs15emu_add_object(sc_pkcs15_card_t *p15card, int type,
const char *label, void *data,
const sc_pkcs15_id_t *auth_id, int obj_flags)
{
sc_pkcs15_object_t *obj;
int df_type;
obj = calloc(1, sizeof(*obj));
obj->type = type;
obj->data = data;
if (label)
strncpy(obj->label, label, sizeof(obj->label)-1);
obj->flags = obj_flags;
if (auth_id)
obj->auth_id = *auth_id;
switch (type & SC_PKCS15_TYPE_CLASS_MASK) {
case SC_PKCS15_TYPE_AUTH:
df_type = SC_PKCS15_AODF;
break;
case SC_PKCS15_TYPE_PRKEY:
df_type = SC_PKCS15_PRKDF;
break;
case SC_PKCS15_TYPE_PUBKEY:
df_type = SC_PKCS15_PUKDF;
break;
case SC_PKCS15_TYPE_CERT:
df_type = SC_PKCS15_CDF;
break;
default:
sc_log(p15card->card->ctx, "Unknown PKCS15 object type %d", type);
free(obj);
return SC_ERROR_INVALID_ARGUMENTS;
}
obj->df = sc_pkcs15emu_get_df(p15card, df_type);
sc_pkcs15_add_object(p15card, obj);
return 0;
}
static int
sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id, const char *label,
const sc_path_t *path, int ref, int type,
unsigned int min_length,
unsigned int max_length,
int flags, int tries_left, const char pad_char, int obj_flags)
{
sc_pkcs15_auth_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
info->auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
info->auth_method = SC_AC_CHV;
info->auth_id = *id;
info->attrs.pin.min_length = min_length;
info->attrs.pin.max_length = max_length;
info->attrs.pin.stored_length = max_length;
info->attrs.pin.type = type;
info->attrs.pin.reference = ref;
info->attrs.pin.flags = flags;
info->attrs.pin.pad_char = pad_char;
info->tries_left = tries_left;
info->logged_in = SC_PIN_STATE_UNKNOWN;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, SC_PKCS15_TYPE_AUTH_PIN, label, info, NULL, obj_flags);
}
static int
sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card,
int type, int authority,
const sc_path_t *path,
const sc_pkcs15_id_t *id,
const char *label, int obj_flags)
{
sc_pkcs15_cert_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
{
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
info->id = *id;
info->authority = authority;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, type, label, info, NULL, obj_flags);
}
static int
sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id,
const char *label,
int type, unsigned int modulus_length, int usage,
const sc_path_t *path, int ref,
const sc_pkcs15_id_t *auth_id, int obj_flags)
{
sc_pkcs15_prkey_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
{
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
info->id = *id;
info->modulus_length = modulus_length;
info->usage = usage;
info->native = 1;
info->access_flags = SC_PKCS15_PRKEY_ACCESS_SENSITIVE
| SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE
| SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE
| SC_PKCS15_PRKEY_ACCESS_LOCAL;
info->key_reference = ref;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, type, label,
info, auth_id, obj_flags);
}
/* SC_IMPLEMENT_DRIVER_VERSION("0.9.4") */
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_346_5 |
crossvul-cpp_data_good_3337_0 | /*-
* Copyright (c) 2006 Verdens Gang AS
* Copyright (c) 2006-2015 Varnish Software AS
* All rights reserved.
*
* Author: Poul-Henning Kamp <phk@phk.freebsd.dk>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 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 "config.h"
#include "cache.h"
#include "cache_director.h"
#include "cache_filter.h"
#include "hash/hash_slinger.h"
#include "storage/storage.h"
#include "vcl.h"
#include "vtim.h"
/*--------------------------------------------------------------------
* Allocate an object, with fall-back to Transient.
* XXX: This somewhat overlaps the stuff in stevedore.c
* XXX: Should this be merged over there ?
*/
static int
vbf_allocobj(struct busyobj *bo, unsigned l)
{
struct objcore *oc;
const struct stevedore *stv;
double lifetime;
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
oc = bo->fetch_objcore;
CHECK_OBJ_NOTNULL(oc, OBJCORE_MAGIC);
lifetime = oc->ttl + oc->grace + oc->keep;
if (bo->uncacheable || lifetime < cache_param->shortlived)
stv = stv_transient;
else
stv = bo->storage;
bo->storage = NULL;
bo->storage_hint = NULL;
if (stv == NULL)
return (0);
if (STV_NewObject(bo->wrk, bo->fetch_objcore, stv, l))
return (1);
if (stv == stv_transient)
return (0);
/*
* Try to salvage the transaction by allocating a shortlived object
* on Transient storage.
*/
if (oc->ttl > cache_param->shortlived)
oc->ttl = cache_param->shortlived;
oc->grace = 0.0;
oc->keep = 0.0;
return (STV_NewObject(bo->wrk, bo->fetch_objcore, stv_transient, l));
}
/*--------------------------------------------------------------------
* Turn the beresp into a obj
*/
static int
vbf_beresp2obj(struct busyobj *bo)
{
unsigned l, l2;
const char *b;
uint8_t *bp;
struct vsb *vary = NULL;
int varyl = 0;
l = 0;
/* Create Vary instructions */
if (!(bo->fetch_objcore->flags & OC_F_PRIVATE)) {
varyl = VRY_Create(bo, &vary);
if (varyl > 0) {
AN(vary);
assert(varyl == VSB_len(vary));
l += PRNDUP((intptr_t)varyl);
} else if (varyl < 0) {
/*
* Vary parse error
* Complain about it, and make this a pass.
*/
VSLb(bo->vsl, SLT_Error,
"Illegal 'Vary' header from backend, "
"making this a pass.");
bo->uncacheable = 1;
AZ(vary);
} else
/* No vary */
AZ(vary);
}
l2 = http_EstimateWS(bo->beresp,
bo->uncacheable ? HTTPH_A_PASS : HTTPH_A_INS);
l += l2;
if (bo->uncacheable)
bo->fetch_objcore->flags |= OC_F_PASS;
if (!vbf_allocobj(bo, l))
return (-1);
if (vary != NULL) {
AN(ObjSetAttr(bo->wrk, bo->fetch_objcore, OA_VARY, varyl,
VSB_data(vary)));
VSB_destroy(&vary);
}
AZ(ObjSetU32(bo->wrk, bo->fetch_objcore, OA_VXID, VXID(bo->vsl->wid)));
/* for HTTP_Encode() VSLH call */
bo->beresp->logtag = SLT_ObjMethod;
/* Filter into object */
bp = ObjSetAttr(bo->wrk, bo->fetch_objcore, OA_HEADERS, l2, NULL);
AN(bp);
HTTP_Encode(bo->beresp, bp, l2,
bo->uncacheable ? HTTPH_A_PASS : HTTPH_A_INS);
if (http_GetHdr(bo->beresp, H_Last_Modified, &b))
AZ(ObjSetDouble(bo->wrk, bo->fetch_objcore, OA_LASTMODIFIED,
VTIM_parse(b)));
else
AZ(ObjSetDouble(bo->wrk, bo->fetch_objcore, OA_LASTMODIFIED,
floor(bo->fetch_objcore->t_origin)));
return (0);
}
/*--------------------------------------------------------------------
* Copy req->bereq and release req if not pass fetch
*/
static enum fetch_step
vbf_stp_mkbereq(struct worker *wrk, struct busyobj *bo)
{
const char *q;
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
CHECK_OBJ_NOTNULL(bo->req, REQ_MAGIC);
assert(bo->fetch_objcore->boc->state == BOS_INVALID);
AZ(bo->storage);
AZ(bo->storage_hint);
HTTP_Setup(bo->bereq0, bo->ws, bo->vsl, SLT_BereqMethod);
http_FilterReq(bo->bereq0, bo->req->http,
bo->do_pass ? HTTPH_R_PASS : HTTPH_R_FETCH);
if (!bo->do_pass) {
http_ForceField(bo->bereq0, HTTP_HDR_METHOD, "GET");
http_ForceField(bo->bereq0, HTTP_HDR_PROTO, "HTTP/1.1");
if (cache_param->http_gzip_support)
http_ForceHeader(bo->bereq0, H_Accept_Encoding, "gzip");
} else {
AZ(bo->stale_oc);
if (bo->bereq0->protover > 11)
http_ForceField(bo->bereq0, HTTP_HDR_PROTO, "HTTP/1.1");
}
http_CopyHome(bo->bereq0);
if (bo->stale_oc != NULL &&
ObjCheckFlag(bo->wrk, bo->stale_oc, OF_IMSCAND) &&
(bo->stale_oc->boc != NULL || ObjGetLen(wrk, bo->stale_oc) != 0)) {
AZ(bo->stale_oc->flags & OC_F_PASS);
q = HTTP_GetHdrPack(bo->wrk, bo->stale_oc, H_Last_Modified);
if (q != NULL)
http_PrintfHeader(bo->bereq0,
"If-Modified-Since: %s", q);
q = HTTP_GetHdrPack(bo->wrk, bo->stale_oc, H_ETag);
if (q != NULL)
http_PrintfHeader(bo->bereq0,
"If-None-Match: %s", q);
}
HTTP_Setup(bo->bereq, bo->ws, bo->vsl, SLT_BereqMethod);
bo->ws_bo = WS_Snapshot(bo->ws);
HTTP_Copy(bo->bereq, bo->bereq0);
if (bo->req->req_body_status == REQ_BODY_NONE) {
bo->req = NULL;
ObjSetState(bo->wrk, bo->fetch_objcore, BOS_REQ_DONE);
}
return (F_STP_STARTFETCH);
}
/*--------------------------------------------------------------------
* Start a new VSL transaction and try again
* Prepare the busyobj and fetch processors
*/
static enum fetch_step
vbf_stp_retry(struct worker *wrk, struct busyobj *bo)
{
struct vfp_ctx *vfc;
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
vfc = bo->vfc;
CHECK_OBJ_NOTNULL(vfc, VFP_CTX_MAGIC);
assert(bo->fetch_objcore->boc->state <= BOS_REQ_DONE);
VSLb_ts_busyobj(bo, "Retry", W_TIM_real(wrk));
/* VDI_Finish must have been called before */
assert(bo->director_state == DIR_S_NULL);
/* reset other bo attributes - See VBO_GetBusyObj */
bo->storage = NULL;
bo->storage_hint = NULL;
bo->do_esi = 0;
bo->do_stream = 1;
/* reset fetch processors */
VFP_Setup(vfc);
// XXX: BereqEnd + BereqAcct ?
VSL_ChgId(bo->vsl, "bereq", "retry", VXID_Get(wrk, VSL_BACKENDMARKER));
VSLb_ts_busyobj(bo, "Start", bo->t_prev);
http_VSL_log(bo->bereq);
return (F_STP_STARTFETCH);
}
/*--------------------------------------------------------------------
* Setup bereq from bereq0, run vcl_backend_fetch
*/
static enum fetch_step
vbf_stp_startfetch(struct worker *wrk, struct busyobj *bo)
{
int i;
double now;
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
AZ(bo->storage);
AZ(bo->storage_hint);
bo->storage = STV_next();
if (bo->retries > 0)
http_Unset(bo->bereq, "\012X-Varnish:");
http_PrintfHeader(bo->bereq, "X-Varnish: %u", VXID(bo->vsl->wid));
VCL_backend_fetch_method(bo->vcl, wrk, NULL, bo, NULL);
bo->uncacheable = bo->do_pass;
if (wrk->handling == VCL_RET_ABANDON || wrk->handling == VCL_RET_FAIL)
return (F_STP_FAIL);
assert (wrk->handling == VCL_RET_FETCH);
HTTP_Setup(bo->beresp, bo->ws, bo->vsl, SLT_BerespMethod);
assert(bo->fetch_objcore->boc->state <= BOS_REQ_DONE);
AZ(bo->htc);
i = VDI_GetHdr(wrk, bo);
now = W_TIM_real(wrk);
VSLb_ts_busyobj(bo, "Beresp", now);
if (i) {
assert(bo->director_state == DIR_S_NULL);
return (F_STP_ERROR);
}
http_VSL_log(bo->beresp);
if (!http_GetHdr(bo->beresp, H_Date, NULL)) {
/*
* RFC 2616 14.18 Date: The Date general-header field
* represents the date and time at which the message was
* originated, having the same semantics as orig-date in
* RFC 822. ... A received message that does not have a
* Date header field MUST be assigned one by the recipient
* if the message will be cached by that recipient or
* gatewayed via a protocol which requires a Date.
*
* If we didn't get a Date header, we assign one here.
*/
http_TimeHeader(bo->beresp, "Date: ", now);
}
/*
* These two headers can be spread over multiple actual headers
* and we rely on their content outside of VCL, so collect them
* into one line here.
*/
http_CollectHdr(bo->beresp, H_Cache_Control);
http_CollectHdr(bo->beresp, H_Vary);
/*
* Figure out how the fetch is supposed to happen, before the
* headers are adultered by VCL
*/
if (!strcasecmp(http_GetMethod(bo->bereq), "head")) {
/*
* A HEAD request can never have a body in the reply,
* no matter what the headers might say.
* [RFC7231 4.3.2 p25]
*/
wrk->stats->fetch_head++;
bo->htc->body_status = BS_NONE;
} else if (http_GetStatus(bo->beresp) <= 199) {
/*
* 1xx responses never have a body.
* [RFC7230 3.3.2 p31]
* ... but we should never see them.
*/
wrk->stats->fetch_1xx++;
bo->htc->body_status = BS_ERROR;
} else if (http_IsStatus(bo->beresp, 204)) {
/*
* 204 is "No Content", obviously don't expect a body.
* [RFC7230 3.3.1 p29 and 3.3.2 p31]
*/
wrk->stats->fetch_204++;
if ((http_GetHdr(bo->beresp, H_Content_Length, NULL) &&
bo->htc->content_length != 0) ||
http_GetHdr(bo->beresp, H_Transfer_Encoding, NULL))
bo->htc->body_status = BS_ERROR;
else
bo->htc->body_status = BS_NONE;
} else if (http_IsStatus(bo->beresp, 304)) {
/*
* 304 is "Not Modified" it has no body.
* [RFC7230 3.3 p28]
*/
wrk->stats->fetch_304++;
bo->htc->body_status = BS_NONE;
} else if (bo->htc->body_status == BS_CHUNKED) {
wrk->stats->fetch_chunked++;
} else if (bo->htc->body_status == BS_LENGTH) {
assert(bo->htc->content_length > 0);
wrk->stats->fetch_length++;
} else if (bo->htc->body_status == BS_EOF) {
wrk->stats->fetch_eof++;
} else if (bo->htc->body_status == BS_ERROR) {
wrk->stats->fetch_bad++;
} else if (bo->htc->body_status == BS_NONE) {
wrk->stats->fetch_none++;
} else {
WRONG("wrong bodystatus");
}
if (bo->htc->body_status == BS_ERROR) {
bo->htc->doclose = SC_RX_BODY;
VDI_Finish(bo->wrk, bo);
VSLb(bo->vsl, SLT_Error, "Body cannot be fetched");
assert(bo->director_state == DIR_S_NULL);
return (F_STP_ERROR);
}
if (bo->fetch_objcore->flags & OC_F_PRIVATE) {
/* private objects have negative TTL */
bo->fetch_objcore->t_origin = now;
bo->fetch_objcore->ttl = -1.;
bo->fetch_objcore->grace = 0;
bo->fetch_objcore->keep = 0;
} else {
/* What does RFC2616 think about TTL ? */
RFC2616_Ttl(bo, now,
&bo->fetch_objcore->t_origin,
&bo->fetch_objcore->ttl,
&bo->fetch_objcore->grace,
&bo->fetch_objcore->keep
);
}
AZ(bo->do_esi);
AZ(bo->was_304);
if (http_IsStatus(bo->beresp, 304)) {
if (bo->stale_oc != NULL &&
ObjCheckFlag(bo->wrk, bo->stale_oc, OF_IMSCAND)) {
if (ObjCheckFlag(bo->wrk, bo->stale_oc, OF_CHGGZIP)) {
/*
* If we changed the gzip status of the object
* the stored Content_Encoding controls we
* must weaken any new ETag we get.
*/
http_Unset(bo->beresp, H_Content_Encoding);
RFC2616_Weaken_Etag(bo->beresp);
}
http_Unset(bo->beresp, H_Content_Length);
HTTP_Merge(bo->wrk, bo->stale_oc, bo->beresp);
assert(http_IsStatus(bo->beresp, 200));
bo->was_304 = 1;
} else if (!bo->do_pass) {
/*
* Backend sent unallowed 304
*/
VSLb(bo->vsl, SLT_Error,
"304 response but not conditional fetch");
bo->htc->doclose = SC_RX_BAD;
VDI_Finish(bo->wrk, bo);
return (F_STP_ERROR);
}
}
bo->vfc->bo = bo;
bo->vfc->oc = bo->fetch_objcore;
bo->vfc->wrk = bo->wrk;
bo->vfc->http = bo->beresp;
bo->vfc->esi_req = bo->bereq;
VCL_backend_response_method(bo->vcl, wrk, NULL, bo, NULL);
if (wrk->handling == VCL_RET_ABANDON || wrk->handling == VCL_RET_FAIL) {
bo->htc->doclose = SC_RESP_CLOSE;
VDI_Finish(bo->wrk, bo);
return (F_STP_FAIL);
}
if (wrk->handling == VCL_RET_RETRY) {
if (bo->htc->body_status != BS_NONE)
bo->htc->doclose = SC_RESP_CLOSE;
if (bo->director_state != DIR_S_NULL)
VDI_Finish(bo->wrk, bo);
if (bo->retries++ < cache_param->max_retries)
return (F_STP_RETRY);
VSLb(bo->vsl, SLT_VCL_Error,
"Too many retries, delivering 503");
assert(bo->director_state == DIR_S_NULL);
return (F_STP_ERROR);
}
assert(bo->fetch_objcore->boc->state <= BOS_REQ_DONE);
if (bo->fetch_objcore->boc->state != BOS_REQ_DONE) {
bo->req = NULL;
ObjSetState(wrk, bo->fetch_objcore, BOS_REQ_DONE);
}
if (bo->do_esi)
bo->do_stream = 0;
if (wrk->handling == VCL_RET_PASS) {
bo->fetch_objcore->flags |= OC_F_HFP;
bo->uncacheable = 1;
wrk->handling = VCL_RET_DELIVER;
}
if (bo->do_pass || bo->uncacheable)
bo->fetch_objcore->flags |= OC_F_PASS;
assert(wrk->handling == VCL_RET_DELIVER);
return (bo->was_304 ? F_STP_CONDFETCH : F_STP_FETCH);
}
/*--------------------------------------------------------------------
*/
static enum fetch_step
vbf_stp_fetchbody(struct worker *wrk, struct busyobj *bo)
{
ssize_t l;
uint8_t *ptr;
enum vfp_status vfps = VFP_ERROR;
ssize_t est;
struct vfp_ctx *vfc;
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
vfc = bo->vfc;
CHECK_OBJ_NOTNULL(vfc, VFP_CTX_MAGIC);
AN(vfc->vfp_nxt);
est = bo->htc->content_length;
if (est < 0)
est = 0;
do {
if (vfc->oc->flags & OC_F_ABANDON) {
/*
* A pass object and delivery was terminated
* We don't fail the fetch, in order for hit-for-pass
* objects to be created.
*/
AN(vfc->oc->flags & OC_F_PASS);
VSLb(wrk->vsl, SLT_FetchError,
"Pass delivery abandoned");
bo->htc->doclose = SC_RX_BODY;
break;
}
AZ(vfc->failed);
l = est;
assert(l >= 0);
if (VFP_GetStorage(vfc, &l, &ptr) != VFP_OK) {
bo->htc->doclose = SC_RX_BODY;
break;
}
AZ(vfc->failed);
vfps = VFP_Suck(vfc, ptr, &l);
if (l > 0 && vfps != VFP_ERROR) {
bo->acct.beresp_bodybytes += l;
VFP_Extend(vfc, l);
if (est >= l)
est -= l;
else
est = 0;
}
} while (vfps == VFP_OK);
if (vfc->failed) {
(void)VFP_Error(vfc, "Fetch pipeline failed to process");
bo->htc->doclose = SC_RX_BODY;
VFP_Close(vfc);
VDI_Finish(wrk, bo);
if (!bo->do_stream) {
assert(bo->fetch_objcore->boc->state < BOS_STREAM);
// XXX: doclose = ?
return (F_STP_ERROR);
} else {
wrk->stats->fetch_failed++;
return (F_STP_FAIL);
}
}
ObjTrimStore(wrk, vfc->oc);
return (F_STP_FETCHEND);
}
/*--------------------------------------------------------------------
*/
#define vbf_vfp_push(bo, vfp, top) \
do { \
if (VFP_Push((bo)->vfc, (vfp), (top)) == NULL) { \
assert (WS_Overflowed((bo)->vfc->http->ws)); \
(void)VFP_Error((bo)->vfc, \
"workspace_backend overflow"); \
(bo)->htc->doclose = SC_OVERLOAD; \
VDI_Finish((bo)->wrk, bo); \
return (F_STP_ERROR); \
} \
} while (0)
static enum fetch_step
vbf_stp_fetch(struct worker *wrk, struct busyobj *bo)
{
const char *p;
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC);
assert(wrk->handling == VCL_RET_DELIVER);
/*
* The VCL variables beresp.do_g[un]zip tells us how we want the
* object processed before it is stored.
*
* The backend Content-Encoding header tells us what we are going
* to receive, which we classify in the following three classes:
*
* "Content-Encoding: gzip" --> object is gzip'ed.
* no Content-Encoding --> object is not gzip'ed.
* anything else --> do nothing wrt gzip
*
*/
/* We do nothing unless the param is set */
if (!cache_param->http_gzip_support)
bo->do_gzip = bo->do_gunzip = 0;
if (bo->htc->content_length == 0)
http_Unset(bo->beresp, H_Content_Encoding);
if (bo->htc->body_status != BS_NONE) {
bo->is_gzip =
http_HdrIs(bo->beresp, H_Content_Encoding, "gzip");
bo->is_gunzip =
!http_GetHdr(bo->beresp, H_Content_Encoding, NULL);
assert(bo->is_gzip == 0 || bo->is_gunzip == 0);
}
/* We won't gunzip unless it is non-empty and gzip'ed */
if (bo->htc->body_status == BS_NONE ||
bo->htc->content_length == 0 ||
(bo->do_gunzip && !bo->is_gzip))
bo->do_gunzip = 0;
/* We wont gzip unless it is non-empty and ungzip'ed */
if (bo->htc->body_status == BS_NONE ||
bo->htc->content_length == 0 ||
(bo->do_gzip && !bo->is_gunzip))
bo->do_gzip = 0;
/* But we can't do both at the same time */
assert(bo->do_gzip == 0 || bo->do_gunzip == 0);
if (bo->do_gunzip || (bo->is_gzip && bo->do_esi))
vbf_vfp_push(bo, &vfp_gunzip, 1);
if (bo->htc->content_length != 0) {
if (bo->do_esi && bo->do_gzip) {
vbf_vfp_push(bo, &vfp_esi_gzip, 1);
} else if (bo->do_esi && bo->is_gzip && !bo->do_gunzip) {
vbf_vfp_push(bo, &vfp_esi_gzip, 1);
} else if (bo->do_esi) {
vbf_vfp_push(bo, &vfp_esi, 1);
} else if (bo->do_gzip) {
vbf_vfp_push(bo, &vfp_gzip, 1);
} else if (bo->is_gzip && !bo->do_gunzip) {
vbf_vfp_push(bo, &vfp_testgunzip, 1);
}
}
if (bo->fetch_objcore->flags & OC_F_PRIVATE)
AN(bo->uncacheable);
/* No reason to try streaming a non-existing body */
if (bo->htc->body_status == BS_NONE)
bo->do_stream = 0;
bo->fetch_objcore->boc->len_so_far = 0;
if (VFP_Open(bo->vfc)) {
(void)VFP_Error(bo->vfc, "Fetch pipeline failed to open");
bo->htc->doclose = SC_RX_BODY;
VDI_Finish(bo->wrk, bo);
return (F_STP_ERROR);
}
if (vbf_beresp2obj(bo)) {
(void)VFP_Error(bo->vfc, "Could not get storage");
bo->htc->doclose = SC_RX_BODY;
VFP_Close(bo->vfc);
VDI_Finish(bo->wrk, bo);
return (F_STP_ERROR);
}
if (bo->do_esi)
ObjSetFlag(bo->wrk, bo->fetch_objcore, OF_ESIPROC, 1);
if (bo->do_gzip || (bo->is_gzip && !bo->do_gunzip))
ObjSetFlag(bo->wrk, bo->fetch_objcore, OF_GZIPED, 1);
if (bo->do_gzip || bo->do_gunzip)
ObjSetFlag(bo->wrk, bo->fetch_objcore, OF_CHGGZIP, 1);
if (!(bo->fetch_objcore->flags & OC_F_PASS) &&
http_IsStatus(bo->beresp, 200) && (
http_GetHdr(bo->beresp, H_Last_Modified, &p) ||
http_GetHdr(bo->beresp, H_ETag, &p)))
ObjSetFlag(bo->wrk, bo->fetch_objcore, OF_IMSCAND, 1);
if (bo->htc->body_status != BS_NONE &&
VDI_GetBody(bo->wrk, bo) != 0) {
(void)VFP_Error(bo->vfc,
"GetBody failed - workspace_backend overflow?");
VFP_Close(bo->vfc);
bo->htc->doclose = SC_OVERLOAD;
VDI_Finish(bo->wrk, bo);
return (F_STP_ERROR);
}
assert(bo->fetch_objcore->boc->refcount >= 1);
assert(bo->fetch_objcore->boc->state == BOS_REQ_DONE);
if (bo->do_stream) {
ObjSetState(wrk, bo->fetch_objcore, BOS_PREP_STREAM);
HSH_Unbusy(wrk, bo->fetch_objcore);
ObjSetState(wrk, bo->fetch_objcore, BOS_STREAM);
}
VSLb(bo->vsl, SLT_Fetch_Body, "%u %s %s",
bo->htc->body_status, body_status_2str(bo->htc->body_status),
bo->do_stream ? "stream" : "-");
if (bo->htc->body_status != BS_NONE) {
assert(bo->htc->body_status != BS_ERROR);
return (F_STP_FETCHBODY);
}
AZ(bo->vfc->failed);
return (F_STP_FETCHEND);
}
static enum fetch_step
vbf_stp_fetchend(struct worker *wrk, struct busyobj *bo)
{
AZ(bo->vfc->failed);
VFP_Close(bo->vfc);
AZ(ObjSetU64(wrk, bo->fetch_objcore, OA_LEN,
bo->fetch_objcore->boc->len_so_far));
if (bo->do_stream)
assert(bo->fetch_objcore->boc->state == BOS_STREAM);
else {
assert(bo->fetch_objcore->boc->state == BOS_REQ_DONE);
HSH_Unbusy(wrk, bo->fetch_objcore);
}
/* Recycle the backend connection before setting BOS_FINISHED to
give predictable backend reuse behavior for varnishtest */
VDI_Finish(bo->wrk, bo);
ObjSetState(wrk, bo->fetch_objcore, BOS_FINISHED);
VSLb_ts_busyobj(bo, "BerespBody", W_TIM_real(wrk));
if (bo->stale_oc != NULL)
HSH_Kill(bo->stale_oc);
return (F_STP_DONE);
}
/*--------------------------------------------------------------------
*/
static int
vbf_objiterator(void *priv, int flush, const void *ptr, ssize_t len)
{
struct busyobj *bo;
ssize_t l;
const uint8_t *ps = ptr;
uint8_t *pd;
(void)flush;
CAST_OBJ_NOTNULL(bo, priv, BUSYOBJ_MAGIC);
while (len > 0) {
l = len;
if (VFP_GetStorage(bo->vfc, &l, &pd) != VFP_OK)
return (1);
if (len < l)
l = len;
memcpy(pd, ps, l);
VFP_Extend(bo->vfc, l);
ps += l;
len -= l;
}
return (0);
}
static enum fetch_step
vbf_stp_condfetch(struct worker *wrk, struct busyobj *bo)
{
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
AZ(vbf_beresp2obj(bo));
if (ObjHasAttr(bo->wrk, bo->stale_oc, OA_ESIDATA))
AZ(ObjCopyAttr(bo->wrk, bo->fetch_objcore, bo->stale_oc,
OA_ESIDATA));
AZ(ObjCopyAttr(bo->wrk, bo->fetch_objcore, bo->stale_oc, OA_FLAGS));
AZ(ObjCopyAttr(bo->wrk, bo->fetch_objcore, bo->stale_oc, OA_GZIPBITS));
if (bo->do_stream) {
ObjSetState(wrk, bo->fetch_objcore, BOS_PREP_STREAM);
HSH_Unbusy(wrk, bo->fetch_objcore);
ObjSetState(wrk, bo->fetch_objcore, BOS_STREAM);
}
if (ObjIterate(wrk, bo->stale_oc, bo, vbf_objiterator, 0))
(void)VFP_Error(bo->vfc, "Template object failed");
if (bo->stale_oc->flags & OC_F_FAILED)
(void)VFP_Error(bo->vfc, "Template object failed");
if (bo->vfc->failed) {
VDI_Finish(bo->wrk, bo);
wrk->stats->fetch_failed++;
return (F_STP_FAIL);
}
return (F_STP_FETCHEND);
}
/*--------------------------------------------------------------------
* Create synth object
*/
static enum fetch_step
vbf_stp_error(struct worker *wrk, struct busyobj *bo)
{
ssize_t l, ll, o;
double now;
uint8_t *ptr;
struct vsb *synth_body;
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC);
AN(bo->fetch_objcore->flags & OC_F_BUSY);
assert(bo->director_state == DIR_S_NULL);
wrk->stats->fetch_failed++;
now = W_TIM_real(wrk);
VSLb_ts_busyobj(bo, "Error", now);
if (bo->fetch_objcore->stobj->stevedore != NULL)
ObjFreeObj(bo->wrk, bo->fetch_objcore);
// XXX: reset all beresp flags ?
HTTP_Setup(bo->beresp, bo->ws, bo->vsl, SLT_BerespMethod);
http_PutResponse(bo->beresp, "HTTP/1.1", 503, "Backend fetch failed");
http_TimeHeader(bo->beresp, "Date: ", now);
http_SetHeader(bo->beresp, "Server: Varnish");
bo->fetch_objcore->t_origin = now;
if (!VTAILQ_EMPTY(&bo->fetch_objcore->objhead->waitinglist)) {
/*
* If there is a waitinglist, it means that there is no
* grace-able object, so cache the error return for a
* short time, so the waiting list can drain, rather than
* each objcore on the waiting list sequentially attempt
* to fetch from the backend.
*/
bo->fetch_objcore->ttl = 1;
bo->fetch_objcore->grace = 5;
bo->fetch_objcore->keep = 5;
} else {
bo->fetch_objcore->ttl = 0;
bo->fetch_objcore->grace = 0;
bo->fetch_objcore->keep = 0;
}
synth_body = VSB_new_auto();
AN(synth_body);
VCL_backend_error_method(bo->vcl, wrk, NULL, bo, synth_body);
AZ(VSB_finish(synth_body));
if (wrk->handling == VCL_RET_ABANDON || wrk->handling == VCL_RET_FAIL) {
VSB_destroy(&synth_body);
return (F_STP_FAIL);
}
if (wrk->handling == VCL_RET_RETRY) {
VSB_destroy(&synth_body);
if (bo->retries++ < cache_param->max_retries)
return (F_STP_RETRY);
VSLb(bo->vsl, SLT_VCL_Error, "Too many retries, failing");
return (F_STP_FAIL);
}
assert(wrk->handling == VCL_RET_DELIVER);
bo->vfc->bo = bo;
bo->vfc->wrk = bo->wrk;
bo->vfc->oc = bo->fetch_objcore;
bo->vfc->http = bo->beresp;
bo->vfc->esi_req = bo->bereq;
if (vbf_beresp2obj(bo)) {
(void)VFP_Error(bo->vfc, "Could not get storage");
VSB_destroy(&synth_body);
return (F_STP_FAIL);
}
ll = VSB_len(synth_body);
o = 0;
while (ll > 0) {
l = ll;
if (VFP_GetStorage(bo->vfc, &l, &ptr) != VFP_OK)
break;
if (l > ll)
l = ll;
memcpy(ptr, VSB_data(synth_body) + o, l);
VFP_Extend(bo->vfc, l);
ll -= l;
o += l;
}
AZ(ObjSetU64(wrk, bo->fetch_objcore, OA_LEN, o));
VSB_destroy(&synth_body);
HSH_Unbusy(wrk, bo->fetch_objcore);
ObjSetState(wrk, bo->fetch_objcore, BOS_FINISHED);
return (F_STP_DONE);
}
/*--------------------------------------------------------------------
*/
static enum fetch_step
vbf_stp_fail(struct worker *wrk, const struct busyobj *bo)
{
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC);
assert(bo->fetch_objcore->boc->state < BOS_FINISHED);
HSH_Fail(bo->fetch_objcore);
if (!(bo->fetch_objcore->flags & OC_F_BUSY))
HSH_Kill(bo->fetch_objcore);
ObjSetState(wrk, bo->fetch_objcore, BOS_FAILED);
return (F_STP_DONE);
}
/*--------------------------------------------------------------------
*/
static enum fetch_step
vbf_stp_done(void)
{
WRONG("Just plain wrong");
NEEDLESS(return(F_STP_DONE));
}
static void __match_proto__(task_func_t)
vbf_fetch_thread(struct worker *wrk, void *priv)
{
struct busyobj *bo;
enum fetch_step stp;
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CAST_OBJ_NOTNULL(bo, priv, BUSYOBJ_MAGIC);
CHECK_OBJ_NOTNULL(bo->req, REQ_MAGIC);
CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC);
THR_SetBusyobj(bo);
stp = F_STP_MKBEREQ;
assert(isnan(bo->t_first));
assert(isnan(bo->t_prev));
VSLb_ts_busyobj(bo, "Start", W_TIM_real(wrk));
bo->wrk = wrk;
wrk->vsl = bo->vsl;
#if 0
if (bo->stale_oc != NULL) {
CHECK_OBJ_NOTNULL(bo->stale_oc, OBJCORE_MAGIC);
/* We don't want the oc/stevedore ops in fetching thread */
if (!ObjCheckFlag(wrk, bo->stale_oc, OF_IMSCAND))
(void)HSH_DerefObjCore(wrk, &bo->stale_oc, 0);
}
#endif
while (stp != F_STP_DONE) {
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
assert(bo->fetch_objcore->boc->refcount >= 1);
switch (stp) {
#define FETCH_STEP(l, U, arg) \
case F_STP_##U: \
stp = vbf_stp_##l arg; \
break;
#include "tbl/steps.h"
default:
WRONG("Illegal fetch_step");
}
}
assert(bo->director_state == DIR_S_NULL);
http_Teardown(bo->bereq);
http_Teardown(bo->beresp);
if (bo->fetch_objcore->boc->state == BOS_FINISHED) {
AZ(bo->fetch_objcore->flags & OC_F_FAILED);
VSLb(bo->vsl, SLT_Length, "%ju",
(uintmax_t)ObjGetLen(bo->wrk, bo->fetch_objcore));
}
// AZ(bo->fetch_objcore->boc); // XXX
if (bo->stale_oc != NULL)
(void)HSH_DerefObjCore(wrk, &bo->stale_oc, 0);
wrk->vsl = NULL;
HSH_DerefBoc(wrk, bo->fetch_objcore);
SES_Rel(bo->sp);
VBO_ReleaseBusyObj(wrk, &bo);
THR_SetBusyobj(NULL);
}
/*--------------------------------------------------------------------
*/
void
VBF_Fetch(struct worker *wrk, struct req *req, struct objcore *oc,
struct objcore *oldoc, enum vbf_fetch_mode_e mode)
{
struct boc *boc;
struct busyobj *bo;
const char *how;
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(req, REQ_MAGIC);
CHECK_OBJ_NOTNULL(oc, OBJCORE_MAGIC);
AN(oc->flags & OC_F_BUSY);
CHECK_OBJ_ORNULL(oldoc, OBJCORE_MAGIC);
bo = VBO_GetBusyObj(wrk, req);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
boc = HSH_RefBoc(oc);
CHECK_OBJ_NOTNULL(boc, BOC_MAGIC);
switch (mode) {
case VBF_PASS:
how = "pass";
bo->do_pass = 1;
break;
case VBF_NORMAL:
how = "fetch";
break;
case VBF_BACKGROUND:
how = "bgfetch";
bo->is_bgfetch = 1;
break;
default:
WRONG("Wrong fetch mode");
}
VSLb(bo->vsl, SLT_Begin, "bereq %u %s", VXID(req->vsl->wid), how);
VSLb(req->vsl, SLT_Link, "bereq %u %s", VXID(bo->vsl->wid), how);
THR_SetBusyobj(bo);
bo->sp = req->sp;
SES_Ref(bo->sp);
AN(bo->vcl);
oc->boc->vary = req->vary_b;
req->vary_b = NULL;
HSH_Ref(oc);
AZ(bo->fetch_objcore);
bo->fetch_objcore = oc;
AZ(bo->stale_oc);
if (oldoc != NULL) {
assert(oldoc->refcnt > 0);
HSH_Ref(oldoc);
bo->stale_oc = oldoc;
}
AZ(bo->req);
bo->req = req;
bo->fetch_task.priv = bo;
bo->fetch_task.func = vbf_fetch_thread;
if (Pool_Task(wrk->pool, &bo->fetch_task, TASK_QUEUE_BO)) {
wrk->stats->fetch_no_thread++;
(void)vbf_stp_fail(req->wrk, bo);
if (bo->stale_oc != NULL)
(void)HSH_DerefObjCore(wrk, &bo->stale_oc, 0);
HSH_DerefBoc(wrk, oc);
SES_Rel(bo->sp);
VBO_ReleaseBusyObj(wrk, &bo);
} else {
bo = NULL; /* ref transferred to fetch thread */
if (mode == VBF_BACKGROUND) {
ObjWaitState(oc, BOS_REQ_DONE);
(void)VRB_Ignore(req);
} else {
ObjWaitState(oc, BOS_STREAM);
if (oc->boc->state == BOS_FAILED) {
AN((oc->flags & OC_F_FAILED));
} else {
AZ(oc->flags & OC_F_BUSY);
}
}
}
AZ(bo);
VSLb_ts_req(req, "Fetch", W_TIM_real(wrk));
assert(oc->boc == boc);
HSH_DerefBoc(wrk, oc);
if (mode == VBF_BACKGROUND)
(void)HSH_DerefObjCore(wrk, &oc, HSH_RUSH_POLICY);
THR_SetBusyobj(NULL);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3337_0 |
crossvul-cpp_data_bad_2918_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% W W PPPP GGGG %
% W W P P G %
% W W W PPPP G GGG %
% WW WW P G G %
% W W P GGG %
% %
% %
% Read WordPerfect Image Format %
% %
% Software Design %
% Jaroslav Fojtik %
% June 2000 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/distort.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magic.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/resource_.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
#include "MagickCore/transform.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
typedef struct
{
unsigned char Red;
unsigned char Blue;
unsigned char Green;
} RGB_Record;
/* Default palette for WPG level 1 */
static const RGB_Record WPG1_Palette[256]={
{ 0, 0, 0}, { 0, 0,168},
{ 0,168, 0}, { 0,168,168},
{168, 0, 0}, {168, 0,168},
{168, 84, 0}, {168,168,168},
{ 84, 84, 84}, { 84, 84,252},
{ 84,252, 84}, { 84,252,252},
{252, 84, 84}, {252, 84,252},
{252,252, 84}, {252,252,252}, /*16*/
{ 0, 0, 0}, { 20, 20, 20},
{ 32, 32, 32}, { 44, 44, 44},
{ 56, 56, 56}, { 68, 68, 68},
{ 80, 80, 80}, { 96, 96, 96},
{112,112,112}, {128,128,128},
{144,144,144}, {160,160,160},
{180,180,180}, {200,200,200},
{224,224,224}, {252,252,252}, /*32*/
{ 0, 0,252}, { 64, 0,252},
{124, 0,252}, {188, 0,252},
{252, 0,252}, {252, 0,188},
{252, 0,124}, {252, 0, 64},
{252, 0, 0}, {252, 64, 0},
{252,124, 0}, {252,188, 0},
{252,252, 0}, {188,252, 0},
{124,252, 0}, { 64,252, 0}, /*48*/
{ 0,252, 0}, { 0,252, 64},
{ 0,252,124}, { 0,252,188},
{ 0,252,252}, { 0,188,252},
{ 0,124,252}, { 0, 64,252},
{124,124,252}, {156,124,252},
{188,124,252}, {220,124,252},
{252,124,252}, {252,124,220},
{252,124,188}, {252,124,156}, /*64*/
{252,124,124}, {252,156,124},
{252,188,124}, {252,220,124},
{252,252,124}, {220,252,124},
{188,252,124}, {156,252,124},
{124,252,124}, {124,252,156},
{124,252,188}, {124,252,220},
{124,252,252}, {124,220,252},
{124,188,252}, {124,156,252}, /*80*/
{180,180,252}, {196,180,252},
{216,180,252}, {232,180,252},
{252,180,252}, {252,180,232},
{252,180,216}, {252,180,196},
{252,180,180}, {252,196,180},
{252,216,180}, {252,232,180},
{252,252,180}, {232,252,180},
{216,252,180}, {196,252,180}, /*96*/
{180,220,180}, {180,252,196},
{180,252,216}, {180,252,232},
{180,252,252}, {180,232,252},
{180,216,252}, {180,196,252},
{0,0,112}, {28,0,112},
{56,0,112}, {84,0,112},
{112,0,112}, {112,0,84},
{112,0,56}, {112,0,28}, /*112*/
{112,0,0}, {112,28,0},
{112,56,0}, {112,84,0},
{112,112,0}, {84,112,0},
{56,112,0}, {28,112,0},
{0,112,0}, {0,112,28},
{0,112,56}, {0,112,84},
{0,112,112}, {0,84,112},
{0,56,112}, {0,28,112}, /*128*/
{56,56,112}, {68,56,112},
{84,56,112}, {96,56,112},
{112,56,112}, {112,56,96},
{112,56,84}, {112,56,68},
{112,56,56}, {112,68,56},
{112,84,56}, {112,96,56},
{112,112,56}, {96,112,56},
{84,112,56}, {68,112,56}, /*144*/
{56,112,56}, {56,112,69},
{56,112,84}, {56,112,96},
{56,112,112}, {56,96,112},
{56,84,112}, {56,68,112},
{80,80,112}, {88,80,112},
{96,80,112}, {104,80,112},
{112,80,112}, {112,80,104},
{112,80,96}, {112,80,88}, /*160*/
{112,80,80}, {112,88,80},
{112,96,80}, {112,104,80},
{112,112,80}, {104,112,80},
{96,112,80}, {88,112,80},
{80,112,80}, {80,112,88},
{80,112,96}, {80,112,104},
{80,112,112}, {80,114,112},
{80,96,112}, {80,88,112}, /*176*/
{0,0,64}, {16,0,64},
{32,0,64}, {48,0,64},
{64,0,64}, {64,0,48},
{64,0,32}, {64,0,16},
{64,0,0}, {64,16,0},
{64,32,0}, {64,48,0},
{64,64,0}, {48,64,0},
{32,64,0}, {16,64,0}, /*192*/
{0,64,0}, {0,64,16},
{0,64,32}, {0,64,48},
{0,64,64}, {0,48,64},
{0,32,64}, {0,16,64},
{32,32,64}, {40,32,64},
{48,32,64}, {56,32,64},
{64,32,64}, {64,32,56},
{64,32,48}, {64,32,40}, /*208*/
{64,32,32}, {64,40,32},
{64,48,32}, {64,56,32},
{64,64,32}, {56,64,32},
{48,64,32}, {40,64,32},
{32,64,32}, {32,64,40},
{32,64,48}, {32,64,56},
{32,64,64}, {32,56,64},
{32,48,64}, {32,40,64}, /*224*/
{44,44,64}, {48,44,64},
{52,44,64}, {60,44,64},
{64,44,64}, {64,44,60},
{64,44,52}, {64,44,48},
{64,44,44}, {64,48,44},
{64,52,44}, {64,60,44},
{64,64,44}, {60,64,44},
{52,64,44}, {48,64,44}, /*240*/
{44,64,44}, {44,64,48},
{44,64,52}, {44,64,60},
{44,64,64}, {44,60,64},
{44,55,64}, {44,48,64},
{0,0,0}, {0,0,0},
{0,0,0}, {0,0,0},
{0,0,0}, {0,0,0},
{0,0,0}, {0,0,0} /*256*/
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s W P G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsWPG() returns True if the image format type, identified by the magick
% string, is WPG.
%
% The format of the IsWPG method is:
%
% unsigned int IsWPG(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o status: Method IsWPG returns True if the image format type is WPG.
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static unsigned int IsWPG(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\377WPC",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
static void Rd_WP_DWORD(Image *image,size_t *d)
{
unsigned char
b;
b=ReadBlobByte(image);
*d=b;
if (b < 0xFFU)
return;
b=ReadBlobByte(image);
*d=(size_t) b;
b=ReadBlobByte(image);
*d+=(size_t) b*256l;
if (*d < 0x8000)
return;
*d=(*d & 0x7FFF) << 16;
b=ReadBlobByte(image);
*d+=(size_t) b;
b=ReadBlobByte(image);
*d+=(size_t) b*256l;
return;
}
static MagickBooleanType InsertRow(Image *image,unsigned char *p,ssize_t y,
int bpp,ExceptionInfo *exception)
{
int
bit;
Quantum
index;
register Quantum
*q;
ssize_t
x;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
return(MagickFalse);
switch (bpp)
{
case 1: /* Convert bitmap scanline. */
{
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (ssize_t) (image->columns % 8); bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
p++;
}
break;
}
case 2: /* Convert PseudoColor scanline. */
{
for (x=0; x < ((ssize_t) image->columns-3); x+=4)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
p++;
}
if ((image->columns % 4) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
if ((image->columns % 4) > 1)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
if ((image->columns % 4) > 2)
{
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,
exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
}
p++;
}
break;
}
case 4: /* Convert PseudoColor scanline. */
{
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0x0f,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
if ((image->columns % 2) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
break;
}
case 8: /* Convert PseudoColor scanline. */
{
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
}
break;
case 24: /* Convert DirectColor scanline. */
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
break;
}
if (!SyncAuthenticPixels(image,exception))
return(MagickFalse);
return(MagickTrue);
}
/* Helper for WPG1 raster reader. */
#define InsertByte(b) \
{ \
BImgBuff[x]=b; \
x++; \
if((ssize_t) x>=ldblk) \
{ \
if (InsertRow(image,BImgBuff,(ssize_t) y,bpp,exception) != MagickFalse) \
y++; \
x=0; \
} \
}
/* WPG1 raster reader. */
static int UnpackWPGRaster(Image *image,int bpp,ExceptionInfo *exception)
{
int
x,
y,
i;
unsigned char
bbuf,
*BImgBuff,
RunCount;
ssize_t
ldblk;
x=0;
y=0;
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
8*sizeof(*BImgBuff));
if(BImgBuff==NULL) return(-2);
while(y<(ssize_t) image->rows)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
bbuf=(unsigned char) c;
RunCount=bbuf & 0x7F;
if(bbuf & 0x80)
{
if(RunCount) /* repeat next byte runcount * */
{
bbuf=ReadBlobByte(image);
for(i=0;i<(int) RunCount;i++) InsertByte(bbuf);
}
else { /* read next byte as RunCount; repeat 0xFF runcount* */
c=ReadBlobByte(image);
if (c < 0)
break;
RunCount=(unsigned char) c;
for(i=0;i<(int) RunCount;i++) InsertByte(0xFF);
}
}
else {
if(RunCount) /* next runcount byte are readed directly */
{
for(i=0;i < (int) RunCount;i++)
{
bbuf=ReadBlobByte(image);
InsertByte(bbuf);
}
}
else { /* repeat previous line runcount* */
c=ReadBlobByte(image);
if (c < 0)
break;
RunCount=(unsigned char) c;
if(x) { /* attempt to duplicate row from x position: */
/* I do not know what to do here */
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-3);
}
for(i=0;i < (int) RunCount;i++)
{
x=0;
y++; /* Here I need to duplicate previous row RUNCOUNT* */
if(y<2) continue;
if(y>(ssize_t) image->rows)
{
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-4);
}
InsertRow(image,BImgBuff,y-1,bpp,exception);
}
}
}
if (EOFBlob(image) != MagickFalse)
break;
}
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(y <(ssize_t) image->rows ? -5 : 0);
}
/* Helper for WPG2 reader. */
#define InsertByte6(b) \
{ \
DisableMSCWarning(4310) \
if(XorMe)\
BImgBuff[x] = (unsigned char)~b;\
else\
BImgBuff[x] = b;\
RestoreMSCWarning \
x++; \
if((ssize_t) x >= ldblk) \
{ \
if (InsertRow(image,BImgBuff,(ssize_t) y,bpp,exception) != MagickFalse) \
y++; \
x=0; \
} \
}
/* WPG2 raster reader. */
static int UnpackWPG2Raster(Image *image,int bpp,ExceptionInfo *exception)
{
int
RunCount,
XorMe = 0;
size_t
x,
y;
ssize_t
i,
ldblk;
unsigned int
SampleSize=1;
unsigned char
bbuf,
*BImgBuff,
SampleBuffer[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
x=0;
y=0;
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
sizeof(*BImgBuff));
if(BImgBuff==NULL)
return(-2);
while( y< image->rows)
{
bbuf=ReadBlobByte(image);
switch(bbuf)
{
case 0x7D:
SampleSize=ReadBlobByte(image); /* DSZ */
if(SampleSize>8)
{
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-2);
}
if(SampleSize<1)
{
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-2);
}
break;
case 0x7E:
(void) FormatLocaleFile(stderr,
"\nUnsupported WPG token XOR, please report!");
XorMe=!XorMe;
break;
case 0x7F:
RunCount=ReadBlobByte(image); /* BLK */
if (RunCount < 0)
break;
for(i=0; i < SampleSize*(RunCount+1); i++)
{
InsertByte6(0);
}
break;
case 0xFD:
RunCount=ReadBlobByte(image); /* EXT */
if (RunCount < 0)
break;
for(i=0; i<= RunCount;i++)
for(bbuf=0; bbuf < SampleSize; bbuf++)
InsertByte6(SampleBuffer[bbuf]);
break;
case 0xFE:
RunCount=ReadBlobByte(image); /* RST */
if (RunCount < 0)
break;
if(x!=0)
{
(void) FormatLocaleFile(stderr,
"\nUnsupported WPG2 unaligned token RST x=%.20g, please report!\n"
,(double) x);
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-3);
}
{
/* duplicate the previous row RunCount x */
for(i=0;i<=RunCount;i++)
{
if (InsertRow(image,BImgBuff,(ssize_t) (image->rows >= y ? y : image->rows-1),
bpp,exception) != MagickFalse)
y++;
}
}
break;
case 0xFF:
RunCount=ReadBlobByte(image); /* WHT */
if (RunCount < 0)
break;
for(i=0; i < SampleSize*(RunCount+1); i++)
{
InsertByte6(0xFF);
}
break;
default:
RunCount=bbuf & 0x7F;
if(bbuf & 0x80) /* REP */
{
for(i=0; i < SampleSize; i++)
SampleBuffer[i]=ReadBlobByte(image);
for(i=0;i<=RunCount;i++)
for(bbuf=0;bbuf<SampleSize;bbuf++)
InsertByte6(SampleBuffer[bbuf]);
}
else { /* NRP */
for(i=0; i< SampleSize*(RunCount+1);i++)
{
bbuf=ReadBlobByte(image);
InsertByte6(bbuf);
}
}
}
if (EOFBlob(image) != MagickFalse)
break;
}
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(0);
}
typedef float tCTM[3][3];
static unsigned LoadWPG2Flags(Image *image,char Precision,float *Angle,tCTM *CTM)
{
const unsigned char TPR=1,TRN=2,SKW=4,SCL=8,ROT=0x10,OID=0x20,LCK=0x80;
ssize_t x;
unsigned DenX;
unsigned Flags;
(void) memset(*CTM,0,sizeof(*CTM)); /*CTM.erase();CTM.resize(3,3);*/
(*CTM)[0][0]=1;
(*CTM)[1][1]=1;
(*CTM)[2][2]=1;
Flags=ReadBlobLSBShort(image);
if(Flags & LCK) (void) ReadBlobLSBLong(image); /*Edit lock*/
if(Flags & OID)
{
if(Precision==0)
{(void) ReadBlobLSBShort(image);} /*ObjectID*/
else
{(void) ReadBlobLSBLong(image);} /*ObjectID (Double precision)*/
}
if(Flags & ROT)
{
x=ReadBlobLSBLong(image); /*Rot Angle*/
if(Angle) *Angle=x/65536.0;
}
if(Flags & (ROT|SCL))
{
x=ReadBlobLSBLong(image); /*Sx*cos()*/
(*CTM)[0][0] = (float)x/0x10000;
x=ReadBlobLSBLong(image); /*Sy*cos()*/
(*CTM)[1][1] = (float)x/0x10000;
}
if(Flags & (ROT|SKW))
{
x=ReadBlobLSBLong(image); /*Kx*sin()*/
(*CTM)[1][0] = (float)x/0x10000;
x=ReadBlobLSBLong(image); /*Ky*sin()*/
(*CTM)[0][1] = (float)x/0x10000;
}
if(Flags & TRN)
{
x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Tx*/
if(x>=0) (*CTM)[0][2] = (float)x+(float)DenX/0x10000;
else (*CTM)[0][2] = (float)x-(float)DenX/0x10000;
x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Ty*/
(*CTM)[1][2]=(float)x + ((x>=0)?1:-1)*(float)DenX/0x10000;
if(x>=0) (*CTM)[1][2] = (float)x+(float)DenX/0x10000;
else (*CTM)[1][2] = (float)x-(float)DenX/0x10000;
}
if(Flags & TPR)
{
x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Px*/
(*CTM)[2][0] = x + (float)DenX/0x10000;;
x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Py*/
(*CTM)[2][1] = x + (float)DenX/0x10000;
}
return(Flags);
}
static Image *ExtractPostscript(Image *image,const ImageInfo *image_info,
MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
char
postscript_file[MagickPathExtent];
const MagicInfo
*magic_info;
FILE
*ps_file;
ImageInfo
*clone_info;
Image
*image2;
unsigned char
magick[2*MagickPathExtent];
if ((clone_info=CloneImageInfo(image_info)) == NULL)
return(image);
clone_info->blob=(void *) NULL;
clone_info->length=0;
/* Obtain temporary file */
(void) AcquireUniqueFilename(postscript_file);
ps_file=fopen_utf8(postscript_file,"wb");
if (ps_file == (FILE *) NULL)
goto FINISH;
/* Copy postscript to temporary file */
(void) SeekBlob(image,PS_Offset,SEEK_SET);
(void) ReadBlob(image, 2*MagickPathExtent, magick);
(void) SeekBlob(image,PS_Offset,SEEK_SET);
while(PS_Size-- > 0)
{
(void) fputc(ReadBlobByte(image),ps_file);
}
(void) fclose(ps_file);
/* Detect file format - Check magic.mgk configuration file. */
magic_info=GetMagicInfo(magick,2*MagickPathExtent,exception);
if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
/* printf("Detected:%s \n",magic_info->name); */
if(exception->severity != UndefinedException) goto FINISH_UNL;
if(magic_info->name == (char *) NULL) goto FINISH_UNL;
(void) strncpy(clone_info->magick,magic_info->name,MagickPathExtent-1);
/* Read nested image */
/*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
FormatLocaleString(clone_info->filename,MagickPathExtent,"%s",postscript_file);
image2=ReadImage(clone_info,exception);
if (!image2)
goto FINISH_UNL;
/*
Replace current image with new image while copying base image
attributes.
*/
(void) CopyMagickString(image2->filename,image->filename,MagickPathExtent);
(void) CopyMagickString(image2->magick_filename,image->magick_filename,MagickPathExtent);
(void) CopyMagickString(image2->magick,image->magick,MagickPathExtent);
image2->depth=image->depth;
DestroyBlob(image2);
image2->blob=ReferenceBlob(image->blob);
if ((image->rows == 0) || (image->columns == 0))
DeleteImageFromList(&image);
AppendImageToList(&image,image2);
FINISH_UNL:
(void) RelinquishUniqueFileResource(postscript_file);
FINISH:
DestroyImageInfo(clone_info);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d W P G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method ReadWPGImage reads an WPG X image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadWPGImage method is:
%
% Image *ReadWPGImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: Method ReadWPGImage returns a pointer to the image after
% reading. A null image is returned if there is a memory shortage or if
% the image cannot be read.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadWPGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct
{
size_t FileId;
MagickOffsetType DataOffset;
unsigned int ProductType;
unsigned int FileType;
unsigned char MajorVersion;
unsigned char MinorVersion;
unsigned int EncryptKey;
unsigned int Reserved;
} WPGHeader;
typedef struct
{
unsigned char RecType;
size_t RecordLength;
} WPGRecord;
typedef struct
{
unsigned char Class;
unsigned char RecType;
size_t Extension;
size_t RecordLength;
} WPG2Record;
typedef struct
{
unsigned HorizontalUnits;
unsigned VerticalUnits;
unsigned char PosSizePrecision;
} WPG2Start;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType1;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned char Depth;
unsigned char Compression;
} WPG2BitmapType1;
typedef struct
{
unsigned int RotAngle;
unsigned int LowLeftX;
unsigned int LowLeftY;
unsigned int UpRightX;
unsigned int UpRightY;
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType2;
typedef struct
{
unsigned int StartIndex;
unsigned int NumOfEntries;
} WPGColorMapRec;
/*
typedef struct {
size_t PS_unknown1;
unsigned int PS_unknown2;
unsigned int PS_unknown3;
} WPGPSl1Record;
*/
Image
*image;
unsigned int
status;
WPGHeader
Header;
WPGRecord
Rec;
WPG2Record
Rec2;
WPG2Start StartWPG;
WPGBitmapType1
BitmapHeader1;
WPG2BitmapType1
Bitmap2Header1;
WPGBitmapType2
BitmapHeader2;
WPGColorMapRec
WPG_Palette;
int
i,
bpp,
WPG2Flags;
ssize_t
ldblk;
size_t
one;
unsigned char
*BImgBuff;
tCTM CTM; /*current transform matrix*/
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1;
image=AcquireImage(image_info,exception);
image->depth=8;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read WPG image.
*/
Header.FileId=ReadBlobLSBLong(image);
Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);
Header.ProductType=ReadBlobLSBShort(image);
Header.FileType=ReadBlobLSBShort(image);
Header.MajorVersion=ReadBlobByte(image);
Header.MinorVersion=ReadBlobByte(image);
Header.EncryptKey=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (Header.EncryptKey!=0)
ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported");
image->columns = 1;
image->rows = 1;
image->colors = 0;
bpp=0;
BitmapHeader2.RotAngle=0;
Rec2.RecordLength=0;
switch(Header.FileType)
{
case 1: /* WPG level 1 */
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec.RecordLength);
if (Rec.RecordLength > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec.RecordLength;
switch(Rec.RecType)
{
case 0x0B: /* bitmap type 1 */
BitmapHeader1.Width=ReadBlobLSBShort(image);
BitmapHeader1.Height=ReadBlobLSBShort(image);
if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader1.Depth=ReadBlobLSBShort(image);
BitmapHeader1.HorzRes=ReadBlobLSBShort(image);
BitmapHeader1.VertRes=ReadBlobLSBShort(image);
if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)
{
image->units=PixelsPerCentimeterResolution;
image->resolution.x=BitmapHeader1.HorzRes/470.0;
image->resolution.y=BitmapHeader1.VertRes/470.0;
}
image->columns=BitmapHeader1.Width;
image->rows=BitmapHeader1.Height;
bpp=BitmapHeader1.Depth;
goto UnpackRaster;
case 0x0E: /*Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) >
(Rec2.RecordLength-2-2) / 3)
ThrowReaderException(CorruptImageError,"InvalidColormapIndex");
image->colors=WPG_Palette.NumOfEntries;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
}
break;
case 0x11: /* Start PS l1 */
if(Rec.RecordLength > 8)
image=ExtractPostscript(image,image_info,
TellBlob(image)+8, /* skip PS header in the wpg */
(ssize_t) Rec.RecordLength-8,exception);
break;
case 0x14: /* bitmap type 2 */
BitmapHeader2.RotAngle=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);
BitmapHeader2.UpRightX=ReadBlobLSBShort(image);
BitmapHeader2.UpRightY=ReadBlobLSBShort(image);
BitmapHeader2.Width=ReadBlobLSBShort(image);
BitmapHeader2.Height=ReadBlobLSBShort(image);
if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader2.Depth=ReadBlobLSBShort(image);
BitmapHeader2.HorzRes=ReadBlobLSBShort(image);
BitmapHeader2.VertRes=ReadBlobLSBShort(image);
image->units=PixelsPerCentimeterResolution;
image->page.width=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);
image->page.height=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);
image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);
image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);
if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)
{
image->resolution.x=BitmapHeader2.HorzRes/470.0;
image->resolution.y=BitmapHeader2.VertRes/470.0;
}
image->columns=BitmapHeader2.Width;
image->rows=BitmapHeader2.Height;
bpp=BitmapHeader2.Depth;
UnpackRaster:
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
if ((image->colors == 0) && (bpp <= 16))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
{
NoMemory:
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
/* printf("Load default colormap \n"); */
for (i=0; (i < (int) image->colors) && (i < 256); i++)
{
image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);
image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);
image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);
}
}
else
{
if (bpp < 24)
if ( (image->colors < (one << bpp)) && (bpp != 24) )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
if (bpp == 1)
{
if(image->colormap[0].red==0 &&
image->colormap[0].green==0 &&
image->colormap[0].blue==0 &&
image->colormap[1].red==0 &&
image->colormap[1].green==0 &&
image->colormap[1].blue==0)
{ /* fix crippled monochrome palette */
image->colormap[1].red =
image->colormap[1].green =
image->colormap[1].blue = QuantumRange;
}
}
if(UnpackWPGRaster(image,bpp,exception) < 0)
/* The raster cannot be unpacked */
{
DecompressionFailed:
ThrowReaderException(CoderError,"UnableToDecompressImage");
}
if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)
{
/* flop command */
if(BitmapHeader2.RotAngle & 0x8000)
{
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
ReplaceImageInList(&image,flop_image);
}
}
/* flip command */
if(BitmapHeader2.RotAngle & 0x2000)
{
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
ReplaceImageInList(&image,flip_image);
}
}
/* rotate command */
if(BitmapHeader2.RotAngle & 0x0FFF)
{
Image
*rotate_image;
rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &
0x0FFF), exception);
if (rotate_image != (Image *) NULL) {
DuplicateBlob(rotate_image,image);
ReplaceImageInList(&image,rotate_image);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x1B: /* Postscript l2 */
if(Rec.RecordLength>0x3C)
image=ExtractPostscript(image,image_info,
TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */
(ssize_t) Rec.RecordLength-0x3C,exception);
break;
}
}
break;
case 2: /* WPG level 2 */
(void) memset(CTM,0,sizeof(CTM));
StartWPG.PosSizePrecision = 0;
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec2.Class=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rec2.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec2.Extension);
Rd_WP_DWORD(image,&Rec2.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec2.RecordLength;
switch(Rec2.RecType)
{
case 1:
StartWPG.HorizontalUnits=ReadBlobLSBShort(image);
StartWPG.VerticalUnits=ReadBlobLSBShort(image);
StartWPG.PosSizePrecision=ReadBlobByte(image);
break;
case 0x0C: /* Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) >
(Rec2.RecordLength-2-2) / 3)
ThrowReaderException(CorruptImageError,"InvalidColormapIndex");
image->colors=WPG_Palette.NumOfEntries;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((char)
ReadBlobByte(image));
(void) ReadBlobByte(image); /*Opacity??*/
}
break;
case 0x0E:
Bitmap2Header1.Width=ReadBlobLSBShort(image);
Bitmap2Header1.Height=ReadBlobLSBShort(image);
if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
Bitmap2Header1.Depth=ReadBlobByte(image);
Bitmap2Header1.Compression=ReadBlobByte(image);
if(Bitmap2Header1.Compression > 1)
continue; /*Unknown compression method */
switch(Bitmap2Header1.Depth)
{
case 1:
bpp=1;
break;
case 2:
bpp=2;
break;
case 3:
bpp=4;
break;
case 4:
bpp=8;
break;
case 8:
bpp=24;
break;
default:
continue; /*Ignore raster with unknown depth*/
}
image->columns=Bitmap2Header1.Width;
image->rows=Bitmap2Header1.Height;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
switch(Bitmap2Header1.Compression)
{
case 0: /*Uncompressed raster*/
{
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)
ldblk+1,sizeof(*BImgBuff));
if (BImgBuff == (unsigned char *) NULL)
goto NoMemory;
for(i=0; i< (ssize_t) image->rows; i++)
{
(void) ReadBlob(image,ldblk,BImgBuff);
InsertRow(image,BImgBuff,i,bpp,exception);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp,exception) < 0)
goto DecompressionFailed;
break;
}
}
if(CTM[0][0]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
ReplaceImageInList(&image,flop_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0;
Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);
Tx(1,2)=0; Tx(2,2)=1; */
}
if(CTM[1][1]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
ReplaceImageInList(&image,flip_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
float_matrix Tx(3,3);
Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0;
Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);
Tx(2,2)=1; */
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x12: /* Postscript WPG2*/
i=ReadBlobLSBShort(image);
if(Rec2.RecordLength > (unsigned int) i)
image=ExtractPostscript(image,image_info,
TellBlob(image)+i, /*skip PS header in the wpg2*/
(ssize_t) (Rec2.RecordLength-i-2),exception);
break;
case 0x1B: /*bitmap rectangle*/
WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);
(void) WPG2Flags;
break;
}
}
break;
default:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
}
}
Finish:
(void) CloseBlob(image);
{
Image
*p;
ssize_t
scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers.
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=(size_t) scene++;
}
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r W P G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method RegisterWPGImage adds attributes for the WPG 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 RegisterWPGImage method is:
%
% size_t RegisterWPGImage(void)
%
*/
ModuleExport size_t RegisterWPGImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("WPG","WPG","Word Perfect Graphics");
entry->decoder=(DecodeImageHandler *) ReadWPGImage;
entry->magick=(IsImageFormatHandler *) IsWPG;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r W P G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method UnregisterWPGImage removes format registrations made by the
% WPG module from the list of supported formats.
%
% The format of the UnregisterWPGImage method is:
%
% UnregisterWPGImage(void)
%
*/
ModuleExport void UnregisterWPGImage(void)
{
(void) UnregisterMagickInfo("WPG");
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2918_0 |
crossvul-cpp_data_good_1746_0 | /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2014 Lennart Poettering
systemd is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <netdb.h>
#include <nss.h>
#include "sd-bus.h"
#include "sd-login.h"
#include "alloc-util.h"
#include "bus-common-errors.h"
#include "bus-util.h"
#include "hostname-util.h"
#include "in-addr-util.h"
#include "macro.h"
#include "nss-util.h"
#include "string-util.h"
#include "user-util.h"
#include "util.h"
NSS_GETHOSTBYNAME_PROTOTYPES(mymachines);
NSS_GETPW_PROTOTYPES(mymachines);
NSS_GETGR_PROTOTYPES(mymachines);
static int count_addresses(sd_bus_message *m, int af, unsigned *ret) {
unsigned c = 0;
int r;
assert(m);
assert(ret);
while ((r = sd_bus_message_enter_container(m, 'r', "iay")) > 0) {
int family;
r = sd_bus_message_read(m, "i", &family);
if (r < 0)
return r;
r = sd_bus_message_skip(m, "ay");
if (r < 0)
return r;
r = sd_bus_message_exit_container(m);
if (r < 0)
return r;
if (af != AF_UNSPEC && family != af)
continue;
c ++;
}
if (r < 0)
return r;
r = sd_bus_message_rewind(m, false);
if (r < 0)
return r;
*ret = c;
return 0;
}
enum nss_status _nss_mymachines_gethostbyname4_r(
const char *name,
struct gaih_addrtuple **pat,
char *buffer, size_t buflen,
int *errnop, int *h_errnop,
int32_t *ttlp) {
struct gaih_addrtuple *r_tuple, *r_tuple_first = NULL;
_cleanup_bus_message_unref_ sd_bus_message* reply = NULL;
_cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
_cleanup_free_ int *ifindices = NULL;
_cleanup_free_ char *class = NULL;
size_t l, ms, idx;
unsigned i = 0, c = 0;
char *r_name;
int n_ifindices, r;
assert(name);
assert(pat);
assert(buffer);
assert(errnop);
assert(h_errnop);
r = sd_machine_get_class(name, &class);
if (r < 0)
goto fail;
if (!streq(class, "container")) {
r = -ENOTTY;
goto fail;
}
n_ifindices = sd_machine_get_ifindices(name, &ifindices);
if (n_ifindices < 0) {
r = n_ifindices;
goto fail;
}
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"GetMachineAddresses",
NULL,
&reply,
"s", name);
if (r < 0)
goto fail;
r = sd_bus_message_enter_container(reply, 'a', "(iay)");
if (r < 0)
goto fail;
r = count_addresses(reply, AF_UNSPEC, &c);
if (r < 0)
goto fail;
if (c <= 0) {
*errnop = ESRCH;
*h_errnop = HOST_NOT_FOUND;
return NSS_STATUS_NOTFOUND;
}
l = strlen(name);
ms = ALIGN(l+1) + ALIGN(sizeof(struct gaih_addrtuple)) * c;
if (buflen < ms) {
*errnop = ENOMEM;
*h_errnop = TRY_AGAIN;
return NSS_STATUS_TRYAGAIN;
}
/* First, append name */
r_name = buffer;
memcpy(r_name, name, l+1);
idx = ALIGN(l+1);
/* Second, append addresses */
r_tuple_first = (struct gaih_addrtuple*) (buffer + idx);
while ((r = sd_bus_message_enter_container(reply, 'r', "iay")) > 0) {
int family;
const void *a;
size_t sz;
r = sd_bus_message_read(reply, "i", &family);
if (r < 0)
goto fail;
r = sd_bus_message_read_array(reply, 'y', &a, &sz);
if (r < 0)
goto fail;
r = sd_bus_message_exit_container(reply);
if (r < 0)
goto fail;
if (!IN_SET(family, AF_INET, AF_INET6)) {
r = -EAFNOSUPPORT;
goto fail;
}
if (sz != FAMILY_ADDRESS_SIZE(family)) {
r = -EINVAL;
goto fail;
}
r_tuple = (struct gaih_addrtuple*) (buffer + idx);
r_tuple->next = i == c-1 ? NULL : (struct gaih_addrtuple*) ((char*) r_tuple + ALIGN(sizeof(struct gaih_addrtuple)));
r_tuple->name = r_name;
r_tuple->family = family;
r_tuple->scopeid = n_ifindices == 1 ? ifindices[0] : 0;
memcpy(r_tuple->addr, a, sz);
idx += ALIGN(sizeof(struct gaih_addrtuple));
i++;
}
assert(i == c);
r = sd_bus_message_exit_container(reply);
if (r < 0)
goto fail;
assert(idx == ms);
if (*pat)
**pat = *r_tuple_first;
else
*pat = r_tuple_first;
if (ttlp)
*ttlp = 0;
/* Explicitly reset all error variables */
*errnop = 0;
*h_errnop = NETDB_SUCCESS;
h_errno = 0;
return NSS_STATUS_SUCCESS;
fail:
*errnop = -r;
*h_errnop = NO_DATA;
return NSS_STATUS_UNAVAIL;
}
enum nss_status _nss_mymachines_gethostbyname3_r(
const char *name,
int af,
struct hostent *result,
char *buffer, size_t buflen,
int *errnop, int *h_errnop,
int32_t *ttlp,
char **canonp) {
_cleanup_bus_message_unref_ sd_bus_message* reply = NULL;
_cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
_cleanup_free_ char *class = NULL;
unsigned c = 0, i = 0;
char *r_name, *r_aliases, *r_addr, *r_addr_list;
size_t l, idx, ms, alen;
int r;
assert(name);
assert(result);
assert(buffer);
assert(errnop);
assert(h_errnop);
if (af == AF_UNSPEC)
af = AF_INET;
if (af != AF_INET && af != AF_INET6) {
r = -EAFNOSUPPORT;
goto fail;
}
r = sd_machine_get_class(name, &class);
if (r < 0)
goto fail;
if (!streq(class, "container")) {
r = -ENOTTY;
goto fail;
}
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"GetMachineAddresses",
NULL,
&reply,
"s", name);
if (r < 0)
goto fail;
r = sd_bus_message_enter_container(reply, 'a', "(iay)");
if (r < 0)
goto fail;
r = count_addresses(reply, af, &c);
if (r < 0)
goto fail;
if (c <= 0) {
*errnop = ENOENT;
*h_errnop = HOST_NOT_FOUND;
return NSS_STATUS_NOTFOUND;
}
alen = FAMILY_ADDRESS_SIZE(af);
l = strlen(name);
ms = ALIGN(l+1) + c * ALIGN(alen) + (c+2) * sizeof(char*);
if (buflen < ms) {
*errnop = ENOMEM;
*h_errnop = NO_RECOVERY;
return NSS_STATUS_TRYAGAIN;
}
/* First, append name */
r_name = buffer;
memcpy(r_name, name, l+1);
idx = ALIGN(l+1);
/* Second, create aliases array */
r_aliases = buffer + idx;
((char**) r_aliases)[0] = NULL;
idx += sizeof(char*);
/* Third, append addresses */
r_addr = buffer + idx;
while ((r = sd_bus_message_enter_container(reply, 'r', "iay")) > 0) {
int family;
const void *a;
size_t sz;
r = sd_bus_message_read(reply, "i", &family);
if (r < 0)
goto fail;
r = sd_bus_message_read_array(reply, 'y', &a, &sz);
if (r < 0)
goto fail;
r = sd_bus_message_exit_container(reply);
if (r < 0)
goto fail;
if (family != af)
continue;
if (sz != alen) {
r = -EINVAL;
goto fail;
}
memcpy(r_addr + i*ALIGN(alen), a, alen);
i++;
}
assert(i == c);
idx += c * ALIGN(alen);
r = sd_bus_message_exit_container(reply);
if (r < 0)
goto fail;
/* Third, append address pointer array */
r_addr_list = buffer + idx;
for (i = 0; i < c; i++)
((char**) r_addr_list)[i] = r_addr + i*ALIGN(alen);
((char**) r_addr_list)[i] = NULL;
idx += (c+1) * sizeof(char*);
assert(idx == ms);
result->h_name = r_name;
result->h_aliases = (char**) r_aliases;
result->h_addrtype = af;
result->h_length = alen;
result->h_addr_list = (char**) r_addr_list;
if (ttlp)
*ttlp = 0;
if (canonp)
*canonp = r_name;
/* Explicitly reset all error variables */
*errnop = 0;
*h_errnop = NETDB_SUCCESS;
h_errno = 0;
return NSS_STATUS_SUCCESS;
fail:
*errnop = -r;
*h_errnop = NO_DATA;
return NSS_STATUS_UNAVAIL;
}
NSS_GETHOSTBYNAME_FALLBACKS(mymachines);
enum nss_status _nss_mymachines_getpwnam_r(
const char *name,
struct passwd *pwd,
char *buffer, size_t buflen,
int *errnop) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_bus_message_unref_ sd_bus_message* reply = NULL;
_cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
const char *p, *e, *machine;
uint32_t mapped;
uid_t uid;
size_t l;
int r;
assert(name);
assert(pwd);
p = startswith(name, "vu-");
if (!p)
goto not_found;
e = strrchr(p, '-');
if (!e || e == p)
goto not_found;
if (e - p > HOST_NAME_MAX - 1) /* -1 for the last dash */
goto not_found;
r = parse_uid(e + 1, &uid);
if (r < 0)
goto not_found;
machine = strndupa(p, e - p);
if (!machine_name_is_valid(machine))
goto not_found;
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"MapFromMachineUser",
&error,
&reply,
"su",
machine, (uint32_t) uid);
if (r < 0) {
if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_USER_MAPPING))
goto not_found;
goto fail;
}
r = sd_bus_message_read(reply, "u", &mapped);
if (r < 0)
goto fail;
l = strlen(name);
if (buflen < l+1) {
*errnop = ENOMEM;
return NSS_STATUS_TRYAGAIN;
}
memcpy(buffer, name, l+1);
pwd->pw_name = buffer;
pwd->pw_uid = mapped;
pwd->pw_gid = 65534; /* nobody */
pwd->pw_gecos = buffer;
pwd->pw_passwd = (char*) "*"; /* locked */
pwd->pw_dir = (char*) "/";
pwd->pw_shell = (char*) "/sbin/nologin";
*errnop = 0;
return NSS_STATUS_SUCCESS;
not_found:
*errnop = 0;
return NSS_STATUS_NOTFOUND;
fail:
*errnop = -r;
return NSS_STATUS_UNAVAIL;
}
enum nss_status _nss_mymachines_getpwuid_r(
uid_t uid,
struct passwd *pwd,
char *buffer, size_t buflen,
int *errnop) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_bus_message_unref_ sd_bus_message* reply = NULL;
_cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
const char *machine, *object;
uint32_t mapped;
int r;
if (!uid_is_valid(uid)) {
r = -EINVAL;
goto fail;
}
/* We consider all uids < 65536 host uids */
if (uid < 0x10000)
goto not_found;
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"MapToMachineUser",
&error,
&reply,
"u",
(uint32_t) uid);
if (r < 0) {
if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_USER_MAPPING))
goto not_found;
goto fail;
}
r = sd_bus_message_read(reply, "sou", &machine, &object, &mapped);
if (r < 0)
goto fail;
if (snprintf(buffer, buflen, "vu-%s-" UID_FMT, machine, (uid_t) mapped) >= (int) buflen) {
*errnop = ENOMEM;
return NSS_STATUS_TRYAGAIN;
}
pwd->pw_name = buffer;
pwd->pw_uid = uid;
pwd->pw_gid = 65534; /* nobody */
pwd->pw_gecos = buffer;
pwd->pw_passwd = (char*) "*"; /* locked */
pwd->pw_dir = (char*) "/";
pwd->pw_shell = (char*) "/sbin/nologin";
*errnop = 0;
return NSS_STATUS_SUCCESS;
not_found:
*errnop = 0;
return NSS_STATUS_NOTFOUND;
fail:
*errnop = -r;
return NSS_STATUS_UNAVAIL;
}
enum nss_status _nss_mymachines_getgrnam_r(
const char *name,
struct group *gr,
char *buffer, size_t buflen,
int *errnop) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_bus_message_unref_ sd_bus_message* reply = NULL;
_cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
const char *p, *e, *machine;
uint32_t mapped;
uid_t gid;
size_t l;
int r;
assert(name);
assert(gr);
p = startswith(name, "vg-");
if (!p)
goto not_found;
e = strrchr(p, '-');
if (!e || e == p)
goto not_found;
if (e - p > HOST_NAME_MAX - 1) /* -1 for the last dash */
goto not_found;
r = parse_gid(e + 1, &gid);
if (r < 0)
goto not_found;
machine = strndupa(p, e - p);
if (!machine_name_is_valid(machine))
goto not_found;
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"MapFromMachineGroup",
&error,
&reply,
"su",
machine, (uint32_t) gid);
if (r < 0) {
if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_GROUP_MAPPING))
goto not_found;
goto fail;
}
r = sd_bus_message_read(reply, "u", &mapped);
if (r < 0)
goto fail;
l = sizeof(char*) + strlen(name) + 1;
if (buflen < l) {
*errnop = ENOMEM;
return NSS_STATUS_TRYAGAIN;
}
memzero(buffer, sizeof(char*));
strcpy(buffer + sizeof(char*), name);
gr->gr_name = buffer + sizeof(char*);
gr->gr_gid = gid;
gr->gr_passwd = (char*) "*"; /* locked */
gr->gr_mem = (char**) buffer;
*errnop = 0;
return NSS_STATUS_SUCCESS;
not_found:
*errnop = 0;
return NSS_STATUS_NOTFOUND;
fail:
*errnop = -r;
return NSS_STATUS_UNAVAIL;
}
enum nss_status _nss_mymachines_getgrgid_r(
gid_t gid,
struct group *gr,
char *buffer, size_t buflen,
int *errnop) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_bus_message_unref_ sd_bus_message* reply = NULL;
_cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
const char *machine, *object;
uint32_t mapped;
int r;
if (!gid_is_valid(gid)) {
r = -EINVAL;
goto fail;
}
/* We consider all gids < 65536 host gids */
if (gid < 0x10000)
goto not_found;
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"MapToMachineGroup",
&error,
&reply,
"u",
(uint32_t) gid);
if (r < 0) {
if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_GROUP_MAPPING))
goto not_found;
goto fail;
}
r = sd_bus_message_read(reply, "sou", &machine, &object, &mapped);
if (r < 0)
goto fail;
if (buflen < sizeof(char*) + 1) {
*errnop = ENOMEM;
return NSS_STATUS_TRYAGAIN;
}
memzero(buffer, sizeof(char*));
if (snprintf(buffer + sizeof(char*), buflen - sizeof(char*), "vg-%s-" GID_FMT, machine, (gid_t) mapped) >= (int) buflen) {
*errnop = ENOMEM;
return NSS_STATUS_TRYAGAIN;
}
gr->gr_name = buffer + sizeof(char*);
gr->gr_gid = gid;
gr->gr_passwd = (char*) "*"; /* locked */
gr->gr_mem = (char**) buffer;
*errnop = 0;
return NSS_STATUS_SUCCESS;
not_found:
*errnop = 0;
return NSS_STATUS_NOTFOUND;
fail:
*errnop = -r;
return NSS_STATUS_UNAVAIL;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_1746_0 |
crossvul-cpp_data_bad_2346_0 | /*
* Copyright (C) 2007-2008 Sourcefire, Inc.
*
* Authors: Alberto Wu, Tomasz Kojm
*
* 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.
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
/*
#define _XOPEN_SOURCE 500
*/
#include <stdio.h>
#include <stdlib.h>
#if HAVE_STRING_H
#include <string.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <time.h>
#include <stdarg.h>
#include "cltypes.h"
#include "clamav.h"
#include "others.h"
#include "pe.h"
#include "petite.h"
#include "fsg.h"
#include "spin.h"
#include "upx.h"
#include "yc.h"
#include "aspack.h"
#include "wwunpack.h"
#include "unsp.h"
#include "scanners.h"
#include "str.h"
#include "execs.h"
#include "mew.h"
#include "upack.h"
#include "matcher.h"
#include "matcher-hash.h"
#include "disasm.h"
#include "special.h"
#include "ishield.h"
#include "asn1.h"
#include "json_api.h"
#define DCONF ctx->dconf->pe
#define PE_IMAGE_DOS_SIGNATURE 0x5a4d /* MZ */
#define PE_IMAGE_DOS_SIGNATURE_OLD 0x4d5a /* ZM */
#define PE_IMAGE_NT_SIGNATURE 0x00004550
#define PE32_SIGNATURE 0x010b
#define PE32P_SIGNATURE 0x020b
#define optional_hdr64 pe_opt.opt64
#define optional_hdr32 pe_opt.opt32
#define UPX_NRV2B "\x11\xdb\x11\xc9\x01\xdb\x75\x07\x8b\x1e\x83\xee\xfc\x11\xdb\x11\xc9\x11\xc9\x75\x20\x41\x01\xdb"
#define UPX_NRV2D "\x83\xf0\xff\x74\x78\xd1\xf8\x89\xc5\xeb\x0b\x01\xdb\x75\x07\x8b\x1e\x83\xee\xfc\x11\xdb\x11\xc9"
#define UPX_NRV2E "\xeb\x52\x31\xc9\x83\xe8\x03\x72\x11\xc1\xe0\x08\x8a\x06\x46\x83\xf0\xff\x74\x75\xd1\xf8\x89\xc5"
#define UPX_LZMA1 "\x56\x83\xc3\x04\x53\x50\xc7\x03\x03\x00\x02\x00\x90\x90\x90\x55\x57\x56\x53\x83"
#define UPX_LZMA2 "\x56\x83\xc3\x04\x53\x50\xc7\x03\x03\x00\x02\x00\x90\x90\x90\x90\x90\x55\x57\x56"
#define EC32(x) ((uint32_t)cli_readint32(&(x))) /* Convert little endian to host */
#define EC16(x) ((uint16_t)cli_readint16(&(x)))
/* lower and upper bondary alignment (size vs offset) */
#define PEALIGN(o,a) (((a))?(((o)/(a))*(a)):(o))
#define PESALIGN(o,a) (((a))?(((o)/(a)+((o)%(a)!=0))*(a)):(o))
#define CLI_UNPSIZELIMITS(NAME,CHK) \
if(cli_checklimits(NAME, ctx, (CHK), 0, 0)!=CL_CLEAN) { \
free(exe_sections); \
return CL_CLEAN; \
}
#define CLI_UNPTEMP(NAME,FREEME) \
if(!(tempfile = cli_gentemp(ctx->engine->tmpdir))) { \
cli_multifree FREEME; \
return CL_EMEM; \
} \
if((ndesc = open(tempfile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) { \
cli_dbgmsg(NAME": Can't create file %s\n", tempfile); \
free(tempfile); \
cli_multifree FREEME; \
return CL_ECREAT; \
}
#define CLI_TMPUNLK() if(!ctx->engine->keeptmp) { \
if (cli_unlink(tempfile)) { \
free(tempfile); \
return CL_EUNLINK; \
} \
}
#ifdef HAVE__INTERNAL__SHA_COLLECT
#define SHA_OFF do { ctx->sha_collect = -1; } while(0)
#define SHA_RESET do { ctx->sha_collect = sha_collect; } while(0)
#else
#define SHA_OFF do {} while(0)
#define SHA_RESET do {} while(0)
#endif
#define FSGCASE(NAME,FREESEC) \
case 0: /* Unpacked and NOT rebuilt */ \
cli_dbgmsg(NAME": Successfully decompressed\n"); \
close(ndesc); \
if (cli_unlink(tempfile)) { \
free(exe_sections); \
free(tempfile); \
FREESEC; \
return CL_EUNLINK; \
} \
free(tempfile); \
FREESEC; \
found = 0; \
upx_success = 1; \
break; /* FSG ONLY! - scan raw data after upx block */
#define SPINCASE() \
case 2: \
free(spinned); \
close(ndesc); \
if (cli_unlink(tempfile)) { \
free(exe_sections); \
free(tempfile); \
return CL_EUNLINK; \
} \
cli_dbgmsg("PESpin: Size exceeded\n"); \
free(tempfile); \
break; \
#define CLI_UNPRESULTS_(NAME,FSGSTUFF,EXPR,GOOD,FREEME) \
switch(EXPR) { \
case GOOD: /* Unpacked and rebuilt */ \
if(ctx->engine->keeptmp) \
cli_dbgmsg(NAME": Unpacked and rebuilt executable saved in %s\n", tempfile); \
else \
cli_dbgmsg(NAME": Unpacked and rebuilt executable\n"); \
cli_multifree FREEME; \
free(exe_sections); \
lseek(ndesc, 0, SEEK_SET); \
cli_dbgmsg("***** Scanning rebuilt PE file *****\n"); \
SHA_OFF; \
if(cli_magic_scandesc(ndesc, ctx) == CL_VIRUS) { \
close(ndesc); \
CLI_TMPUNLK(); \
free(tempfile); \
SHA_RESET; \
return CL_VIRUS; \
} \
SHA_RESET; \
close(ndesc); \
CLI_TMPUNLK(); \
free(tempfile); \
return CL_CLEAN; \
\
FSGSTUFF; \
\
default: \
cli_dbgmsg(NAME": Unpacking failed\n"); \
close(ndesc); \
if (cli_unlink(tempfile)) { \
free(exe_sections); \
free(tempfile); \
cli_multifree FREEME; \
return CL_EUNLINK; \
} \
cli_multifree FREEME; \
free(tempfile); \
}
#define CLI_UNPRESULTS(NAME,EXPR,GOOD,FREEME) CLI_UNPRESULTS_(NAME,(void)0,EXPR,GOOD,FREEME)
#define CLI_UNPRESULTSFSG1(NAME,EXPR,GOOD,FREEME) CLI_UNPRESULTS_(NAME,FSGCASE(NAME,free(sections)),EXPR,GOOD,FREEME)
#define CLI_UNPRESULTSFSG2(NAME,EXPR,GOOD,FREEME) CLI_UNPRESULTS_(NAME,FSGCASE(NAME,(void)0),EXPR,GOOD,FREEME)
#define DETECT_BROKEN_PE (DETECT_BROKEN && !ctx->corrupted_input)
extern const unsigned int hashlen[];
struct offset_list {
uint32_t offset;
struct offset_list *next;
};
static void cli_multifree(void *f, ...) {
void *ff;
va_list ap;
free(f);
va_start(ap, f);
while((ff=va_arg(ap, void*))) free(ff);
va_end(ap);
}
struct vinfo_list {
uint32_t rvas[16];
unsigned int count;
};
static int versioninfo_cb(void *opaque, uint32_t type, uint32_t name, uint32_t lang, uint32_t rva) {
struct vinfo_list *vlist = (struct vinfo_list *)opaque;
cli_dbgmsg("versioninfo_cb: type: %x, name: %x, lang: %x, rva: %x\n", type, name, lang, rva);
vlist->rvas[vlist->count] = rva;
if(++vlist->count == sizeof(vlist->rvas) / sizeof(vlist->rvas[0]))
return 1;
return 0;
}
uint32_t cli_rawaddr(uint32_t rva, const struct cli_exe_section *shp, uint16_t nos, unsigned int *err, size_t fsize, uint32_t hdr_size)
{
int i, found = 0;
uint32_t ret;
if (rva<hdr_size) { /* Out of section EP - mapped to imagebase+rva */
if (rva >= fsize) {
*err=1;
return 0;
}
*err=0;
return rva;
}
for(i = nos-1; i >= 0; i--) {
if(shp[i].rsz && shp[i].rva <= rva && shp[i].rsz > rva - shp[i].rva) {
found = 1;
break;
}
}
if(!found) {
*err = 1;
return 0;
}
ret = rva - shp[i].rva + shp[i].raw;
*err = 0;
return ret;
}
/*
static int cli_ddump(int desc, int offset, int size, const char *file) {
int pos, ndesc, bread, sum = 0;
char buff[FILEBUFF];
cli_dbgmsg("in ddump()\n");
if((pos = lseek(desc, 0, SEEK_CUR)) == -1) {
cli_dbgmsg("Invalid descriptor\n");
return -1;
}
if(lseek(desc, offset, SEEK_SET) == -1) {
cli_dbgmsg("lseek() failed\n");
lseek(desc, pos, SEEK_SET);
return -1;
}
if((ndesc = open(file, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
cli_dbgmsg("Can't create file %s\n", file);
lseek(desc, pos, SEEK_SET);
return -1;
}
while((bread = cli_readn(desc, buff, FILEBUFF)) > 0) {
if(sum + bread >= size) {
if(write(ndesc, buff, size - sum) == -1) {
cli_dbgmsg("Can't write to file\n");
lseek(desc, pos, SEEK_SET);
close(ndesc);
cli_unlink(file);
return -1;
}
break;
} else {
if(write(ndesc, buff, bread) == -1) {
cli_dbgmsg("Can't write to file\n");
lseek(desc, pos, SEEK_SET);
close(ndesc);
cli_unlink(file);
return -1;
}
}
sum += bread;
}
close(ndesc);
lseek(desc, pos, SEEK_SET);
return 0;
}
*/
/*
void findres(uint32_t by_type, uint32_t by_name, uint32_t res_rva, cli_ctx *ctx, struct cli_exe_section *exe_sections, uint16_t nsections, uint32_t hdr_size, int (*cb)(void *, uint32_t, uint32_t, uint32_t, uint32_t), void *opaque)
callback based res lookup
by_type: lookup type
by_name: lookup name or (unsigned)-1 to look for any name
res_rva: base resource rva (i.e. dirs[2].VirtualAddress)
ctx, exe_sections, nsections, hdr_size: same as in scanpe
cb: the callback function executed on each successful match
opaque: an opaque pointer passed to the callback
the callback proto is
int pe_res_cballback (void *opaque, uint32_t type, uint32_t name, uint32_t lang, uint32_t rva);
the callback shall return 0 to continue the lookup or 1 to abort
*/
void findres(uint32_t by_type, uint32_t by_name, uint32_t res_rva, fmap_t *map, struct cli_exe_section *exe_sections, uint16_t nsections, uint32_t hdr_size, int (*cb)(void *, uint32_t, uint32_t, uint32_t, uint32_t), void *opaque) {
unsigned int err = 0;
uint32_t type, type_offs, name, name_offs, lang, lang_offs;
const uint8_t *resdir, *type_entry, *name_entry, *lang_entry ;
uint16_t type_cnt, name_cnt, lang_cnt;
if (!(resdir = fmap_need_off_once(map, cli_rawaddr(res_rva, exe_sections, nsections, &err, map->len, hdr_size), 16)) || err)
return;
type_cnt = (uint16_t)cli_readint16(resdir+12);
type_entry = resdir+16;
if(!(by_type>>31)) {
type_entry += type_cnt * 8;
type_cnt = (uint16_t)cli_readint16(resdir+14);
}
while(type_cnt--) {
if(!fmap_need_ptr_once(map, type_entry, 8))
return;
type = cli_readint32(type_entry);
type_offs = cli_readint32(type_entry+4);
if(type == by_type && (type_offs>>31)) {
type_offs &= 0x7fffffff;
if (!(resdir = fmap_need_off_once(map, cli_rawaddr(res_rva + type_offs, exe_sections, nsections, &err, map->len, hdr_size), 16)) || err)
return;
name_cnt = (uint16_t)cli_readint16(resdir+12);
name_entry = resdir+16;
if(by_name == 0xffffffff)
name_cnt += (uint16_t)cli_readint16(resdir+14);
else if(!(by_name>>31)) {
name_entry += name_cnt * 8;
name_cnt = (uint16_t)cli_readint16(resdir+14);
}
while(name_cnt--) {
if(!fmap_need_ptr_once(map, name_entry, 8))
return;
name = cli_readint32(name_entry);
name_offs = cli_readint32(name_entry+4);
if((by_name == 0xffffffff || name == by_name) && (name_offs>>31)) {
name_offs &= 0x7fffffff;
if (!(resdir = fmap_need_off_once(map, cli_rawaddr(res_rva + name_offs, exe_sections, nsections, &err, map->len, hdr_size), 16)) || err)
return;
lang_cnt = (uint16_t)cli_readint16(resdir+12) + (uint16_t)cli_readint16(resdir+14);
lang_entry = resdir+16;
while(lang_cnt--) {
if(!fmap_need_ptr_once(map, lang_entry, 8))
return;
lang = cli_readint32(lang_entry);
lang_offs = cli_readint32(lang_entry+4);
if(!(lang_offs >>31)) {
if(cb(opaque, type, name, lang, res_rva + lang_offs))
return;
}
lang_entry += 8;
}
}
name_entry += 8;
}
return; /* FIXME: unless we want to find ALL types */
}
type_entry += 8;
}
}
static void cli_parseres_special(uint32_t base, uint32_t rva, fmap_t *map, struct cli_exe_section *exe_sections, uint16_t nsections, size_t fsize, uint32_t hdr_size, unsigned int level, uint32_t type, unsigned int *maxres, struct swizz_stats *stats) {
unsigned int err = 0, i;
const uint8_t *resdir;
const uint8_t *entry, *oentry;
uint16_t named, unnamed;
uint32_t rawaddr = cli_rawaddr(rva, exe_sections, nsections, &err, fsize, hdr_size);
uint32_t entries;
if(level>2 || !*maxres) return;
*maxres-=1;
if(err || !(resdir = fmap_need_off_once(map, rawaddr, 16)))
return;
named = (uint16_t)cli_readint16(resdir+12);
unnamed = (uint16_t)cli_readint16(resdir+14);
entries = /*named+*/unnamed;
if (!entries)
return;
rawaddr += named*8; /* skip named */
/* this is just used in a heuristic detection, so don't give error on failure */
if(!(entry = fmap_need_off(map, rawaddr+16, entries*8))) {
cli_dbgmsg("cli_parseres_special: failed to read resource directory at:%lu\n", (unsigned long)rawaddr+16);
return;
}
oentry = entry;
/*for (i=0; i<named; i++) {
uint32_t id, offs;
id = cli_readint32(entry);
offs = cli_readint32(entry+4);
if(offs>>31)
cli_parseres( base, base + (offs&0x7fffffff), srcfd, exe_sections, nsections, fsize, hdr_size, level+1, type, maxres, stats);
entry+=8;
}*/
for (i=0; i<unnamed; i++, entry += 8) {
uint32_t id, offs;
if (stats->errors >= SWIZZ_MAXERRORS) {
cli_dbgmsg("cli_parseres_special: resources broken, ignoring\n");
return;
}
id = cli_readint32(entry)&0x7fffffff;
if(level==0) {
type = 0;
switch(id) {
case 4: /* menu */
case 5: /* dialog */
case 6: /* string */
case 11:/* msgtable */
type = id;
break;
case 16:
type = id;
/* 14: version */
stats->has_version = 1;
break;
case 24: /* manifest */
stats->has_manifest = 1;
break;
/* otherwise keep it 0, we don't want it */
}
}
if (!type) {
/* if we are not interested in this type, skip */
continue;
}
offs = cli_readint32(entry+4);
if(offs>>31)
cli_parseres_special(base, base + (offs&0x7fffffff), map, exe_sections, nsections, fsize, hdr_size, level+1, type, maxres, stats);
else {
offs = cli_readint32(entry+4);
rawaddr = cli_rawaddr(base + offs, exe_sections, nsections, &err, fsize, hdr_size);
if (!err && (resdir = fmap_need_off_once(map, rawaddr, 16))) {
uint32_t isz = cli_readint32(resdir+4);
const uint8_t *str;
rawaddr = cli_rawaddr(cli_readint32(resdir), exe_sections, nsections, &err, fsize, hdr_size);
if (err || !isz || isz >= fsize || rawaddr+isz >= fsize) {
cli_dbgmsg("cli_parseres_special: invalid resource table entry: %lu + %lu\n",
(unsigned long)rawaddr,
(unsigned long)isz);
stats->errors++;
continue;
}
if ((id&0xff) != 0x09) /* english res only */
continue;
if((str = fmap_need_off_once(map, rawaddr, isz)))
cli_detect_swizz_str(str, isz, stats, type);
}
}
}
fmap_unneed_ptr(map, oentry, entries*8);
}
static unsigned int cli_hashsect(fmap_t *map, struct cli_exe_section *s, unsigned char **digest, int * foundhash, int * foundwild)
{
const void *hashme;
if (s->rsz > CLI_MAX_ALLOCATION) {
cli_dbgmsg("cli_hashsect: skipping hash calculation for too big section\n");
return 0;
}
if(!s->rsz) return 0;
if(!(hashme=fmap_need_off_once(map, s->raw, s->rsz))) {
cli_dbgmsg("cli_hashsect: unable to read section data\n");
return 0;
}
if(foundhash[CLI_HASH_MD5] || foundwild[CLI_HASH_MD5])
cl_hash_data("md5", hashme, s->rsz, digest[CLI_HASH_MD5], NULL);
if(foundhash[CLI_HASH_SHA1] || foundwild[CLI_HASH_SHA1])
cl_sha1(hashme, s->rsz, digest[CLI_HASH_SHA1], NULL);
if(foundhash[CLI_HASH_SHA256] || foundwild[CLI_HASH_SHA256])
cl_sha256(hashme, s->rsz, digest[CLI_HASH_SHA256], NULL);
return 1;
}
/* check hash section sigs */
static int scan_pe_mdb (cli_ctx * ctx, struct cli_exe_section *exe_section)
{
struct cli_matcher * mdb_sect = ctx->engine->hm_mdb;
unsigned char * hashset[CLI_HASH_AVAIL_TYPES];
const char * virname = NULL;
int foundsize[CLI_HASH_AVAIL_TYPES];
int foundwild[CLI_HASH_AVAIL_TYPES];
enum CLI_HASH_TYPE type;
int ret = CL_CLEAN;
unsigned char * md5 = NULL;
/* pick hashtypes to generate */
for(type = CLI_HASH_MD5; type < CLI_HASH_AVAIL_TYPES; type++) {
foundsize[type] = cli_hm_have_size(mdb_sect, type, exe_section->rsz);
foundwild[type] = cli_hm_have_wild(mdb_sect, type);
if(foundsize[type] || foundwild[type]) {
hashset[type] = cli_malloc(hashlen[type]);
if(!hashset[type]) {
cli_errmsg("scan_pe: cli_malloc failed!\n");
for(; type > 0;)
free(hashset[--type]);
return CL_EMEM;
}
}
else {
hashset[type] = NULL;
}
}
/* Generate hashes */
cli_hashsect(*ctx->fmap, exe_section, hashset, foundsize, foundwild);
/* Print hash */
if (cli_debug_flag) {
md5 = hashset[CLI_HASH_MD5];
if (md5) {
cli_dbgmsg("MDB: %u:%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n",
exe_section->rsz, md5[0], md5[1], md5[2], md5[3], md5[4], md5[5], md5[6], md5[7],
md5[8], md5[9], md5[10], md5[11], md5[12], md5[13], md5[14], md5[15]);
} else if (cli_always_gen_section_hash) {
const void *hashme = fmap_need_off_once(*ctx->fmap, exe_section->raw, exe_section->rsz);
if (!(hashme)) {
cli_errmsg("scan_pe_mdb: unable to read section data\n");
ret = CL_EREAD;
goto end;
}
md5 = cli_malloc(16);
if (!(md5)) {
cli_errmsg("scan_pe_mdb: cli_malloc failed!\n");
ret = CL_EMEM;
goto end;
}
cl_hash_data("md5", hashme, exe_section->rsz, md5, NULL);
cli_dbgmsg("MDB: %u:%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n",
exe_section->rsz, md5[0], md5[1], md5[2], md5[3], md5[4], md5[5], md5[6], md5[7],
md5[8], md5[9], md5[10], md5[11], md5[12], md5[13], md5[14], md5[15]);
free(md5);
} else {
cli_dbgmsg("MDB: %u:notgenerated\n", exe_section->rsz);
}
}
/* Do scans */
for(type = CLI_HASH_MD5; type < CLI_HASH_AVAIL_TYPES; type++) {
if(foundsize[type] && cli_hm_scan(hashset[type], exe_section->rsz, &virname, mdb_sect, type) == CL_VIRUS) {
cli_append_virus(ctx, virname);
ret = CL_VIRUS;
if (!SCAN_ALL) {
break;
}
}
if(foundwild[type] && cli_hm_scan_wild(hashset[type], &virname, mdb_sect, type) == CL_VIRUS) {
cli_append_virus(ctx, virname);
ret = CL_VIRUS;
if (!SCAN_ALL) {
break;
}
}
}
end:
for(type = CLI_HASH_AVAIL_TYPES; type > 0;)
free(hashset[--type]);
return ret;
}
#if HAVE_JSON
static struct json_object *get_pe_property(cli_ctx *ctx)
{
struct json_object *pe;
if (!(ctx) || !(ctx->wrkproperty))
return NULL;
if (!json_object_object_get_ex(ctx->wrkproperty, "PE", &pe)) {
pe = json_object_new_object();
if (!(pe))
return NULL;
json_object_object_add(ctx->wrkproperty, "PE", pe);
}
return pe;
}
static void pe_add_heuristic_property(cli_ctx *ctx, const char *key)
{
struct json_object *heuristics;
struct json_object *pe;
struct json_object *str;
pe = get_pe_property(ctx);
if (!(pe))
return;
if (!json_object_object_get_ex(pe, "Heuristics", &heuristics)) {
heuristics = json_object_new_array();
if (!(heuristics))
return;
json_object_object_add(pe, "Heuristics", heuristics);
}
str = json_object_new_string(key);
if (!(str))
return;
json_object_array_add(heuristics, str);
}
static struct json_object *get_section_json(cli_ctx *ctx)
{
struct json_object *pe;
struct json_object *section;
pe = get_pe_property(ctx);
if (!(pe))
return NULL;
if (!json_object_object_get_ex(pe, "Sections", §ion)) {
section = json_object_new_array();
if (!(section))
return NULL;
json_object_object_add(pe, "Sections", section);
}
return section;
}
static void add_section_info(cli_ctx *ctx, struct cli_exe_section *s)
{
struct json_object *sections, *section, *obj;
char address[16];
sections = get_section_json(ctx);
if (!(sections))
return;
section = json_object_new_object();
if (!(section))
return;
obj = json_object_new_int((int32_t)(s->rsz));
if (!(obj))
return;
json_object_object_add(section, "RawSize", obj);
obj = json_object_new_int((int32_t)(s->raw));
if (!(obj))
return;
json_object_object_add(section, "RawOffset", obj);
snprintf(address, sizeof(address), "0x%08x", s->rva);
obj = json_object_new_string(address);
if (!(obj))
return;
json_object_object_add(section, "VirtualAddress", obj);
obj = json_object_new_boolean((s->chr & 0x20000000) == 0x20000000);
if ((obj))
json_object_object_add(section, "Executable", obj);
obj = json_object_new_boolean((s->chr & 0x80000000) == 0x80000000);
if ((obj))
json_object_object_add(section, "Writable", obj);
obj = json_object_new_boolean(s->urva>>31 || s->uvsz>>31 || (s->rsz && s->uraw>>31) || s->ursz>>31);
if ((obj))
json_object_object_add(section, "Signed", obj);
json_object_array_add(sections, section);
}
#endif
int cli_scanpe(cli_ctx *ctx)
{
uint16_t e_magic; /* DOS signature ("MZ") */
uint16_t nsections;
uint32_t e_lfanew; /* address of new exe header */
uint32_t ep, vep; /* entry point (raw, virtual) */
uint8_t polipos = 0;
time_t timestamp;
struct pe_image_file_hdr file_hdr;
union {
struct pe_image_optional_hdr64 opt64;
struct pe_image_optional_hdr32 opt32;
} pe_opt;
struct pe_image_section_hdr *section_hdr;
char sname[9], epbuff[4096], *tempfile;
uint32_t epsize;
ssize_t bytes, at;
unsigned int i, found, upx_success = 0, min = 0, max = 0, err, overlays = 0;
unsigned int ssize = 0, dsize = 0, dll = 0, pe_plus = 0, corrupted_cur;
int (*upxfn)(const char *, uint32_t, char *, uint32_t *, uint32_t, uint32_t, uint32_t) = NULL;
const char *src = NULL;
char *dest = NULL;
int ndesc, ret = CL_CLEAN, upack = 0, native=0;
size_t fsize;
uint32_t valign, falign, hdr_size, j;
struct cli_exe_section *exe_sections;
char timestr[32];
struct pe_image_data_dir *dirs;
struct cli_bc_ctx *bc_ctx;
fmap_t *map;
struct cli_pe_hook_data pedata;
#ifdef HAVE__INTERNAL__SHA_COLLECT
int sha_collect = ctx->sha_collect;
#endif
const char *archtype=NULL, *subsystem=NULL;
uint32_t viruses_found = 0;
#if HAVE_JSON
int toval = 0;
struct json_object *pe_json=NULL;
char jsonbuf[128];
#endif
if(!ctx) {
cli_errmsg("cli_scanpe: ctx == NULL\n");
return CL_ENULLARG;
}
#if HAVE_JSON
if (cli_json_timeout_cycle_check(ctx, &toval) != CL_SUCCESS) {
return CL_ETIMEOUT;
}
if (ctx->options & CL_SCAN_FILE_PROPERTIES) {
pe_json = get_pe_property(ctx);
}
#endif
map = *ctx->fmap;
if(fmap_readn(map, &e_magic, 0, sizeof(e_magic)) != sizeof(e_magic)) {
cli_dbgmsg("Can't read DOS signature\n");
return CL_CLEAN;
}
if(EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE && EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE_OLD) {
cli_dbgmsg("Invalid DOS signature\n");
return CL_CLEAN;
}
if(fmap_readn(map, &e_lfanew, 58 + sizeof(e_magic), sizeof(e_lfanew)) != sizeof(e_lfanew)) {
cli_dbgmsg("Can't read new header address\n");
/* truncated header? */
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
e_lfanew = EC32(e_lfanew);
cli_dbgmsg("e_lfanew == %d\n", e_lfanew);
if(!e_lfanew) {
cli_dbgmsg("Not a PE file\n");
return CL_CLEAN;
}
if(fmap_readn(map, &file_hdr, e_lfanew, sizeof(struct pe_image_file_hdr)) != sizeof(struct pe_image_file_hdr)) {
/* bad information in e_lfanew - probably not a PE file */
cli_dbgmsg("Can't read file header\n");
return CL_CLEAN;
}
if(EC32(file_hdr.Magic) != PE_IMAGE_NT_SIGNATURE) {
cli_dbgmsg("Invalid PE signature (probably NE file)\n");
return CL_CLEAN;
}
if(EC16(file_hdr.Characteristics) & 0x2000) {
#if HAVE_JSON
if ((pe_json))
cli_jsonstr(pe_json, "Type", "DLL");
#endif
cli_dbgmsg("File type: DLL\n");
dll = 1;
} else if(EC16(file_hdr.Characteristics) & 0x01) {
#if HAVE_JSON
if ((pe_json))
cli_jsonstr(pe_json, "Type", "EXE");
#endif
cli_dbgmsg("File type: Executable\n");
}
switch(EC16(file_hdr.Machine)) {
case 0x0:
archtype = "Unknown";
break;
case 0x14c:
archtype = "80386";
break;
case 0x14d:
archtype = "80486";
break;
case 0x14e:
archtype = "80586";
break;
case 0x160:
archtype = "R30000 (big-endian)";
break;
case 0x162:
archtype = "R3000";
break;
case 0x166:
archtype = "R4000";
break;
case 0x168:
archtype = "R10000";
break;
case 0x184:
archtype = "DEC Alpha AXP";
break;
case 0x284:
archtype = "DEC Alpha AXP 64bit";
break;
case 0x1f0:
archtype = "PowerPC";
break;
case 0x200:
archtype = "IA64";
break;
case 0x268:
archtype = "M68k";
break;
case 0x266:
archtype = "MIPS16";
break;
case 0x366:
archtype = "MIPS+FPU";
break;
case 0x466:
archtype = "MIPS16+FPU";
break;
case 0x1a2:
archtype = "Hitachi SH3";
break;
case 0x1a3:
archtype = "Hitachi SH3-DSP";
break;
case 0x1a4:
archtype = "Hitachi SH3-E";
break;
case 0x1a6:
archtype = "Hitachi SH4";
break;
case 0x1a8:
archtype = "Hitachi SH5";
break;
case 0x1c0:
archtype = "ARM";
break;
case 0x1c2:
archtype = "THUMB";
break;
case 0x1d3:
archtype = "AM33";
break;
case 0x520:
archtype = "Infineon TriCore";
break;
case 0xcef:
archtype = "CEF";
break;
case 0xebc:
archtype = "EFI Byte Code";
break;
case 0x9041:
archtype = "M32R";
break;
case 0xc0ee:
archtype = "CEEE";
break;
case 0x8664:
archtype = "AMD64";
break;
default:
archtype = "Unknown";
}
if ((archtype)) {
cli_dbgmsg("Machine type: %s\n", archtype);
#if HAVE_JSON
cli_jsonstr(pe_json, "ArchType", archtype);
#endif
}
nsections = EC16(file_hdr.NumberOfSections);
if(nsections < 1 || nsections > 96) {
#if HAVE_JSON
pe_add_heuristic_property(ctx, "BadNumberOfSections");
#endif
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
if(!ctx->corrupted_input) {
if(nsections)
cli_warnmsg("PE file contains %d sections\n", nsections);
else
cli_warnmsg("PE file contains no sections\n");
}
return CL_CLEAN;
}
cli_dbgmsg("NumberOfSections: %d\n", nsections);
timestamp = (time_t) EC32(file_hdr.TimeDateStamp);
cli_dbgmsg("TimeDateStamp: %s", cli_ctime(×tamp, timestr, sizeof(timestr)));
#if HAVE_JSON
cli_jsonstr(pe_json, "TimeDateStamp", cli_ctime(×tamp, timestr, sizeof(timestr)));
#endif
cli_dbgmsg("SizeOfOptionalHeader: %x\n", EC16(file_hdr.SizeOfOptionalHeader));
#if HAVE_JSON
cli_jsonint(pe_json, "SizeOfOptionalHeader", EC16(file_hdr.SizeOfOptionalHeader));
#endif
if (EC16(file_hdr.SizeOfOptionalHeader) < sizeof(struct pe_image_optional_hdr32)) {
#if HAVE_JSON
pe_add_heuristic_property(ctx, "BadOptionalHeaderSize");
#endif
cli_dbgmsg("SizeOfOptionalHeader too small\n");
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
at = e_lfanew + sizeof(struct pe_image_file_hdr);
if(fmap_readn(map, &optional_hdr32, at, sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr32)) {
cli_dbgmsg("Can't read optional file header\n");
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
at += sizeof(struct pe_image_optional_hdr32);
/* This will be a chicken and egg problem until we drop 9x */
if(EC16(optional_hdr64.Magic)==PE32P_SIGNATURE) {
#if HAVE_JSON
pe_add_heuristic_property(ctx, "BadOptionalHeaderSizePE32Plus");
#endif
if(EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr64)) {
/* FIXME: need to play around a bit more with xp64 */
cli_dbgmsg("Incorrect SizeOfOptionalHeader for PE32+\n");
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
pe_plus = 1;
}
if(!pe_plus) { /* PE */
if (EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr32)) {
/* Seek to the end of the long header */
at += EC16(file_hdr.SizeOfOptionalHeader)-sizeof(struct pe_image_optional_hdr32);
}
if(DCONF & PE_CONF_UPACK)
upack = (EC16(file_hdr.SizeOfOptionalHeader)==0x148);
vep = EC32(optional_hdr32.AddressOfEntryPoint);
hdr_size = EC32(optional_hdr32.SizeOfHeaders);
cli_dbgmsg("File format: PE\n");
cli_dbgmsg("MajorLinkerVersion: %d\n", optional_hdr32.MajorLinkerVersion);
cli_dbgmsg("MinorLinkerVersion: %d\n", optional_hdr32.MinorLinkerVersion);
cli_dbgmsg("SizeOfCode: 0x%x\n", EC32(optional_hdr32.SizeOfCode));
cli_dbgmsg("SizeOfInitializedData: 0x%x\n", EC32(optional_hdr32.SizeOfInitializedData));
cli_dbgmsg("SizeOfUninitializedData: 0x%x\n", EC32(optional_hdr32.SizeOfUninitializedData));
cli_dbgmsg("AddressOfEntryPoint: 0x%x\n", vep);
cli_dbgmsg("BaseOfCode: 0x%x\n", EC32(optional_hdr32.BaseOfCode));
cli_dbgmsg("SectionAlignment: 0x%x\n", EC32(optional_hdr32.SectionAlignment));
cli_dbgmsg("FileAlignment: 0x%x\n", EC32(optional_hdr32.FileAlignment));
cli_dbgmsg("MajorSubsystemVersion: %d\n", EC16(optional_hdr32.MajorSubsystemVersion));
cli_dbgmsg("MinorSubsystemVersion: %d\n", EC16(optional_hdr32.MinorSubsystemVersion));
cli_dbgmsg("SizeOfImage: 0x%x\n", EC32(optional_hdr32.SizeOfImage));
cli_dbgmsg("SizeOfHeaders: 0x%x\n", hdr_size);
cli_dbgmsg("NumberOfRvaAndSizes: %d\n", EC32(optional_hdr32.NumberOfRvaAndSizes));
dirs = optional_hdr32.DataDirectory;
#if HAVE_JSON
cli_jsonint(pe_json, "MajorLinkerVersion", optional_hdr32.MajorLinkerVersion);
cli_jsonint(pe_json, "MinorLinkerVersion", optional_hdr32.MinorLinkerVersion);
cli_jsonint(pe_json, "SizeOfCode", EC32(optional_hdr32.SizeOfCode));
cli_jsonint(pe_json, "SizeOfInitializedData", EC32(optional_hdr32.SizeOfInitializedData));
cli_jsonint(pe_json, "SizeOfUninitializedData", EC32(optional_hdr32.SizeOfUninitializedData));
cli_jsonint(pe_json, "NumberOfRvaAndSizes", EC32(optional_hdr32.NumberOfRvaAndSizes));
cli_jsonint(pe_json, "MajorSubsystemVersion", EC16(optional_hdr32.MajorSubsystemVersion));
cli_jsonint(pe_json, "MinorSubsystemVersion", EC16(optional_hdr32.MinorSubsystemVersion));
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr32.BaseOfCode));
cli_jsonstr(pe_json, "BaseOfCode", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr32.SectionAlignment));
cli_jsonstr(pe_json, "SectionAlignment", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr32.FileAlignment));
cli_jsonstr(pe_json, "FileAlignment", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr32.SizeOfImage));
cli_jsonstr(pe_json, "SizeOfImage", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", hdr_size);
cli_jsonstr(pe_json, "SizeOfHeaders", jsonbuf);
#endif
} else { /* PE+ */
/* read the remaining part of the header */
if(fmap_readn(map, &optional_hdr32 + 1, at, sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) {
cli_dbgmsg("Can't read optional file header\n");
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
at += sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32);
vep = EC32(optional_hdr64.AddressOfEntryPoint);
hdr_size = EC32(optional_hdr64.SizeOfHeaders);
cli_dbgmsg("File format: PE32+\n");
cli_dbgmsg("MajorLinkerVersion: %d\n", optional_hdr64.MajorLinkerVersion);
cli_dbgmsg("MinorLinkerVersion: %d\n", optional_hdr64.MinorLinkerVersion);
cli_dbgmsg("SizeOfCode: 0x%x\n", EC32(optional_hdr64.SizeOfCode));
cli_dbgmsg("SizeOfInitializedData: 0x%x\n", EC32(optional_hdr64.SizeOfInitializedData));
cli_dbgmsg("SizeOfUninitializedData: 0x%x\n", EC32(optional_hdr64.SizeOfUninitializedData));
cli_dbgmsg("AddressOfEntryPoint: 0x%x\n", vep);
cli_dbgmsg("BaseOfCode: 0x%x\n", EC32(optional_hdr64.BaseOfCode));
cli_dbgmsg("SectionAlignment: 0x%x\n", EC32(optional_hdr64.SectionAlignment));
cli_dbgmsg("FileAlignment: 0x%x\n", EC32(optional_hdr64.FileAlignment));
cli_dbgmsg("MajorSubsystemVersion: %d\n", EC16(optional_hdr64.MajorSubsystemVersion));
cli_dbgmsg("MinorSubsystemVersion: %d\n", EC16(optional_hdr64.MinorSubsystemVersion));
cli_dbgmsg("SizeOfImage: 0x%x\n", EC32(optional_hdr64.SizeOfImage));
cli_dbgmsg("SizeOfHeaders: 0x%x\n", hdr_size);
cli_dbgmsg("NumberOfRvaAndSizes: %d\n", EC32(optional_hdr64.NumberOfRvaAndSizes));
dirs = optional_hdr64.DataDirectory;
#if HAVE_JSON
cli_jsonint(pe_json, "MajorLinkerVersion", optional_hdr64.MajorLinkerVersion);
cli_jsonint(pe_json, "MinorLinkerVersion", optional_hdr64.MinorLinkerVersion);
cli_jsonint(pe_json, "SizeOfCode", EC32(optional_hdr64.SizeOfCode));
cli_jsonint(pe_json, "SizeOfInitializedData", EC32(optional_hdr64.SizeOfInitializedData));
cli_jsonint(pe_json, "SizeOfUninitializedData", EC32(optional_hdr64.SizeOfUninitializedData));
cli_jsonint(pe_json, "NumberOfRvaAndSizes", EC32(optional_hdr64.NumberOfRvaAndSizes));
cli_jsonint(pe_json, "MajorSubsystemVersion", EC16(optional_hdr64.MajorSubsystemVersion));
cli_jsonint(pe_json, "MinorSubsystemVersion", EC16(optional_hdr64.MinorSubsystemVersion));
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr64.BaseOfCode));
cli_jsonstr(pe_json, "BaseOfCode", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr64.SectionAlignment));
cli_jsonstr(pe_json, "SectionAlignment", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr64.FileAlignment));
cli_jsonstr(pe_json, "FileAlignment", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", EC32(optional_hdr64.SizeOfImage));
cli_jsonstr(pe_json, "SizeOfImage", jsonbuf);
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", hdr_size);
cli_jsonstr(pe_json, "SizeOfHeaders", jsonbuf);
#endif
}
#if HAVE_JSON
if (ctx->options & CL_SCAN_FILE_PROPERTIES) {
snprintf(jsonbuf, sizeof(jsonbuf), "0x%x", vep);
cli_jsonstr(pe_json, "EntryPoint", jsonbuf);
}
#endif
switch(pe_plus ? EC16(optional_hdr64.Subsystem) : EC16(optional_hdr32.Subsystem)) {
case 0:
subsystem = "Unknown";
break;
case 1:
subsystem = "Native (svc)";
native = 1;
break;
case 2:
subsystem = "Win32 GUI";
break;
case 3:
subsystem = "Win32 console";
break;
case 5:
subsystem = "OS/2 console";
break;
case 7:
subsystem = "POSIX console";
break;
case 8:
subsystem = "Native Win9x driver";
break;
case 9:
subsystem = "WinCE GUI";
break;
case 10:
subsystem = "EFI application";
break;
case 11:
subsystem = "EFI driver";
break;
case 12:
subsystem = "EFI runtime driver";
break;
case 13:
subsystem = "EFI ROM image";
break;
case 14:
subsystem = "Xbox";
break;
case 16:
subsystem = "Boot application";
break;
default:
subsystem = "Unknown";
}
cli_dbgmsg("Subsystem: %s\n", subsystem);
#if HAVE_JSON
cli_jsonstr(pe_json, "Subsystem", subsystem);
#endif
cli_dbgmsg("------------------------------------\n");
if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment)) || (pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment))%0x1000)) {
cli_dbgmsg("Bad virtual alignemnt\n");
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment)) || (pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment))%0x200)) {
cli_dbgmsg("Bad file alignemnt\n");
cli_append_virus(ctx, "Heuristics.Broken.Executable");
return CL_VIRUS;
}
fsize = map->len;
section_hdr = (struct pe_image_section_hdr *) cli_calloc(nsections, sizeof(struct pe_image_section_hdr));
if(!section_hdr) {
cli_dbgmsg("Can't allocate memory for section headers\n");
return CL_EMEM;
}
exe_sections = (struct cli_exe_section *) cli_calloc(nsections, sizeof(struct cli_exe_section));
if(!exe_sections) {
cli_dbgmsg("Can't allocate memory for section headers\n");
free(section_hdr);
return CL_EMEM;
}
valign = (pe_plus)?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment);
falign = (pe_plus)?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment);
if(fmap_readn(map, section_hdr, at, sizeof(struct pe_image_section_hdr)*nsections) != (int)(nsections*sizeof(struct pe_image_section_hdr))) {
cli_dbgmsg("Can't read section header\n");
cli_dbgmsg("Possibly broken PE file\n");
free(section_hdr);
free(exe_sections);
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
at += sizeof(struct pe_image_section_hdr)*nsections;
for(i = 0; falign!=0x200 && i<nsections; i++) {
/* file alignment fallback mode - blah */
if (falign && section_hdr[i].SizeOfRawData && EC32(section_hdr[i].PointerToRawData)%falign && !(EC32(section_hdr[i].PointerToRawData)%0x200)) {
cli_dbgmsg("Found misaligned section, using 0x200\n");
falign = 0x200;
}
}
hdr_size = PESALIGN(hdr_size, valign); /* Aligned headers virtual size */
#if HAVE_JSON
cli_jsonint(pe_json, "NumberOfSections", nsections);
#endif
for(i = 0; i < nsections; i++) {
strncpy(sname, (char *) section_hdr[i].Name, 8);
sname[8] = 0;
exe_sections[i].rva = PEALIGN(EC32(section_hdr[i].VirtualAddress), valign);
exe_sections[i].vsz = PESALIGN(EC32(section_hdr[i].VirtualSize), valign);
exe_sections[i].raw = PEALIGN(EC32(section_hdr[i].PointerToRawData), falign);
exe_sections[i].rsz = PESALIGN(EC32(section_hdr[i].SizeOfRawData), falign);
exe_sections[i].chr = EC32(section_hdr[i].Characteristics);
exe_sections[i].urva = EC32(section_hdr[i].VirtualAddress); /* Just in case */
exe_sections[i].uvsz = EC32(section_hdr[i].VirtualSize);
exe_sections[i].uraw = EC32(section_hdr[i].PointerToRawData);
exe_sections[i].ursz = EC32(section_hdr[i].SizeOfRawData);
#if HAVE_JSON
add_section_info(ctx, &exe_sections[i]);
if (cli_json_timeout_cycle_check(ctx, &toval) != CL_SUCCESS) {
free(section_hdr);
free(exe_sections);
return CL_ETIMEOUT;
}
#endif
if (!exe_sections[i].vsz && exe_sections[i].rsz)
exe_sections[i].vsz=PESALIGN(exe_sections[i].ursz, valign);
if (exe_sections[i].rsz && fsize>exe_sections[i].raw && !CLI_ISCONTAINED(0, (uint32_t) fsize, exe_sections[i].raw, exe_sections[i].rsz))
exe_sections[i].rsz = fsize - exe_sections[i].raw;
cli_dbgmsg("Section %d\n", i);
cli_dbgmsg("Section name: %s\n", sname);
cli_dbgmsg("Section data (from headers - in memory)\n");
cli_dbgmsg("VirtualSize: 0x%x 0x%x\n", exe_sections[i].uvsz, exe_sections[i].vsz);
cli_dbgmsg("VirtualAddress: 0x%x 0x%x\n", exe_sections[i].urva, exe_sections[i].rva);
cli_dbgmsg("SizeOfRawData: 0x%x 0x%x\n", exe_sections[i].ursz, exe_sections[i].rsz);
cli_dbgmsg("PointerToRawData: 0x%x 0x%x\n", exe_sections[i].uraw, exe_sections[i].raw);
if(exe_sections[i].chr & 0x20) {
cli_dbgmsg("Section contains executable code\n");
if(exe_sections[i].vsz < exe_sections[i].rsz) {
cli_dbgmsg("Section contains free space\n");
/*
cli_dbgmsg("Dumping %d bytes\n", section_hdr.SizeOfRawData - section_hdr.VirtualSize);
ddump(desc, section_hdr.PointerToRawData + section_hdr.VirtualSize, section_hdr.SizeOfRawData - section_hdr.VirtualSize, cli_gentemp(NULL));
*/
}
}
if(exe_sections[i].chr & 0x20000000)
cli_dbgmsg("Section's memory is executable\n");
if(exe_sections[i].chr & 0x80000000)
cli_dbgmsg("Section's memory is writeable\n");
if (DETECT_BROKEN_PE && (!valign || (exe_sections[i].urva % valign))) { /* Bad virtual alignment */
cli_dbgmsg("VirtualAddress is misaligned\n");
cli_dbgmsg("------------------------------------\n");
cli_append_virus(ctx, "Heuristics.Broken.Executable");
free(section_hdr);
free(exe_sections);
return CL_VIRUS;
}
if (exe_sections[i].rsz) { /* Don't bother with virtual only sections */
if (exe_sections[i].raw >= fsize) { /* really broken */
cli_dbgmsg("Broken PE file - Section %d starts beyond the end of file (Offset@ %lu, Total filesize %lu)\n", i, (unsigned long)exe_sections[i].raw, (unsigned long)fsize);
cli_dbgmsg("------------------------------------\n");
free(section_hdr);
free(exe_sections);
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx, "Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN; /* no ninjas to see here! move along! */
}
if(SCAN_ALGO && (DCONF & PE_CONF_POLIPOS) && !*sname && exe_sections[i].vsz > 40000 && exe_sections[i].vsz < 70000 && exe_sections[i].chr == 0xe0000060) polipos = i;
/* check hash section sigs */
if((DCONF & PE_CONF_MD5SECT) && ctx->engine->hm_mdb) {
ret = scan_pe_mdb(ctx, &exe_sections[i]);
if (ret != CL_CLEAN) {
if (ret != CL_VIRUS)
cli_errmsg("scan_pe: scan_pe_mdb failed: %s!\n", cl_strerror(ret));
cli_dbgmsg("------------------------------------\n");
free(section_hdr);
free(exe_sections);
return ret;
}
}
}
cli_dbgmsg("------------------------------------\n");
if (exe_sections[i].urva>>31 || exe_sections[i].uvsz>>31 || (exe_sections[i].rsz && exe_sections[i].uraw>>31) || exe_sections[i].ursz>>31) {
cli_dbgmsg("Found PE values with sign bit set\n");
free(section_hdr);
free(exe_sections);
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx, "Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
if(!i) {
if (DETECT_BROKEN_PE && exe_sections[i].urva!=hdr_size) { /* Bad first section RVA */
cli_dbgmsg("First section is in the wrong place\n");
cli_append_virus(ctx, "Heuristics.Broken.Executable");
free(section_hdr);
free(exe_sections);
return CL_VIRUS;
}
min = exe_sections[i].rva;
max = exe_sections[i].rva + exe_sections[i].rsz;
} else {
if (DETECT_BROKEN_PE && exe_sections[i].urva - exe_sections[i-1].urva != exe_sections[i-1].vsz) { /* No holes, no overlapping, no virtual disorder */
cli_dbgmsg("Virtually misplaced section (wrong order, overlapping, non contiguous)\n");
cli_append_virus(ctx, "Heuristics.Broken.Executable");
free(section_hdr);
free(exe_sections);
return CL_VIRUS;
}
if(exe_sections[i].rva < min)
min = exe_sections[i].rva;
if(exe_sections[i].rva + exe_sections[i].rsz > max) {
max = exe_sections[i].rva + exe_sections[i].rsz;
overlays = exe_sections[i].raw + exe_sections[i].rsz;
}
}
}
free(section_hdr);
if(!(ep = cli_rawaddr(vep, exe_sections, nsections, &err, fsize, hdr_size)) && err) {
cli_dbgmsg("EntryPoint out of file\n");
free(exe_sections);
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
#if HAVE_JSON
cli_jsonint(pe_json, "EntryPointOffset", ep);
if (cli_json_timeout_cycle_check(ctx, &toval) != CL_SUCCESS) {
return CL_ETIMEOUT;
}
#endif
cli_dbgmsg("EntryPoint offset: 0x%x (%d)\n", ep, ep);
if(pe_plus) { /* Do not continue for PE32+ files */
free(exe_sections);
return CL_CLEAN;
}
epsize = fmap_readn(map, epbuff, ep, 4096);
/* Disasm scan disabled since it's now handled by the bytecode */
/* CLI_UNPTEMP("DISASM",(exe_sections,0)); */
/* if(disasmbuf((unsigned char*)epbuff, epsize, ndesc)) */
/* ret = cli_scandesc(ndesc, ctx, CL_TYPE_PE_DISASM, 1, NULL, AC_SCAN_VIR); */
/* close(ndesc); */
/* CLI_TMPUNLK(); */
/* free(tempfile); */
/* if(ret == CL_VIRUS) { */
/* free(exe_sections); */
/* return ret; */
/* } */
if(overlays) {
int overlays_sz = fsize - overlays;
if(overlays_sz > 0) {
ret = cli_scanishield(ctx, overlays, overlays_sz);
if(ret != CL_CLEAN) {
free(exe_sections);
return ret;
}
}
}
pedata.nsections = nsections;
pedata.ep = ep;
pedata.offset = 0;
memcpy(&pedata.file_hdr, &file_hdr, sizeof(file_hdr));
memcpy(&pedata.opt32, &pe_opt.opt32, sizeof(pe_opt.opt32));
memcpy(&pedata.opt64, &pe_opt.opt64, sizeof(pe_opt.opt64));
memcpy(&pedata.dirs, dirs, sizeof(pedata.dirs));
pedata.e_lfanew = e_lfanew;
pedata.overlays = overlays;
pedata.overlays_sz = fsize - overlays;
pedata.hdr_size = hdr_size;
/* Bytecode BC_PE_ALL hook */
bc_ctx = cli_bytecode_context_alloc();
if (!bc_ctx) {
cli_errmsg("cli_scanpe: can't allocate memory for bc_ctx\n");
free(exe_sections);
return CL_EMEM;
}
cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections);
cli_bytecode_context_setctx(bc_ctx, ctx);
ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_ALL, map);
switch (ret) {
case CL_ENULLARG:
cli_warnmsg("cli_scanpe: NULL argument supplied\n");
break;
case CL_VIRUS:
case CL_BREAK:
free(exe_sections);
cli_bytecode_context_destroy(bc_ctx);
return ret == CL_VIRUS ? CL_VIRUS : CL_CLEAN;
}
cli_bytecode_context_destroy(bc_ctx);
/* Attempt to detect some popular polymorphic viruses */
/* W32.Parite.B */
if(SCAN_ALGO && (DCONF & PE_CONF_PARITE) && !dll && epsize == 4096 && ep == exe_sections[nsections - 1].raw) {
const char *pt = cli_memstr(epbuff, 4040, "\x47\x65\x74\x50\x72\x6f\x63\x41\x64\x64\x72\x65\x73\x73\x00", 15);
if(pt) {
pt += 15;
if((((uint32_t)cli_readint32(pt) ^ (uint32_t)cli_readint32(pt + 4)) == 0x505a4f) && (((uint32_t)cli_readint32(pt + 8) ^ (uint32_t)cli_readint32(pt + 12)) == 0xffffb) && (((uint32_t)cli_readint32(pt + 16) ^ (uint32_t)cli_readint32(pt + 20)) == 0xb8)) {
cli_append_virus(ctx,"Heuristics.W32.Parite.B");
if (!SCAN_ALL) {
free(exe_sections);
return CL_VIRUS;
}
viruses_found++;
}
}
}
/* Kriz */
if(SCAN_ALGO && (DCONF & PE_CONF_KRIZ) && epsize >= 200 && CLI_ISCONTAINED(exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz, ep, 0x0fd2) && epbuff[1]=='\x9c' && epbuff[2]=='\x60') {
enum {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSXORPRFX,KZSXOR,KZSDDELTA,KZSLOOP,KZSTOP};
uint8_t kzs[] = {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSTRASH,KZSXORPRFX,KZSXOR,KZSTRASH,KZSDDELTA,KZSTRASH,KZSLOOP,KZSTOP};
uint8_t *kzstate = kzs;
uint8_t *kzcode = (uint8_t *)epbuff + 3;
uint8_t kzdptr=0xff, kzdsize=0xff;
int kzlen = 197, kzinitlen=0xffff, kzxorlen=-1;
cli_dbgmsg("in kriz\n");
while(*kzstate!=KZSTOP) {
uint8_t op;
if(kzlen<=6) break;
op = *kzcode++;
kzlen--;
switch (*kzstate) {
case KZSTRASH: case KZSGETSIZE: {
int opsz=0;
switch(op) {
case 0x81:
kzcode+=5;
kzlen-=5;
break;
case 0xb8: case 0xb9: case 0xba: case 0xbb: case 0xbd: case 0xbe: case 0xbf:
if(*kzstate==KZSGETSIZE && cli_readint32(kzcode)==0x0fd2) {
kzinitlen = kzlen-5;
kzdsize=op-0xb8;
kzstate++;
op=4; /* fake the register to avoid breaking out */
cli_dbgmsg("kriz: using #%d as size counter\n", kzdsize);
}
opsz=4;
case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4d: case 0x4e: case 0x4f:
op&=7;
if(op!=kzdptr && op!=kzdsize) {
kzcode+=opsz;
kzlen-=opsz;
break;
}
default:
kzcode--;
kzlen++;
kzstate++;
}
break;
}
case KZSCDELTA:
if(op==0xe8 && (uint32_t)cli_readint32(kzcode) < 0xff) {
kzlen-=*kzcode+4;
kzcode+=*kzcode+4;
kzstate++;
} else *kzstate=KZSTOP;
break;
case KZSPDELTA:
if((op&0xf8)==0x58 && (kzdptr=op-0x58)!=4) {
kzstate++;
cli_dbgmsg("kriz: using #%d as pointer\n", kzdptr);
} else *kzstate=KZSTOP;
break;
case KZSXORPRFX:
kzstate++;
if(op==0x3e) break;
case KZSXOR:
if (op==0x80 && *kzcode==kzdptr+0xb0) {
kzxorlen=kzlen;
kzcode+=+6;
kzlen-=+6;
kzstate++;
} else *kzstate=KZSTOP;
break;
case KZSDDELTA:
if (op==kzdptr+0x48) kzstate++;
else *kzstate=KZSTOP;
break;
case KZSLOOP:
if (op==kzdsize+0x48 && *kzcode==0x75 && kzlen-(int8_t)kzcode[1]-3<=kzinitlen && kzlen-(int8_t)kzcode[1]>=kzxorlen) {
cli_append_virus(ctx,"Heuristics.W32.Kriz");
if (!SCAN_ALL) {
free(exe_sections);
return CL_VIRUS;
}
viruses_found++;
}
cli_dbgmsg("kriz: loop out of bounds, corrupted sample?\n");
kzstate++;
}
}
}
/* W32.Magistr.A/B */
if(SCAN_ALGO && (DCONF & PE_CONF_MAGISTR) && !dll && (nsections>1) && (exe_sections[nsections - 1].chr & 0x80000000)) {
uint32_t rsize, vsize, dam = 0;
vsize = exe_sections[nsections - 1].uvsz;
rsize = exe_sections[nsections - 1].rsz;
if(rsize < exe_sections[nsections - 1].ursz) {
rsize = exe_sections[nsections - 1].ursz;
dam = 1;
}
if(vsize >= 0x612c && rsize >= 0x612c && ((vsize & 0xff) == 0xec)) {
int bw = rsize < 0x7000 ? rsize : 0x7000;
const char *tbuff;
if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) {
if(cli_memstr(tbuff, 4091, "\xe8\x2c\x61\x00\x00", 5)) {
cli_append_virus(ctx, dam ? "Heuristics.W32.Magistr.A.dam" : "Heuristics.W32.Magistr.A");
if (!SCAN_ALL) {
free(exe_sections);
return CL_VIRUS;
}
viruses_found++;
}
}
} else if(rsize >= 0x7000 && vsize >= 0x7000 && ((vsize & 0xff) == 0xed)) {
int bw = rsize < 0x8000 ? rsize : 0x8000;
const char *tbuff;
if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) {
if(cli_memstr(tbuff, 4091, "\xe8\x04\x72\x00\x00", 5)) {
cli_append_virus(ctx,dam ? "Heuristics.W32.Magistr.B.dam" : "Heuristics.W32.Magistr.B");
if (!SCAN_ALL) {
free(exe_sections);
return CL_VIRUS;
}
viruses_found++;
}
}
}
}
/* W32.Polipos.A */
while(polipos && !dll && nsections > 2 && nsections < 13 && e_lfanew <= 0x800 && (EC16(optional_hdr32.Subsystem) == 2 || EC16(optional_hdr32.Subsystem) == 3) && EC16(file_hdr.Machine) == 0x14c && optional_hdr32.SizeOfStackReserve >= 0x80000) {
uint32_t jump, jold, *jumps = NULL;
const uint8_t *code;
unsigned int xsjs = 0;
if(exe_sections[0].rsz > CLI_MAX_ALLOCATION) break;
if(!exe_sections[0].rsz) break;
if(!(code=fmap_need_off_once(map, exe_sections[0].raw, exe_sections[0].rsz))) break;
for(i=0; i<exe_sections[0].rsz - 5; i++) {
if((uint8_t)(code[i]-0xe8) > 1) continue;
jump = cli_rawaddr(exe_sections[0].rva+i+5+cli_readint32(&code[i+1]), exe_sections, nsections, &err, fsize, hdr_size);
if(err || !CLI_ISCONTAINED(exe_sections[polipos].raw, exe_sections[polipos].rsz, jump, 9)) continue;
if(xsjs % 128 == 0) {
if(xsjs == 1280) break;
if(!(jumps=(uint32_t *)cli_realloc2(jumps, (xsjs+128)*sizeof(uint32_t)))) {
free(exe_sections);
return CL_EMEM;
}
}
j=0;
for(; j<xsjs; j++) {
if(jumps[j]<jump) continue;
if(jumps[j]==jump) {
xsjs--;
break;
}
jold=jumps[j];
jumps[j]=jump;
jump=jold;
}
jumps[j]=jump;
xsjs++;
}
if(!xsjs) break;
cli_dbgmsg("Polipos: Checking %d xsect jump(s)\n", xsjs);
for(i=0;i<xsjs;i++) {
if(!(code = fmap_need_off_once(map, jumps[i], 9))) continue;
if((jump=cli_readint32(code))==0x60ec8b55 || (code[4]==0x0ec && ((jump==0x83ec8b55 && code[6]==0x60) || (jump==0x81ec8b55 && !code[7] && !code[8])))) {
cli_append_virus(ctx,"Heuristics.W32.Polipos.A");
if (!SCAN_ALL) {
free(jumps);
free(exe_sections);
return CL_VIRUS;
}
viruses_found++;
}
}
free(jumps);
break;
}
/* Trojan.Swizzor.Gen */
if (SCAN_ALGO && (DCONF & PE_CONF_SWIZZOR) && nsections > 1 && fsize > 64*1024 && fsize < 4*1024*1024) {
if(dirs[2].Size) {
struct swizz_stats *stats = cli_calloc(1, sizeof(*stats));
unsigned int m = 1000;
ret = CL_CLEAN;
if (!stats)
ret = CL_EMEM;
else {
cli_parseres_special(EC32(dirs[2].VirtualAddress), EC32(dirs[2].VirtualAddress), map, exe_sections, nsections, fsize, hdr_size, 0, 0, &m, stats);
if ((ret = cli_detect_swizz(stats)) == CL_VIRUS) {
cli_append_virus(ctx,"Heuristics.Trojan.Swizzor.Gen");
}
free(stats);
}
if (ret != CL_CLEAN) {
if (!(ret == CL_VIRUS && SCAN_ALL)) {
free(exe_sections);
return ret;
}
viruses_found++;
}
}
}
/* !!!!!!!!!!!!!! PACKERS START HERE !!!!!!!!!!!!!! */
corrupted_cur = ctx->corrupted_input;
ctx->corrupted_input = 2; /* caller will reset on return */
/* UPX, FSG, MEW support */
/* try to find the first section with physical size == 0 */
found = 0;
if(DCONF & (PE_CONF_UPX | PE_CONF_FSG | PE_CONF_MEW)) {
for(i = 0; i < (unsigned int) nsections - 1; i++) {
if(!exe_sections[i].rsz && exe_sections[i].vsz && exe_sections[i + 1].rsz && exe_sections[i + 1].vsz) {
found = 1;
cli_dbgmsg("UPX/FSG/MEW: empty section found - assuming compression\n");
#if HAVE_JSON
cli_jsonbool(pe_json, "HasEmptySection", 1);
#endif
break;
}
}
}
/* MEW support */
if (found && (DCONF & PE_CONF_MEW) && epsize>=16 && epbuff[0]=='\xe9') {
uint32_t fileoffset;
const char *tbuff;
fileoffset = (vep + cli_readint32(epbuff + 1) + 5);
while (fileoffset == 0x154 || fileoffset == 0x158) {
char *src;
uint32_t offdiff, uselzma;
cli_dbgmsg ("MEW: found MEW characteristics %08X + %08X + 5 = %08X\n",
cli_readint32(epbuff + 1), vep, cli_readint32(epbuff + 1) + vep + 5);
if(!(tbuff = fmap_need_off_once(map, fileoffset, 0xb0)))
break;
if (fileoffset == 0x154) cli_dbgmsg("MEW: Win9x compatibility was set!\n");
else cli_dbgmsg("MEW: Win9x compatibility was NOT set!\n");
if((offdiff = cli_readint32(tbuff+1) - EC32(optional_hdr32.ImageBase)) <= exe_sections[i + 1].rva || offdiff >= exe_sections[i + 1].rva + exe_sections[i + 1].raw - 4) {
cli_dbgmsg("MEW: ESI is not in proper section\n");
break;
}
offdiff -= exe_sections[i + 1].rva;
if(!exe_sections[i + 1].rsz) {
cli_dbgmsg("MEW: mew section is empty\n");
break;
}
ssize = exe_sections[i + 1].vsz;
dsize = exe_sections[i].vsz;
cli_dbgmsg("MEW: ssize %08x dsize %08x offdiff: %08x\n", ssize, dsize, offdiff);
CLI_UNPSIZELIMITS("MEW", MAX(ssize, dsize));
CLI_UNPSIZELIMITS("MEW", MAX(ssize + dsize, exe_sections[i + 1].rsz));
if (exe_sections[i + 1].rsz < offdiff + 12 || exe_sections[i + 1].rsz > ssize) {
cli_dbgmsg("MEW: Size mismatch: %08x\n", exe_sections[i + 1].rsz);
break;
}
/* allocate needed buffer */
if (!(src = cli_calloc (ssize + dsize, sizeof(char)))) {
free(exe_sections);
return CL_EMEM;
}
if((bytes = fmap_readn(map, src + dsize, exe_sections[i + 1].raw, exe_sections[i + 1].rsz)) != exe_sections[i + 1].rsz) {
cli_dbgmsg("MEW: Can't read %d bytes [read: %lu]\n", exe_sections[i + 1].rsz, (unsigned long)bytes);
free(exe_sections);
free(src);
return CL_EREAD;
}
cli_dbgmsg("MEW: %u (%08x) bytes read\n", (unsigned int)bytes, (unsigned int)bytes);
/* count offset to lzma proc, if lzma used, 0xe8 -> call */
if (tbuff[0x7b] == '\xe8') {
if (!CLI_ISCONTAINED(exe_sections[1].rva, exe_sections[1].vsz, cli_readint32(tbuff + 0x7c) + fileoffset + 0x80, 4)) {
cli_dbgmsg("MEW: lzma proc out of bounds!\n");
free(src);
break; /* to next unpacker in chain */
}
uselzma = cli_readint32(tbuff + 0x7c) - (exe_sections[0].rva - fileoffset - 0x80);
} else {
uselzma = 0;
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "MEW");
#endif
CLI_UNPTEMP("MEW",(src,exe_sections,0));
CLI_UNPRESULTS("MEW",(unmew11(src, offdiff, ssize, dsize, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, uselzma, ndesc)),1,(src,0));
break;
}
}
if(epsize<168) {
free(exe_sections);
return CL_CLEAN;
}
if (found || upack) {
/* Check EP for UPX vs. FSG vs. Upack */
/* Upack 0.39 produces 2 types of executables
* 3 sections: | 2 sections (one empty, I don't chech found if !upack, since it's in OR above):
* mov esi, value | pusha
* lodsd | call $+0x9
* push eax |
*
* Upack 1.1/1.2 Beta produces [based on 2 samples (sUx) provided by aCaB]:
* 2 sections
* mov esi, value
* loads
* mov edi, eax
*
* Upack unknown [sample 0297729]
* 3 sections
* mov esi, value
* push [esi]
* jmp
*
*/
/* upack 0.39-3s + sample 0151477*/
while(((upack && nsections == 3) && /* 3 sections */
((
epbuff[0] == '\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && /* mov esi */
epbuff[5] == '\xad' && epbuff[6] == '\x50' /* lodsd; push eax */
)
||
/* based on 0297729 sample from aCaB */
(epbuff[0] == '\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && /* mov esi */
epbuff[5] == '\xff' && epbuff[6] == '\x36' /* push [esi] */
)
))
||
((!upack && nsections == 2) && /* 2 sections */
(( /* upack 0.39-2s */
epbuff[0] == '\x60' && epbuff[1] == '\xe8' && cli_readint32(epbuff+2) == 0x9 /* pusha; call+9 */
)
||
( /* upack 1.1/1.2, based on 2 samples */
epbuff[0] == '\xbe' && cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase) < min && /* mov esi */
cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > 0 &&
epbuff[5] == '\xad' && epbuff[6] == '\x8b' && epbuff[7] == '\xf8' /* loads; mov edi, eax */
)
))
) {
uint32_t vma, off;
int a,b,c;
cli_dbgmsg("Upack characteristics found.\n");
a = exe_sections[0].vsz;
b = exe_sections[1].vsz;
if (upack) {
cli_dbgmsg("Upack: var set\n");
c = exe_sections[2].vsz;
ssize = exe_sections[0].ursz + exe_sections[0].uraw;
off = exe_sections[0].rva;
vma = EC32(optional_hdr32.ImageBase) + exe_sections[0].rva;
} else {
cli_dbgmsg("Upack: var NOT set\n");
c = exe_sections[1].rva;
ssize = exe_sections[1].uraw;
off = 0;
vma = exe_sections[1].rva - exe_sections[1].uraw;
}
dsize = a+b+c;
CLI_UNPSIZELIMITS("Upack", MAX(MAX(dsize, ssize), exe_sections[1].ursz));
if (!CLI_ISCONTAINED(0, dsize, exe_sections[1].rva - off, exe_sections[1].ursz) || (upack && !CLI_ISCONTAINED(0, dsize, exe_sections[2].rva - exe_sections[0].rva, ssize)) || ssize > dsize) {
cli_dbgmsg("Upack: probably malformed pe-header, skipping to next unpacker\n");
break;
}
if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
free(exe_sections);
return CL_EMEM;
}
if((unsigned int)fmap_readn(map, dest, 0, ssize) != ssize) {
cli_dbgmsg("Upack: Can't read raw data of section 0\n");
free(dest);
break;
}
if(upack) memmove(dest + exe_sections[2].rva - exe_sections[0].rva, dest, ssize);
if((unsigned int)fmap_readn(map, dest + exe_sections[1].rva - off, exe_sections[1].uraw, exe_sections[1].ursz) != exe_sections[1].ursz) {
cli_dbgmsg("Upack: Can't read raw data of section 1\n");
free(dest);
break;
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "Upack");
#endif
CLI_UNPTEMP("Upack",(dest,exe_sections,0));
CLI_UNPRESULTS("Upack",(unupack(upack, dest, dsize, epbuff, vma, ep, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, ndesc)),1,(dest,0));
break;
}
}
while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\x87' && epbuff[1] == '\x25') {
const char *dst;
/* FSG v2.0 support - thanks to aCaB ! */
uint32_t newesi, newedi, newebx, newedx;
ssize = exe_sections[i + 1].rsz;
dsize = exe_sections[i].vsz;
CLI_UNPSIZELIMITS("FSG", MAX(dsize, ssize));
if(ssize <= 0x19 || dsize <= ssize) {
cli_dbgmsg("FSG: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize);
free(exe_sections);
return CL_CLEAN;
}
newedx = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase);
if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) {
cli_dbgmsg("FSG: xchg out of bounds (%x), giving up\n", newedx);
break;
}
if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {
cli_dbgmsg("Can't read raw data of section %d\n", i + 1);
free(exe_sections);
return CL_ESEEK;
}
dst = src + newedx - exe_sections[i + 1].rva;
if(newedx < exe_sections[i + 1].rva || !CLI_ISCONTAINED(src, ssize, dst, 4)) {
cli_dbgmsg("FSG: New ESP out of bounds\n");
break;
}
newedx = cli_readint32(dst) - EC32(optional_hdr32.ImageBase);
if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) {
cli_dbgmsg("FSG: New ESP (%x) is wrong\n", newedx);
break;
}
dst = src + newedx - exe_sections[i + 1].rva;
if(!CLI_ISCONTAINED(src, ssize, dst, 32)) {
cli_dbgmsg("FSG: New stack out of bounds\n");
break;
}
newedi = cli_readint32(dst) - EC32(optional_hdr32.ImageBase);
newesi = cli_readint32(dst + 4) - EC32(optional_hdr32.ImageBase);
newebx = cli_readint32(dst + 16) - EC32(optional_hdr32.ImageBase);
newedx = cli_readint32(dst + 20);
if(newedi != exe_sections[i].rva) {
cli_dbgmsg("FSG: Bad destination buffer (edi is %x should be %x)\n", newedi, exe_sections[i].rva);
break;
}
if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) {
cli_dbgmsg("FSG: Source buffer out of section bounds\n");
break;
}
if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newebx, 16)) {
cli_dbgmsg("FSG: Array of functions out of bounds\n");
break;
}
newedx=cli_readint32(newebx + 12 - exe_sections[i + 1].rva + src) - EC32(optional_hdr32.ImageBase);
cli_dbgmsg("FSG: found old EP @%x\n",newedx);
if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
free(exe_sections);
return CL_EMEM;
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "FSG");
#endif
CLI_UNPTEMP("FSG",(dest,exe_sections,0));
CLI_UNPRESULTSFSG2("FSG",(unfsg_200(newesi - exe_sections[i + 1].rva + src, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, newedi, EC32(optional_hdr32.ImageBase), newedx, ndesc)),1,(dest,0));
break;
}
while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min) {
/* FSG support - v. 1.33 (thx trog for the many samples) */
int sectcnt = 0;
const char *support;
uint32_t newesi, newedi, oldep, gp, t;
struct cli_exe_section *sections;
ssize = exe_sections[i + 1].rsz;
dsize = exe_sections[i].vsz;
CLI_UNPSIZELIMITS("FSG", MAX(dsize, ssize));
if(ssize <= 0x19 || dsize <= ssize) {
cli_dbgmsg("FSG: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize);
free(exe_sections);
return CL_CLEAN;
}
if(!(t = cli_rawaddr(cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size)) && err ) {
cli_dbgmsg("FSG: Support data out of padding area\n");
break;
}
gp = exe_sections[i + 1].raw - t;
CLI_UNPSIZELIMITS("FSG", gp);
if(!(support = fmap_need_off_once(map, t, gp))) {
cli_dbgmsg("Can't read %d bytes from padding area\n", gp);
free(exe_sections);
return CL_EREAD;
}
/* newebx = cli_readint32(support) - EC32(optional_hdr32.ImageBase); Unused */
newedi = cli_readint32(support + 4) - EC32(optional_hdr32.ImageBase); /* 1st dest */
newesi = cli_readint32(support + 8) - EC32(optional_hdr32.ImageBase); /* Source */
if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) {
cli_dbgmsg("FSG: Source buffer out of section bounds\n");
break;
}
if(newedi != exe_sections[i].rva) {
cli_dbgmsg("FSG: Bad destination (is %x should be %x)\n", newedi, exe_sections[i].rva);
break;
}
/* Counting original sections */
for(t = 12; t < gp - 4; t += 4) {
uint32_t rva = cli_readint32(support+t);
if(!rva)
break;
rva -= EC32(optional_hdr32.ImageBase)+1;
sectcnt++;
if(rva % 0x1000) cli_dbgmsg("FSG: Original section %d is misaligned\n", sectcnt);
if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) {
cli_dbgmsg("FSG: Original section %d is out of bounds\n", sectcnt);
break;
}
}
if(t >= gp - 4 || cli_readint32(support + t)) {
break;
}
if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) {
cli_errmsg("FSG: Unable to allocate memory for sections %lu\n", (sectcnt + 1) * sizeof(struct cli_exe_section));
free(exe_sections);
return CL_EMEM;
}
sections[0].rva = newedi;
for(t = 1; t <= (uint32_t)sectcnt; t++)
sections[t].rva = cli_readint32(support + 8 + t * 4) - 1 - EC32(optional_hdr32.ImageBase);
if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {
cli_dbgmsg("Can't read raw data of section %d\n", i);
free(exe_sections);
free(sections);
return CL_EREAD;
}
if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
free(exe_sections);
free(sections);
return CL_EMEM;
}
oldep = vep + 161 + 6 + cli_readint32(epbuff+163);
cli_dbgmsg("FSG: found old EP @%x\n", oldep);
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "FSG");
#endif
CLI_UNPTEMP("FSG",(dest,sections,exe_sections,0));
CLI_UNPRESULTSFSG1("FSG",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0));
break; /* were done with 1.33 */
}
while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\xbb' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min && epbuff[5] == '\xbf' && epbuff[10] == '\xbe' && vep >= exe_sections[i + 1].rva && vep - exe_sections[i + 1].rva > exe_sections[i + 1].rva - 0xe0 ) {
/* FSG support - v. 1.31 */
int sectcnt = 0;
uint32_t gp, t = cli_rawaddr(cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size);
const char *support;
uint32_t newesi = cli_readint32(epbuff+11) - EC32(optional_hdr32.ImageBase);
uint32_t newedi = cli_readint32(epbuff+6) - EC32(optional_hdr32.ImageBase);
uint32_t oldep = vep - exe_sections[i + 1].rva;
struct cli_exe_section *sections;
ssize = exe_sections[i + 1].rsz;
dsize = exe_sections[i].vsz;
if(err) {
cli_dbgmsg("FSG: Support data out of padding area\n");
break;
}
if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].raw) {
cli_dbgmsg("FSG: Source buffer out of section bounds\n");
break;
}
if(newedi != exe_sections[i].rva) {
cli_dbgmsg("FSG: Bad destination (is %x should be %x)\n", newedi, exe_sections[i].rva);
break;
}
CLI_UNPSIZELIMITS("FSG", MAX(dsize, ssize));
if(ssize <= 0x19 || dsize <= ssize) {
cli_dbgmsg("FSG: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize);
free(exe_sections);
return CL_CLEAN;
}
gp = exe_sections[i + 1].raw - t;
CLI_UNPSIZELIMITS("FSG", gp)
if(!(support = fmap_need_off_once(map, t, gp))) {
cli_dbgmsg("Can't read %d bytes from padding area\n", gp);
free(exe_sections);
return CL_EREAD;
}
/* Counting original sections */
for(t = 0; t < gp - 2; t += 2) {
uint32_t rva = support[t]|(support[t+1]<<8);
if (rva == 2 || rva == 1)
break;
rva = ((rva-2)<<12) - EC32(optional_hdr32.ImageBase);
sectcnt++;
if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) {
cli_dbgmsg("FSG: Original section %d is out of bounds\n", sectcnt);
break;
}
}
if(t >= gp-10 || cli_readint32(support + t + 6) != 2) {
break;
}
if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) {
cli_errmsg("FSG: Unable to allocate memory for sections %lu\n", (sectcnt + 1) * sizeof(struct cli_exe_section));
free(exe_sections);
return CL_EMEM;
}
sections[0].rva = newedi;
for(t = 0; t <= (uint32_t)sectcnt - 1; t++) {
sections[t+1].rva = (((support[t*2]|(support[t*2+1]<<8))-2)<<12)-EC32(optional_hdr32.ImageBase);
}
if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {
cli_dbgmsg("FSG: Can't read raw data of section %d\n", i);
free(exe_sections);
free(sections);
return CL_EREAD;
}
if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
free(exe_sections);
free(sections);
return CL_EMEM;
}
gp = 0xda + 6*(epbuff[16]=='\xe8');
oldep = vep + gp + 6 + cli_readint32(src+gp+2+oldep);
cli_dbgmsg("FSG: found old EP @%x\n", oldep);
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "FSG");
#endif
CLI_UNPTEMP("FSG",(dest,sections,exe_sections,0));
CLI_UNPRESULTSFSG1("FSG",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0));
break; /* were done with 1.31 */
}
if(found && (DCONF & PE_CONF_UPX)) {
/* UPX support */
/* we assume (i + 1) is UPX1 */
ssize = exe_sections[i + 1].rsz;
dsize = exe_sections[i].vsz + exe_sections[i + 1].vsz;
/* cli_dbgmsg("UPX: ssize %u dsize %u\n", ssize, dsize); */
CLI_UNPSIZELIMITS("UPX", MAX(dsize, ssize));
if(ssize <= 0x19 || dsize <= ssize || dsize > CLI_MAX_ALLOCATION ) {
cli_dbgmsg("UPX: Size mismatch or dsize too big (ssize: %d, dsize: %d)\n", ssize, dsize);
free(exe_sections);
return CL_CLEAN;
}
if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {
cli_dbgmsg("UPX: Can't read raw data of section %d\n", i+1);
free(exe_sections);
return CL_EREAD;
}
if((dest = (char *) cli_calloc(dsize + 8192, sizeof(char))) == NULL) {
free(exe_sections);
return CL_EMEM;
}
/* try to detect UPX code */
if(cli_memstr(UPX_NRV2B, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2B, 24, epbuff + 0x69 + 8, 13)) {
cli_dbgmsg("UPX: Looks like a NRV2B decompression routine\n");
upxfn = upx_inflate2b;
} else if(cli_memstr(UPX_NRV2D, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2D, 24, epbuff + 0x69 + 8, 13)) {
cli_dbgmsg("UPX: Looks like a NRV2D decompression routine\n");
upxfn = upx_inflate2d;
} else if(cli_memstr(UPX_NRV2E, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2E, 24, epbuff + 0x69 + 8, 13)) {
cli_dbgmsg("UPX: Looks like a NRV2E decompression routine\n");
upxfn = upx_inflate2e;
}
if(upxfn) {
int skew = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase) - exe_sections[i + 1].rva;
if(epbuff[1] != '\xbe' || skew <= 0 || skew > 0xfff) { /* FIXME: legit skews?? */
skew = 0;
} else if ((unsigned int)skew > ssize) {
/* Ignore suggested skew larger than section size */
skew = 0;
} else {
cli_dbgmsg("UPX: UPX1 seems skewed by %d bytes\n", skew);
}
/* Try skewed first (skew may be zero) */
if(upxfn(src + skew, ssize - skew, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep-skew) >= 0) {
upx_success = 1;
}
/* If skew not successful and non-zero, try no skew */
else if(skew && (upxfn(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >= 0)) {
upx_success = 1;
}
if(upx_success)
cli_dbgmsg("UPX: Successfully decompressed\n");
else
cli_dbgmsg("UPX: Preferred decompressor failed\n");
}
if(!upx_success && upxfn != upx_inflate2b) {
if(upx_inflate2b(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2b(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) {
cli_dbgmsg("UPX: NRV2B decompressor failed\n");
} else {
upx_success = 1;
cli_dbgmsg("UPX: Successfully decompressed with NRV2B\n");
}
}
if(!upx_success && upxfn != upx_inflate2d) {
if(upx_inflate2d(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2d(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) {
cli_dbgmsg("UPX: NRV2D decompressor failed\n");
} else {
upx_success = 1;
cli_dbgmsg("UPX: Successfully decompressed with NRV2D\n");
}
}
if(!upx_success && upxfn != upx_inflate2e) {
if(upx_inflate2e(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2e(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) {
cli_dbgmsg("UPX: NRV2E decompressor failed\n");
} else {
upx_success = 1;
cli_dbgmsg("UPX: Successfully decompressed with NRV2E\n");
}
}
if(cli_memstr(UPX_LZMA2, 20, epbuff + 0x2f, 20)) {
uint32_t strictdsize=cli_readint32(epbuff+0x21), skew = 0;
if(ssize > 0x15 && epbuff[0] == '\x60' && epbuff[1] == '\xbe') {
skew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase;
if(skew!=0x15) skew = 0;
}
if(strictdsize<=dsize)
upx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0;
} else if (cli_memstr(UPX_LZMA1, 20, epbuff + 0x39, 20)) {
uint32_t strictdsize=cli_readint32(epbuff+0x2b), skew = 0;
if(ssize > 0x15 && epbuff[0] == '\x60' && epbuff[1] == '\xbe') {
skew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase;
if(skew!=0x15) skew = 0;
}
if(strictdsize<=dsize)
upx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0;
}
if(!upx_success) {
cli_dbgmsg("UPX: All decompressors failed\n");
free(dest);
}
}
if(upx_success) {
free(exe_sections);
CLI_UNPTEMP("UPX/FSG",(dest,0));
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "UPX");
#endif
if((unsigned int) write(ndesc, dest, dsize) != dsize) {
cli_dbgmsg("UPX/FSG: Can't write %d bytes\n", dsize);
free(tempfile);
free(dest);
close(ndesc);
return CL_EWRITE;
}
free(dest);
if (lseek(ndesc, 0, SEEK_SET) == -1) {
cli_dbgmsg("UPX/FSG: lseek() failed\n");
close(ndesc);
CLI_TMPUNLK();
free(tempfile);
SHA_RESET;
return CL_ESEEK;
}
if(ctx->engine->keeptmp)
cli_dbgmsg("UPX/FSG: Decompressed data saved in %s\n", tempfile);
cli_dbgmsg("***** Scanning decompressed file *****\n");
SHA_OFF;
if((ret = cli_magic_scandesc(ndesc, ctx)) == CL_VIRUS) {
close(ndesc);
CLI_TMPUNLK();
free(tempfile);
SHA_RESET;
return CL_VIRUS;
}
SHA_RESET;
close(ndesc);
CLI_TMPUNLK();
free(tempfile);
return ret;
}
/* Petite */
if(epsize<200) {
free(exe_sections);
return CL_CLEAN;
}
found = 2;
if(epbuff[0] != '\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 1].rva + EC32(optional_hdr32.ImageBase)) {
if(nsections < 2 || epbuff[0] != '\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 2].rva + EC32(optional_hdr32.ImageBase))
found = 0;
else
found = 1;
}
if(found && (DCONF & PE_CONF_PETITE)) {
cli_dbgmsg("Petite: v2.%d compression detected\n", found);
if(cli_readint32(epbuff + 0x80) == 0x163c988d) {
cli_dbgmsg("Petite: level zero compression is not supported yet\n");
} else {
dsize = max - min;
CLI_UNPSIZELIMITS("Petite", dsize);
if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
cli_dbgmsg("Petite: Can't allocate %d bytes\n", dsize);
free(exe_sections);
return CL_EMEM;
}
for(i = 0 ; i < nsections; i++) {
if(exe_sections[i].raw) {
if(!exe_sections[i].rsz || (unsigned int)fmap_readn(map, dest + exe_sections[i].rva - min, exe_sections[i].raw, exe_sections[i].ursz) != exe_sections[i].ursz) {
free(exe_sections);
free(dest);
return CL_CLEAN;
}
}
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "Petite");
#endif
CLI_UNPTEMP("Petite",(dest,exe_sections,0));
CLI_UNPRESULTS("Petite",(petite_inflate2x_1to9(dest, min, max - min, exe_sections, nsections - (found == 1 ? 1 : 0), EC32(optional_hdr32.ImageBase),vep, ndesc, found, EC32(optional_hdr32.DataDirectory[2].VirtualAddress),EC32(optional_hdr32.DataDirectory[2].Size))),0,(dest,0));
}
}
/* PESpin 1.1 */
if((DCONF & PE_CONF_PESPIN) && nsections > 1 &&
vep >= exe_sections[nsections - 1].rva &&
vep < exe_sections[nsections - 1].rva + exe_sections[nsections - 1].rsz - 0x3217 - 4 &&
memcmp(epbuff+4, "\xe8\x00\x00\x00\x00\x8b\x1c\x24\x83\xc3", 10) == 0) {
char *spinned;
CLI_UNPSIZELIMITS("PEspin", fsize);
if((spinned = (char *) cli_malloc(fsize)) == NULL) {
cli_errmsg("PESping: Unable to allocate memory for spinned %lu\n", (unsigned long)fsize);
free(exe_sections);
return CL_EMEM;
}
if((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) {
cli_dbgmsg("PESpin: Can't read %lu bytes\n", (unsigned long)fsize);
free(spinned);
free(exe_sections);
return CL_EREAD;
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "PEspin");
#endif
CLI_UNPTEMP("PESpin",(spinned,exe_sections,0));
CLI_UNPRESULTS_("PEspin",SPINCASE(),(unspin(spinned, fsize, exe_sections, nsections - 1, vep, ndesc, ctx)),0,(spinned,0));
}
/* yC 1.3 & variants */
if((DCONF & PE_CONF_YC) && nsections > 1 &&
(EC32(optional_hdr32.AddressOfEntryPoint) == exe_sections[nsections - 1].rva + 0x60)) {
uint32_t ecx = 0;
int16_t offset;
/* yC 1.3 */
if (!memcmp(epbuff, "\x55\x8B\xEC\x53\x56\x57\x60\xE8\x00\x00\x00\x00\x5D\x81\xED", 15) &&
!memcmp(epbuff+0x26, "\x8D\x3A\x8B\xF7\x33\xC0\xEB\x04\x90\xEB\x01\xC2\xAC", 13) &&
((uint8_t)epbuff[0x13] == 0xB9) &&
((uint16_t)(cli_readint16(epbuff+0x18)) == 0xE981) &&
!memcmp(epbuff+0x1e,"\x8B\xD5\x81\xC2", 4)) {
offset = 0;
if (0x6c - cli_readint32(epbuff+0xf) + cli_readint32(epbuff+0x22) == 0xC6)
ecx = cli_readint32(epbuff+0x14) - cli_readint32(epbuff+0x1a);
}
/* yC 1.3 variant */
if (!ecx && !memcmp(epbuff, "\x55\x8B\xEC\x83\xEC\x40\x53\x56\x57", 9) &&
!memcmp(epbuff+0x17, "\xe8\x00\x00\x00\x00\x5d\x81\xed", 8) &&
((uint8_t)epbuff[0x23] == 0xB9)) {
offset = 0x10;
if (0x6c - cli_readint32(epbuff+0x1f) + cli_readint32(epbuff+0x32) == 0xC6)
ecx = cli_readint32(epbuff+0x24) - cli_readint32(epbuff+0x2a);
}
/* yC 1.x/modified */
if (!ecx && !memcmp(epbuff, "\x60\xe8\x00\x00\x00\x00\x5d\x81\xed",9) &&
((uint8_t)epbuff[0xd] == 0xb9) &&
((uint16_t)cli_readint16(epbuff + 0x12)== 0xbd8d) &&
!memcmp(epbuff+0x18, "\x8b\xf7\xac", 3)) {
offset = -0x18;
if (0x66 - cli_readint32(epbuff+0x9) + cli_readint32(epbuff+0x14) == 0xae)
ecx = cli_readint32(epbuff+0xe);
}
if (ecx > 0x800 && ecx < 0x2000 &&
!memcmp(epbuff+0x63+offset, "\xaa\xe2\xcc", 3) &&
(fsize >= exe_sections[nsections-1].raw + 0xC6 + ecx + offset)) {
char *spinned;
if((spinned = (char *) cli_malloc(fsize)) == NULL) {
cli_errmsg("yC: Unable to allocate memory for spinned %lu\n", (unsigned long)fsize);
free(exe_sections);
return CL_EMEM;
}
if((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) {
cli_dbgmsg("yC: Can't read %lu bytes\n", (unsigned long)fsize);
free(spinned);
free(exe_sections);
return CL_EREAD;
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "yC");
#endif
cli_dbgmsg("%d,%d,%d,%d\n", nsections-1, e_lfanew, ecx, offset);
CLI_UNPTEMP("yC",(spinned,exe_sections,0));
CLI_UNPRESULTS("yC",(yc_decrypt(spinned, fsize, exe_sections, nsections-1, e_lfanew, ndesc, ecx, offset)),0,(spinned,0));
}
}
/* WWPack */
while ((DCONF & PE_CONF_WWPACK) && nsections > 1 &&
vep == exe_sections[nsections - 1].rva &&
memcmp(epbuff, "\x53\x55\x8b\xe8\x33\xdb\xeb", 7) == 0 &&
memcmp(epbuff+0x68, "\xe8\x00\x00\x00\x00\x58\x2d\x6d\x00\x00\x00\x50\x60\x33\xc9\x50\x58\x50\x50", 19) == 0) {
uint32_t head = exe_sections[nsections - 1].raw;
uint8_t *packer;
char *src;
ssize = 0;
for(i=0 ; ; i++) {
if(exe_sections[i].raw<head)
head=exe_sections[i].raw;
if(i+1==nsections) break;
if(ssize<exe_sections[i].rva+exe_sections[i].vsz)
ssize=exe_sections[i].rva+exe_sections[i].vsz;
}
if(!head || !ssize || head>ssize) break;
CLI_UNPSIZELIMITS("WWPack", ssize);
if(!(src=(char *)cli_calloc(ssize, sizeof(char)))) {
free(exe_sections);
return CL_EMEM;
}
if((size_t) fmap_readn(map, src, 0, head) != head) {
cli_dbgmsg("WWPack: Can't read %d bytes from headers\n", head);
free(src);
free(exe_sections);
return CL_EREAD;
}
for(i = 0 ; i < (unsigned int)nsections-1; i++) {
if(!exe_sections[i].rsz) continue;
if(!CLI_ISCONTAINED(src, ssize, src+exe_sections[i].rva, exe_sections[i].rsz)) break;
if((unsigned int)fmap_readn(map, src+exe_sections[i].rva, exe_sections[i].raw, exe_sections[i].rsz)!=exe_sections[i].rsz) break;
}
if(i+1!=nsections) {
cli_dbgmsg("WWpack: Probably hacked/damaged file.\n");
free(src);
break;
}
if((packer = (uint8_t *) cli_calloc(exe_sections[nsections - 1].rsz, sizeof(char))) == NULL) {
free(src);
free(exe_sections);
return CL_EMEM;
}
if(!exe_sections[nsections - 1].rsz || (size_t) fmap_readn(map, packer, exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz) != exe_sections[nsections - 1].rsz) {
cli_dbgmsg("WWPack: Can't read %d bytes from wwpack sect\n", exe_sections[nsections - 1].rsz);
free(src);
free(packer);
free(exe_sections);
return CL_EREAD;
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "WWPack");
#endif
CLI_UNPTEMP("WWPack",(src,packer,exe_sections,0));
CLI_UNPRESULTS("WWPack",(wwunpack((uint8_t *)src, ssize, packer, exe_sections, nsections-1, e_lfanew, ndesc)),0,(src,packer,0));
break;
}
/* ASPACK support */
while((DCONF & PE_CONF_ASPACK) && ep+58+0x70e < fsize && !memcmp(epbuff,"\x60\xe8\x03\x00\x00\x00\xe9\xeb",8)) {
char *src;
if(epsize<0x3bf || memcmp(epbuff+0x3b9, "\x68\x00\x00\x00\x00\xc3",6)) break;
ssize = 0;
for(i=0 ; i< nsections ; i++)
if(ssize<exe_sections[i].rva+exe_sections[i].vsz)
ssize=exe_sections[i].rva+exe_sections[i].vsz;
if(!ssize) break;
CLI_UNPSIZELIMITS("Aspack", ssize);
if(!(src=(char *)cli_calloc(ssize, sizeof(char)))) {
free(exe_sections);
return CL_EMEM;
}
for(i = 0 ; i < (unsigned int)nsections; i++) {
if(!exe_sections[i].rsz) continue;
if(!CLI_ISCONTAINED(src, ssize, src+exe_sections[i].rva, exe_sections[i].rsz)) break;
if((unsigned int)fmap_readn(map, src+exe_sections[i].rva, exe_sections[i].raw, exe_sections[i].rsz)!=exe_sections[i].rsz) break;
}
if(i!=nsections) {
cli_dbgmsg("Aspack: Probably hacked/damaged Aspack file.\n");
free(src);
break;
}
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "Aspack");
#endif
CLI_UNPTEMP("Aspack",(src,exe_sections,0));
CLI_UNPRESULTS("Aspack",(unaspack212((uint8_t *)src, ssize, exe_sections, nsections, vep-1, EC32(optional_hdr32.ImageBase), ndesc)),1,(src,0));
break;
}
/* NsPack */
while (DCONF & PE_CONF_NSPACK) {
uint32_t eprva = vep;
uint32_t start_of_stuff, rep = ep;
unsigned int nowinldr;
const char *nbuff;
src=epbuff;
if (*epbuff=='\xe9') { /* bitched headers */
eprva = cli_readint32(epbuff+1)+vep+5;
if (!(rep = cli_rawaddr(eprva, exe_sections, nsections, &err, fsize, hdr_size)) && err) break;
if (!(nbuff = fmap_need_off_once(map, rep, 24))) break;
src = nbuff;
}
if (memcmp(src, "\x9c\x60\xe8\x00\x00\x00\x00\x5d\xb8\x07\x00\x00\x00", 13)) break;
nowinldr = 0x54-cli_readint32(src+17);
cli_dbgmsg("NsPack: Found *start_of_stuff @delta-%x\n", nowinldr);
if(!(nbuff = fmap_need_off_once(map, rep-nowinldr, 4))) break;
start_of_stuff=rep+cli_readint32(nbuff);
if(!(nbuff = fmap_need_off_once(map, start_of_stuff, 20))) break;
src = nbuff;
if (!cli_readint32(nbuff)) {
start_of_stuff+=4; /* FIXME: more to do */
src+=4;
}
ssize = cli_readint32(src+5)|0xff;
dsize = cli_readint32(src+9);
CLI_UNPSIZELIMITS("NsPack", MAX(ssize,dsize));
if (!ssize || !dsize || dsize != exe_sections[0].vsz) break;
if (!(dest=cli_malloc(dsize))) {
cli_errmsg("NsPack: Unable to allocate memory for dest %u\n", dsize);
break;
}
/* memset(dest, 0xfc, dsize); */
if(!(src = fmap_need_off(map, start_of_stuff, ssize))) {
free(dest);
break;
}
/* memset(src, 0x00, ssize); */
eprva+=0x27a;
if (!(rep = cli_rawaddr(eprva, exe_sections, nsections, &err, fsize, hdr_size)) && err) {
free(dest);
break;
}
if(!(nbuff = fmap_need_off_once(map, rep, 5))) {
free(dest);
break;
}
fmap_unneed_off(map, start_of_stuff, ssize);
eprva=eprva+5+cli_readint32(nbuff+1);
cli_dbgmsg("NsPack: OEP = %08x\n", eprva);
#if HAVE_JSON
cli_jsonstr(pe_json, "Packer", "NsPack");
#endif
CLI_UNPTEMP("NsPack",(dest,exe_sections,0));
CLI_UNPRESULTS("NsPack",(unspack(src, dest, ctx, exe_sections[0].rva, EC32(optional_hdr32.ImageBase), eprva, ndesc)),0,(dest,0));
break;
}
/* to be continued ... */
/* !!!!!!!!!!!!!! PACKERS END HERE !!!!!!!!!!!!!! */
ctx->corrupted_input = corrupted_cur;
/* Bytecode BC_PE_UNPACKER hook */
bc_ctx = cli_bytecode_context_alloc();
if (!bc_ctx) {
cli_errmsg("cli_scanpe: can't allocate memory for bc_ctx\n");
return CL_EMEM;
}
cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections);
cli_bytecode_context_setctx(bc_ctx, ctx);
ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_UNPACKER, map);
switch (ret) {
case CL_VIRUS:
free(exe_sections);
cli_bytecode_context_destroy(bc_ctx);
return CL_VIRUS;
case CL_SUCCESS:
ndesc = cli_bytecode_context_getresult_file(bc_ctx, &tempfile);
cli_bytecode_context_destroy(bc_ctx);
if (ndesc != -1 && tempfile) {
CLI_UNPRESULTS("bytecode PE hook", 1, 1, (0));
}
break;
default:
cli_bytecode_context_destroy(bc_ctx);
}
free(exe_sections);
#if HAVE_JSON
if (cli_json_timeout_cycle_check(ctx, &toval) != CL_SUCCESS) {
return CL_ETIMEOUT;
}
#endif
if (SCAN_ALL && viruses_found)
return CL_VIRUS;
return CL_CLEAN;
}
int cli_peheader(fmap_t *map, struct cli_exe_info *peinfo)
{
uint16_t e_magic; /* DOS signature ("MZ") */
uint32_t e_lfanew; /* address of new exe header */
/* Obsolete - see below
uint32_t min = 0, max = 0;
*/
struct pe_image_file_hdr file_hdr;
union {
struct pe_image_optional_hdr64 opt64;
struct pe_image_optional_hdr32 opt32;
} pe_opt;
struct pe_image_section_hdr *section_hdr;
unsigned int i;
unsigned int err, pe_plus = 0;
uint32_t valign, falign, hdr_size;
size_t fsize;
ssize_t at;
struct pe_image_data_dir *dirs;
cli_dbgmsg("in cli_peheader\n");
fsize = map->len - peinfo->offset;
if(fmap_readn(map, &e_magic, peinfo->offset, sizeof(e_magic)) != sizeof(e_magic)) {
cli_dbgmsg("Can't read DOS signature\n");
return -1;
}
if(EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE && EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE_OLD) {
cli_dbgmsg("Invalid DOS signature\n");
return -1;
}
if(fmap_readn(map, &e_lfanew, peinfo->offset + 58 + sizeof(e_magic), sizeof(e_lfanew)) != sizeof(e_lfanew)) {
/* truncated header? */
return -1;
}
e_lfanew = EC32(e_lfanew);
if(!e_lfanew) {
cli_dbgmsg("Not a PE file\n");
return -1;
}
if(fmap_readn(map, &file_hdr, peinfo->offset + e_lfanew, sizeof(struct pe_image_file_hdr)) != sizeof(struct pe_image_file_hdr)) {
/* bad information in e_lfanew - probably not a PE file */
cli_dbgmsg("Can't read file header\n");
return -1;
}
if(EC32(file_hdr.Magic) != PE_IMAGE_NT_SIGNATURE) {
cli_dbgmsg("Invalid PE signature (probably NE file)\n");
return -1;
}
if ( (peinfo->nsections = EC16(file_hdr.NumberOfSections)) < 1 || peinfo->nsections > 96 ) return -1;
if (EC16(file_hdr.SizeOfOptionalHeader) < sizeof(struct pe_image_optional_hdr32)) {
cli_dbgmsg("SizeOfOptionalHeader too small\n");
return -1;
}
at = peinfo->offset + e_lfanew + sizeof(struct pe_image_file_hdr);
if(fmap_readn(map, &optional_hdr32, at, sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr32)) {
cli_dbgmsg("Can't read optional file header\n");
return -1;
}
at += sizeof(struct pe_image_optional_hdr32);
if(EC16(optional_hdr64.Magic)==PE32P_SIGNATURE) { /* PE+ */
if(EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr64)) {
cli_dbgmsg("Incorrect SizeOfOptionalHeader for PE32+\n");
return -1;
}
if(fmap_readn(map, &optional_hdr32 + 1, at, sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) {
cli_dbgmsg("Can't read optional file header\n");
return -1;
}
at += sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32);
hdr_size = EC32(optional_hdr64.SizeOfHeaders);
pe_plus=1;
} else { /* PE */
if (EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr32)) {
/* Seek to the end of the long header */
at += EC16(file_hdr.SizeOfOptionalHeader)-sizeof(struct pe_image_optional_hdr32);
}
hdr_size = EC32(optional_hdr32.SizeOfHeaders);
}
valign = (pe_plus)?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment);
falign = (pe_plus)?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment);
peinfo->hdr_size = hdr_size = PESALIGN(hdr_size, valign);
peinfo->section = (struct cli_exe_section *) cli_calloc(peinfo->nsections, sizeof(struct cli_exe_section));
if(!peinfo->section) {
cli_dbgmsg("Can't allocate memory for section headers\n");
return -1;
}
section_hdr = (struct pe_image_section_hdr *) cli_calloc(peinfo->nsections, sizeof(struct pe_image_section_hdr));
if(!section_hdr) {
cli_dbgmsg("Can't allocate memory for section headers\n");
free(peinfo->section);
peinfo->section = NULL;
return -1;
}
if(fmap_readn(map, section_hdr, at, peinfo->nsections * sizeof(struct pe_image_section_hdr)) != peinfo->nsections * sizeof(struct pe_image_section_hdr)) {
cli_dbgmsg("Can't read section header\n");
cli_dbgmsg("Possibly broken PE file\n");
free(section_hdr);
free(peinfo->section);
peinfo->section = NULL;
return -1;
}
at += sizeof(struct pe_image_section_hdr)*peinfo->nsections;
for(i = 0; falign!=0x200 && i<peinfo->nsections; i++) {
/* file alignment fallback mode - blah */
if (falign && section_hdr[i].SizeOfRawData && EC32(section_hdr[i].PointerToRawData)%falign && !(EC32(section_hdr[i].PointerToRawData)%0x200)) {
falign = 0x200;
}
}
for(i = 0; i < peinfo->nsections; i++) {
peinfo->section[i].rva = PEALIGN(EC32(section_hdr[i].VirtualAddress), valign);
peinfo->section[i].vsz = PESALIGN(EC32(section_hdr[i].VirtualSize), valign);
peinfo->section[i].raw = PEALIGN(EC32(section_hdr[i].PointerToRawData), falign);
peinfo->section[i].rsz = PESALIGN(EC32(section_hdr[i].SizeOfRawData), falign);
if (!peinfo->section[i].vsz && peinfo->section[i].rsz)
peinfo->section[i].vsz=PESALIGN(EC32(section_hdr[i].SizeOfRawData), valign);
if (peinfo->section[i].rsz && !CLI_ISCONTAINED(0, (uint32_t) fsize, peinfo->section[i].raw, peinfo->section[i].rsz))
peinfo->section[i].rsz = (fsize - peinfo->section[i].raw)*(fsize>peinfo->section[i].raw);
}
if(pe_plus) {
peinfo->ep = EC32(optional_hdr64.AddressOfEntryPoint);
dirs = optional_hdr64.DataDirectory;
} else {
peinfo->ep = EC32(optional_hdr32.AddressOfEntryPoint);
dirs = optional_hdr32.DataDirectory;
}
if(!(peinfo->ep = cli_rawaddr(peinfo->ep, peinfo->section, peinfo->nsections, &err, fsize, hdr_size)) && err) {
cli_dbgmsg("Broken PE file\n");
free(section_hdr);
free(peinfo->section);
peinfo->section = NULL;
return -1;
}
if(EC16(file_hdr.Characteristics) & 0x2000 || !dirs[2].Size)
peinfo->res_addr = 0;
else
peinfo->res_addr = EC32(dirs[2].VirtualAddress);
while(dirs[2].Size) {
struct vinfo_list vlist;
const uint8_t *vptr, *baseptr;
uint32_t rva, res_sz;
memset(&vlist, 0, sizeof(vlist));
findres(0x10, 0xffffffff, EC32(dirs[2].VirtualAddress), map, peinfo->section, peinfo->nsections, hdr_size, versioninfo_cb, &vlist);
if(!vlist.count) break; /* No version_information */
if(cli_hashset_init(&peinfo->vinfo, 32, 80)) {
cli_errmsg("cli_peheader: Unable to init vinfo hashset\n");
free(section_hdr);
free(peinfo->section);
peinfo->section = NULL;
return -1;
}
err = 0;
for(i=0; i<vlist.count; i++) { /* enum all version_information res - RESUMABLE */
cli_dbgmsg("cli_peheader: parsing version info @ rva %x (%u/%u)\n", vlist.rvas[i], i+1, vlist.count);
rva = cli_rawaddr(vlist.rvas[i], peinfo->section, peinfo->nsections, &err, fsize, hdr_size);
if(err)
continue;
if(!(vptr = fmap_need_off_once(map, rva, 16)))
continue;
baseptr = vptr - rva;
/* parse resource */
rva = cli_readint32(vptr); /* ptr to version_info */
res_sz = cli_readint32(vptr+4); /* sizeof(resource) */
rva = cli_rawaddr(rva, peinfo->section, peinfo->nsections, &err, fsize, hdr_size);
if(err)
continue;
if(!(vptr = fmap_need_off_once(map, rva, res_sz)))
continue;
while(res_sz>4) { /* look for version_info - NOT RESUMABLE (expecting exactly one versioninfo) */
uint32_t vinfo_sz, vinfo_val_sz, got_varfileinfo = 0;
vinfo_sz = vinfo_val_sz = cli_readint32(vptr);
vinfo_sz &= 0xffff;
if(vinfo_sz > res_sz)
break; /* the content is larger than the container */
vinfo_val_sz >>= 16;
if(vinfo_sz <= 6 + 0x20 + 2 + 0x34 ||
vinfo_val_sz != 0x34 ||
memcmp(vptr+6, "V\0S\0_\0V\0E\0R\0S\0I\0O\0N\0_\0I\0N\0F\0O\0\0\0", 0x20) ||
(unsigned int)cli_readint32(vptr + 0x28) != 0xfeef04bd) {
/* - there should be enough room for the header(6), the key "VS_VERSION_INFO"(20), the padding(2) and the value(34)
* - the value should be sizeof(fixedfileinfo)
* - the key should match
* - there should be some proper magic for fixedfileinfo */
break; /* there's no point in looking further */
}
/* move to the end of fixedfileinfo where the child elements are located */
vptr += 6 + 0x20 + 2 + 0x34;
vinfo_sz -= 6 + 0x20 + 2 + 0x34;
while(vinfo_sz > 6) { /* look for stringfileinfo - NOT RESUMABLE (expecting at most one stringfileinfo) */
uint32_t sfi_sz = cli_readint32(vptr) & 0xffff;
if(sfi_sz > vinfo_sz)
break; /* the content is larger than the container */
if(!got_varfileinfo && sfi_sz > 6 + 0x18 && !memcmp(vptr+6, "V\0a\0r\0F\0i\0l\0e\0I\0n\0f\0o\0\0\0", 0x18)) {
/* skip varfileinfo as it sometimes appear before stringtableinfo */
vptr += sfi_sz;
vinfo_sz -= sfi_sz;
got_varfileinfo = 1;
continue;
}
if(sfi_sz <= 6 + 0x1e || memcmp(vptr+6, "S\0t\0r\0i\0n\0g\0F\0i\0l\0e\0I\0n\0f\0o\0\0\0", 0x1e)) {
/* - there should be enough room for the header(6) and the key "StringFileInfo"(1e)
* - the key should match */
break; /* this is an implicit hard fail: parent is not resumable */
}
/* move to the end of stringfileinfo where the child elements are located */
vptr += 6 + 0x1e;
sfi_sz -= 6 + 0x1e;
while(sfi_sz > 6) { /* enum all stringtables - RESUMABLE */
uint32_t st_sz = cli_readint32(vptr) & 0xffff;
const uint8_t *next_vptr = vptr + st_sz;
uint32_t next_sfi_sz = sfi_sz - st_sz;
if(st_sz > sfi_sz || st_sz <= 24) {
/* - the content is larger than the container
- there's no room for a stringtables (headers(6) + key(16) + padding(2)) */
break; /* this is an implicit hard fail: parent is not resumable */
}
/* move to the end of stringtable where the child elements are located */
vptr += 24;
st_sz -= 24;
while(st_sz > 6) { /* enum all strings - RESUMABLE */
uint32_t s_sz, s_key_sz, s_val_sz;
s_sz = (cli_readint32(vptr) & 0xffff) + 3;
s_sz &= ~3;
if(s_sz > st_sz || s_sz <= 6 + 2 + 8) {
/* - the content is larger than the container
* - there's no room for a minimal string
* - there's no room for the value */
st_sz = 0;
sfi_sz = 0;
break; /* force a hard fail */
}
/* ~wcstrlen(key) */
for(s_key_sz = 6; s_key_sz+1 < s_sz; s_key_sz += 2) {
if(vptr[s_key_sz] || vptr[s_key_sz+1]) continue;
s_key_sz += 2;
break;
}
s_key_sz += 3;
s_key_sz &= ~3;
if(s_key_sz >= s_sz) {
/* key overflow */
vptr += s_sz;
st_sz -= s_sz;
continue;
}
s_val_sz = s_sz - s_key_sz;
s_key_sz -= 6;
if(s_val_sz <= 2) {
/* skip unset value */
vptr += s_sz;
st_sz -= s_sz;
continue;
}
if(cli_hashset_addkey(&peinfo->vinfo, (uint32_t)(vptr - baseptr + 6))) {
cli_errmsg("cli_peheader: Unable to add rva to vinfo hashset\n");
cli_hashset_destroy(&peinfo->vinfo);
free(section_hdr);
free(peinfo->section);
peinfo->section = NULL;
return -1;
}
if(cli_debug_flag) {
char *k, *v, *s;
/* FIXME: skip too long strings */
k = cli_utf16toascii((const char*)vptr + 6, s_key_sz);
if(k) {
v = cli_utf16toascii((const char*)vptr + s_key_sz + 6, s_val_sz);
if(v) {
s = cli_str2hex((const char*)vptr + 6, s_key_sz + s_val_sz - 6);
if(s) {
cli_dbgmsg("VersionInfo (%x): '%s'='%s' - VI:%s\n", (uint32_t)(vptr - baseptr + 6), k, v, s);
free(s);
}
free(v);
}
free(k);
}
}
vptr += s_sz;
st_sz -= s_sz;
} /* enum all strings - RESUMABLE */
vptr = next_vptr;
sfi_sz = next_sfi_sz * (sfi_sz != 0);
} /* enum all stringtables - RESUMABLE */
break;
} /* look for stringfileinfo - NOT RESUMABLE */
break;
} /* look for version_info - NOT RESUMABLE */
} /* enum all version_information res - RESUMABLE */
break;
} /* while(dirs[2].Size) */
free(section_hdr);
return 0;
}
static int sort_sects(const void *first, const void *second) {
const struct cli_exe_section *a = first, *b = second;
return (a->raw - b->raw);
}
int cli_checkfp_pe(cli_ctx *ctx, uint8_t *authsha1, stats_section_t *hashes, uint32_t flags) {
uint16_t e_magic; /* DOS signature ("MZ") */
uint16_t nsections;
uint32_t e_lfanew; /* address of new exe header */
struct pe_image_file_hdr file_hdr;
union {
struct pe_image_optional_hdr64 opt64;
struct pe_image_optional_hdr32 opt32;
} pe_opt;
const struct pe_image_section_hdr *section_hdr;
ssize_t at;
unsigned int i, pe_plus = 0, hlen;
size_t fsize;
uint32_t valign, falign, hdr_size;
struct cli_exe_section *exe_sections;
struct pe_image_data_dir *dirs;
fmap_t *map = *ctx->fmap;
void *hashctx=NULL;
if (flags & CL_CHECKFP_PE_FLAG_STATS)
if (!(hashes))
return CL_EFORMAT;
if (flags == CL_CHECKFP_PE_FLAG_NONE)
return CL_VIRUS;
if(!(DCONF & PE_CONF_CATALOG))
return CL_EFORMAT;
if(fmap_readn(map, &e_magic, 0, sizeof(e_magic)) != sizeof(e_magic))
return CL_EFORMAT;
if(EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE && EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE_OLD)
return CL_EFORMAT;
if(fmap_readn(map, &e_lfanew, 58 + sizeof(e_magic), sizeof(e_lfanew)) != sizeof(e_lfanew))
return CL_EFORMAT;
e_lfanew = EC32(e_lfanew);
if(!e_lfanew)
return CL_EFORMAT;
if(fmap_readn(map, &file_hdr, e_lfanew, sizeof(struct pe_image_file_hdr)) != sizeof(struct pe_image_file_hdr))
return CL_EFORMAT;
if(EC32(file_hdr.Magic) != PE_IMAGE_NT_SIGNATURE)
return CL_EFORMAT;
nsections = EC16(file_hdr.NumberOfSections);
if(nsections < 1 || nsections > 96)
return CL_EFORMAT;
if(EC16(file_hdr.SizeOfOptionalHeader) < sizeof(struct pe_image_optional_hdr32))
return CL_EFORMAT;
at = e_lfanew + sizeof(struct pe_image_file_hdr);
if(fmap_readn(map, &optional_hdr32, at, sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr32))
return CL_EFORMAT;
at += sizeof(struct pe_image_optional_hdr32);
/* This will be a chicken and egg problem until we drop 9x */
if(EC16(optional_hdr64.Magic)==PE32P_SIGNATURE) {
if(EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr64))
return CL_EFORMAT;
pe_plus = 1;
}
if(!pe_plus) { /* PE */
if (EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr32)) {
/* Seek to the end of the long header */
at += EC16(file_hdr.SizeOfOptionalHeader)-sizeof(struct pe_image_optional_hdr32);
}
hdr_size = EC32(optional_hdr32.SizeOfHeaders);
dirs = optional_hdr32.DataDirectory;
} else { /* PE+ */
size_t readlen = sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32);
/* read the remaining part of the header */
if((size_t)fmap_readn(map, &optional_hdr32 + 1, at, readlen) != readlen)
return CL_EFORMAT;
at += sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32);
hdr_size = EC32(optional_hdr64.SizeOfHeaders);
dirs = optional_hdr64.DataDirectory;
}
fsize = map->len;
valign = (pe_plus)?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment);
falign = (pe_plus)?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment);
section_hdr = fmap_need_off_once(map, at, sizeof(*section_hdr) * nsections);
if(!section_hdr)
return CL_EFORMAT;
at += sizeof(*section_hdr) * nsections;
exe_sections = (struct cli_exe_section *) cli_calloc(nsections, sizeof(struct cli_exe_section));
if(!exe_sections)
return CL_EMEM;
for(i = 0; falign!=0x200 && i<nsections; i++) {
/* file alignment fallback mode - blah */
if (falign && section_hdr[i].SizeOfRawData && EC32(section_hdr[i].PointerToRawData)%falign && !(EC32(section_hdr[i].PointerToRawData)%0x200))
falign = 0x200;
}
hdr_size = PESALIGN(hdr_size, falign); /* Aligned headers virtual size */
if (flags & CL_CHECKFP_PE_FLAG_STATS) {
hashes->nsections = nsections;
hashes->sections = cli_calloc(nsections, sizeof(struct cli_section_hash));
if (!(hashes->sections)) {
free(exe_sections);
return CL_EMEM;
}
}
for(i = 0; i < nsections; i++) {
exe_sections[i].rva = PEALIGN(EC32(section_hdr[i].VirtualAddress), valign);
exe_sections[i].vsz = PESALIGN(EC32(section_hdr[i].VirtualSize), valign);
exe_sections[i].raw = PEALIGN(EC32(section_hdr[i].PointerToRawData), falign);
exe_sections[i].rsz = PESALIGN(EC32(section_hdr[i].SizeOfRawData), falign);
if (!exe_sections[i].vsz && exe_sections[i].rsz)
exe_sections[i].vsz=PESALIGN(exe_sections[i].ursz, valign);
if (exe_sections[i].rsz && fsize>exe_sections[i].raw && !CLI_ISCONTAINED(0, (uint32_t) fsize, exe_sections[i].raw, exe_sections[i].rsz))
exe_sections[i].rsz = fsize - exe_sections[i].raw;
if (exe_sections[i].rsz && exe_sections[i].raw >= fsize) {
free(exe_sections);
return CL_EFORMAT;
}
if (exe_sections[i].urva>>31 || exe_sections[i].uvsz>>31 || (exe_sections[i].rsz && exe_sections[i].uraw>>31) || exe_sections[i].ursz>>31) {
free(exe_sections);
return CL_EFORMAT;
}
}
cli_qsort(exe_sections, nsections, sizeof(*exe_sections), sort_sects);
hashctx = cl_hash_init("sha1");
if (!(hashctx)) {
if (flags & CL_CHECKFP_PE_FLAG_AUTHENTICODE)
flags ^= CL_CHECKFP_PE_FLAG_AUTHENTICODE;
}
if (flags & CL_CHECKFP_PE_FLAG_AUTHENTICODE) {
/* Check to see if we have a security section. */
if(!cli_hm_have_size(ctx->engine->hm_fp, CLI_HASH_SHA1, 2) && dirs[4].Size < 8) {
if (flags & CL_CHECKFP_PE_FLAG_STATS) {
/* If stats is enabled, continue parsing the sample */
flags ^= CL_CHECKFP_PE_FLAG_AUTHENTICODE;
} else {
if (hashctx)
cl_hash_destroy(hashctx);
return CL_BREAK;
}
}
}
#define hash_chunk(where, size, isStatAble, section) \
do { \
const uint8_t *hptr; \
if(!(size)) break; \
if(!(hptr = fmap_need_off_once(map, where, size))){ \
free(exe_sections); \
if (hashctx) \
cl_hash_destroy(hashctx); \
return CL_EFORMAT; \
} \
if (flags & CL_CHECKFP_PE_FLAG_AUTHENTICODE && hashctx) \
cl_update_hash(hashctx, (void *)hptr, size); \
if (isStatAble && flags & CL_CHECKFP_PE_FLAG_STATS) { \
void *md5ctx; \
md5ctx = cl_hash_init("md5"); \
if (md5ctx) { \
cl_update_hash(md5ctx, (void *)hptr, size); \
cl_finish_hash(md5ctx, hashes->sections[section].md5); \
} \
} \
} while(0)
while (flags & CL_CHECKFP_PE_FLAG_AUTHENTICODE) {
/* MZ to checksum */
at = 0;
hlen = e_lfanew + sizeof(struct pe_image_file_hdr) + (pe_plus ? offsetof(struct pe_image_optional_hdr64, CheckSum) : offsetof(struct pe_image_optional_hdr32, CheckSum));
hash_chunk(0, hlen, 0, 0);
at = hlen + 4;
/* Checksum to security */
if(pe_plus)
hlen = offsetof(struct pe_image_optional_hdr64, DataDirectory[4]) - offsetof(struct pe_image_optional_hdr64, CheckSum) - 4;
else
hlen = offsetof(struct pe_image_optional_hdr32, DataDirectory[4]) - offsetof(struct pe_image_optional_hdr32, CheckSum) - 4;
hash_chunk(at, hlen, 0, 0);
at += hlen + 8;
if(at > hdr_size) {
if (flags & CL_CHECKFP_PE_FLAG_STATS) {
flags ^= CL_CHECKFP_PE_FLAG_AUTHENTICODE;
break;
} else {
free(exe_sections);
if (hashctx)
cl_hash_destroy(hashctx);
return CL_EFORMAT;
}
}
/* Security to End of header */
hlen = hdr_size - at;
hash_chunk(at, hlen, 0, 0);
at = hdr_size;
break;
}
/* Hash the sections */
for(i = 0; i < nsections; i++) {
if(!exe_sections[i].rsz)
continue;
hash_chunk(exe_sections[i].raw, exe_sections[i].rsz, 1, i);
if (flags & CL_CHECKFP_PE_FLAG_AUTHENTICODE)
at += exe_sections[i].rsz;
}
while (flags & CL_CHECKFP_PE_FLAG_AUTHENTICODE) {
if((size_t)at < fsize) {
hlen = fsize - at;
if(dirs[4].Size > hlen) {
if (flags & CL_CHECKFP_PE_FLAG_STATS) {
flags ^= CL_CHECKFP_PE_FLAG_AUTHENTICODE;
break;
} else {
free(exe_sections);
if (hashctx)
cl_hash_destroy(hashctx);
return CL_EFORMAT;
}
}
hlen -= dirs[4].Size;
hash_chunk(at, hlen, 0, 0);
at += hlen;
}
break;
} while (0);
free(exe_sections);
if (flags & CL_CHECKFP_PE_FLAG_AUTHENTICODE && hashctx) {
cl_finish_hash(hashctx, authsha1);
if(cli_debug_flag) {
char shatxt[SHA1_HASH_SIZE*2+1];
for(i=0; i<SHA1_HASH_SIZE; i++)
sprintf(&shatxt[i*2], "%02x", authsha1[i]);
cli_dbgmsg("Authenticode: %s\n", shatxt);
}
hlen = dirs[4].Size;
if(hlen < 8)
return CL_VIRUS;
hlen -= 8;
return asn1_check_mscat((struct cl_engine *)(ctx->engine), map, at + 8, hlen, authsha1);
} else {
if (hashctx)
cl_hash_destroy(hashctx);
return CL_VIRUS;
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2346_0 |
crossvul-cpp_data_bad_2400_0 | /*
* Copyright (c) Ian F. Darwin 1986-1995.
* Software written by Ian F. Darwin and others;
* maintained 1995-present by Christos Zoulas and others.
*
* 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.
*/
/*
* softmagic - interpret variable magic from MAGIC
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: softmagic.c,v 1.195 2014/09/24 19:49:07 christos Exp $")
#endif /* lint */
#include "magic.h"
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>
private int match(struct magic_set *, struct magic *, uint32_t,
const unsigned char *, size_t, size_t, int, int, int, int, int *, int *,
int *);
private int mget(struct magic_set *, const unsigned char *,
struct magic *, size_t, size_t, unsigned int, int, int, int, int, int *,
int *, int *);
private int magiccheck(struct magic_set *, struct magic *);
private int32_t mprint(struct magic_set *, struct magic *);
private int32_t moffset(struct magic_set *, struct magic *);
private void mdebug(uint32_t, const char *, size_t);
private int mcopy(struct magic_set *, union VALUETYPE *, int, int,
const unsigned char *, uint32_t, size_t, struct magic *);
private int mconvert(struct magic_set *, struct magic *, int);
private int print_sep(struct magic_set *, int);
private int handle_annotation(struct magic_set *, struct magic *);
private void cvt_8(union VALUETYPE *, const struct magic *);
private void cvt_16(union VALUETYPE *, const struct magic *);
private void cvt_32(union VALUETYPE *, const struct magic *);
private void cvt_64(union VALUETYPE *, const struct magic *);
#define OFFSET_OOB(n, o, i) ((n) < (o) || (i) > ((n) - (o)))
/*
* softmagic - lookup one file in parsed, in-memory copy of database
* Passed the name and FILE * of one file to be typed.
*/
/*ARGSUSED1*/ /* nbytes passed for regularity, maybe need later */
protected int
file_softmagic(struct magic_set *ms, const unsigned char *buf, size_t nbytes,
size_t level, int mode, int text)
{
struct mlist *ml;
int rv, printed_something = 0, need_separator = 0;
for (ml = ms->mlist[0]->next; ml != ms->mlist[0]; ml = ml->next)
if ((rv = match(ms, ml->magic, ml->nmagic, buf, nbytes, 0, mode,
text, 0, level, &printed_something, &need_separator,
NULL)) != 0)
return rv;
return 0;
}
#define FILE_FMTDEBUG
#ifdef FILE_FMTDEBUG
#define F(a, b, c) file_fmtcheck((a), (b), (c), __FILE__, __LINE__)
private const char * __attribute__((__format_arg__(3)))
file_fmtcheck(struct magic_set *ms, const struct magic *m, const char *def,
const char *file, size_t line)
{
const char *ptr = fmtcheck(m->desc, def);
if (ptr == def)
file_magerror(ms,
"%s, %" SIZE_T_FORMAT "u: format `%s' does not match"
" with `%s'", file, line, m->desc, def);
return ptr;
}
#else
#define F(a, b, c) fmtcheck((b)->desc, (c))
#endif
/*
* Go through the whole list, stopping if you find a match. Process all
* the continuations of that match before returning.
*
* We support multi-level continuations:
*
* At any time when processing a successful top-level match, there is a
* current continuation level; it represents the level of the last
* successfully matched continuation.
*
* Continuations above that level are skipped as, if we see one, it
* means that the continuation that controls them - i.e, the
* lower-level continuation preceding them - failed to match.
*
* Continuations below that level are processed as, if we see one,
* it means we've finished processing or skipping higher-level
* continuations under the control of a successful or unsuccessful
* lower-level continuation, and are now seeing the next lower-level
* continuation and should process it. The current continuation
* level reverts to the level of the one we're seeing.
*
* Continuations at the current level are processed as, if we see
* one, there's no lower-level continuation that may have failed.
*
* If a continuation matches, we bump the current continuation level
* so that higher-level continuations are processed.
*/
private int
match(struct magic_set *ms, struct magic *magic, uint32_t nmagic,
const unsigned char *s, size_t nbytes, size_t offset, int mode, int text,
int flip, int recursion_level, int *printed_something, int *need_separator,
int *returnval)
{
uint32_t magindex = 0;
unsigned int cont_level = 0;
int returnvalv = 0, e; /* if a match is found it is set to 1*/
int firstline = 1; /* a flag to print X\n X\n- X */
int print = (ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0;
if (returnval == NULL)
returnval = &returnvalv;
if (file_check_mem(ms, cont_level) == -1)
return -1;
for (magindex = 0; magindex < nmagic; magindex++) {
int flush = 0;
struct magic *m = &magic[magindex];
if (m->type != FILE_NAME)
if ((IS_STRING(m->type) &&
#define FLT (STRING_BINTEST | STRING_TEXTTEST)
((text && (m->str_flags & FLT) == STRING_BINTEST) ||
(!text && (m->str_flags & FLT) == STRING_TEXTTEST))) ||
(m->flag & mode) != mode) {
/* Skip sub-tests */
while (magindex + 1 < nmagic &&
magic[magindex + 1].cont_level != 0 &&
++magindex)
continue;
continue; /* Skip to next top-level test*/
}
ms->offset = m->offset;
ms->line = m->lineno;
/* if main entry matches, print it... */
switch (mget(ms, s, m, nbytes, offset, cont_level, mode, text,
flip, recursion_level + 1, printed_something,
need_separator, returnval)) {
case -1:
return -1;
case 0:
flush = m->reln != '!';
break;
default:
if (m->type == FILE_INDIRECT)
*returnval = 1;
switch (magiccheck(ms, m)) {
case -1:
return -1;
case 0:
flush++;
break;
default:
flush = 0;
break;
}
break;
}
if (flush) {
/*
* main entry didn't match,
* flush its continuations
*/
while (magindex < nmagic - 1 &&
magic[magindex + 1].cont_level != 0)
magindex++;
continue;
}
if ((e = handle_annotation(ms, m)) != 0) {
*need_separator = 1;
*printed_something = 1;
*returnval = 1;
return e;
}
/*
* If we are going to print something, we'll need to print
* a blank before we print something else.
*/
if (*m->desc) {
*need_separator = 1;
*printed_something = 1;
if (print_sep(ms, firstline) == -1)
return -1;
}
if (print && mprint(ms, m) == -1)
return -1;
ms->c.li[cont_level].off = moffset(ms, m);
/* and any continuations that match */
if (file_check_mem(ms, ++cont_level) == -1)
return -1;
while (magindex + 1 < nmagic &&
magic[magindex + 1].cont_level != 0) {
m = &magic[++magindex];
ms->line = m->lineno; /* for messages */
if (cont_level < m->cont_level)
continue;
if (cont_level > m->cont_level) {
/*
* We're at the end of the level
* "cont_level" continuations.
*/
cont_level = m->cont_level;
}
ms->offset = m->offset;
if (m->flag & OFFADD) {
ms->offset +=
ms->c.li[cont_level - 1].off;
}
#ifdef ENABLE_CONDITIONALS
if (m->cond == COND_ELSE ||
m->cond == COND_ELIF) {
if (ms->c.li[cont_level].last_match == 1)
continue;
}
#endif
switch (mget(ms, s, m, nbytes, offset, cont_level, mode,
text, flip, recursion_level + 1, printed_something,
need_separator, returnval)) {
case -1:
return -1;
case 0:
if (m->reln != '!')
continue;
flush = 1;
break;
default:
if (m->type == FILE_INDIRECT)
*returnval = 1;
flush = 0;
break;
}
switch (flush ? 1 : magiccheck(ms, m)) {
case -1:
return -1;
case 0:
#ifdef ENABLE_CONDITIONALS
ms->c.li[cont_level].last_match = 0;
#endif
break;
default:
#ifdef ENABLE_CONDITIONALS
ms->c.li[cont_level].last_match = 1;
#endif
if (m->type == FILE_CLEAR)
ms->c.li[cont_level].got_match = 0;
else if (ms->c.li[cont_level].got_match) {
if (m->type == FILE_DEFAULT)
break;
} else
ms->c.li[cont_level].got_match = 1;
if ((e = handle_annotation(ms, m)) != 0) {
*need_separator = 1;
*printed_something = 1;
*returnval = 1;
return e;
}
/*
* If we are going to print something,
* make sure that we have a separator first.
*/
if (*m->desc) {
if (!*printed_something) {
*printed_something = 1;
if (print_sep(ms, firstline)
== -1)
return -1;
}
}
/*
* This continuation matched. Print
* its message, with a blank before it
* if the previous item printed and
* this item isn't empty.
*/
/* space if previous printed */
if (*need_separator
&& ((m->flag & NOSPACE) == 0)
&& *m->desc) {
if (print &&
file_printf(ms, " ") == -1)
return -1;
*need_separator = 0;
}
if (print && mprint(ms, m) == -1)
return -1;
ms->c.li[cont_level].off = moffset(ms, m);
if (*m->desc)
*need_separator = 1;
/*
* If we see any continuations
* at a higher level,
* process them.
*/
if (file_check_mem(ms, ++cont_level) == -1)
return -1;
break;
}
}
if (*printed_something) {
firstline = 0;
if (print)
*returnval = 1;
}
if ((ms->flags & MAGIC_CONTINUE) == 0 && *printed_something) {
return *returnval; /* don't keep searching */
}
}
return *returnval; /* This is hit if -k is set or there is no match */
}
private int
check_fmt(struct magic_set *ms, struct magic *m)
{
file_regex_t rx;
int rc, rv = -1;
if (strchr(m->desc, '%') == NULL)
return 0;
rc = file_regcomp(&rx, "%[-0-9\\.]*s", REG_EXTENDED|REG_NOSUB);
if (rc) {
file_regerror(&rx, rc, ms);
} else {
rc = file_regexec(&rx, m->desc, 0, 0, 0);
rv = !rc;
}
file_regfree(&rx);
return rv;
}
#ifndef HAVE_STRNDUP
char * strndup(const char *, size_t);
char *
strndup(const char *str, size_t n)
{
size_t len;
char *copy;
for (len = 0; len < n && str[len]; len++)
continue;
if ((copy = malloc(len + 1)) == NULL)
return NULL;
(void)memcpy(copy, str, len);
copy[len] = '\0';
return copy;
}
#endif /* HAVE_STRNDUP */
static char *
printable(char *buf, size_t bufsiz, const char *str)
{
char *ptr, *eptr;
const unsigned char *s = (const unsigned char *)str;
for (ptr = buf, eptr = ptr + bufsiz - 1; ptr < eptr && *s; s++) {
if (isprint(*s)) {
*ptr++ = *s;
continue;
}
if (ptr >= eptr + 4)
break;
*ptr++ = '\\';
*ptr++ = ((*s >> 6) & 7) + '0';
*ptr++ = ((*s >> 3) & 7) + '0';
*ptr++ = ((*s >> 0) & 7) + '0';
}
*ptr = '\0';
return buf;
}
private int32_t
mprint(struct magic_set *ms, struct magic *m)
{
uint64_t v;
float vf;
double vd;
int64_t t = 0;
char buf[128], tbuf[26];
union VALUETYPE *p = &ms->ms_value;
switch (m->type) {
case FILE_BYTE:
v = file_signextend(ms, m, (uint64_t)p->b);
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%d",
(unsigned char)v);
if (file_printf(ms, F(ms, m, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, m, "%d"),
(unsigned char) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(char);
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
v = file_signextend(ms, m, (uint64_t)p->h);
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%u",
(unsigned short)v);
if (file_printf(ms, F(ms, m, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, m, "%u"),
(unsigned short) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(short);
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
v = file_signextend(ms, m, (uint64_t)p->l);
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%u", (uint32_t) v);
if (file_printf(ms, F(ms, m, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, m, "%u"), (uint32_t) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(int32_t);
break;
case FILE_QUAD:
case FILE_BEQUAD:
case FILE_LEQUAD:
v = file_signextend(ms, m, p->q);
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%" INT64_T_FORMAT "u",
(unsigned long long)v);
if (file_printf(ms, F(ms, m, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, m, "%" INT64_T_FORMAT "u"),
(unsigned long long) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(int64_t);
break;
case FILE_STRING:
case FILE_PSTRING:
case FILE_BESTRING16:
case FILE_LESTRING16:
if (m->reln == '=' || m->reln == '!') {
if (file_printf(ms, F(ms, m, "%s"), m->value.s) == -1)
return -1;
t = ms->offset + m->vallen;
}
else {
char sbuf[512];
char *str = p->s;
/* compute t before we mangle the string? */
t = ms->offset + strlen(str);
if (*m->value.s == '\0')
str[strcspn(str, "\n")] = '\0';
if (m->str_flags & STRING_TRIM) {
char *last;
while (isspace((unsigned char)*str))
str++;
last = str;
while (*last)
last++;
--last;
while (isspace((unsigned char)*last))
last--;
*++last = '\0';
}
if (file_printf(ms, F(ms, m, "%s"),
printable(sbuf, sizeof(sbuf), str)) == -1)
return -1;
if (m->type == FILE_PSTRING)
t += file_pstring_length_size(m);
}
break;
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
if (file_printf(ms, F(ms, m, "%s"),
file_fmttime(p->l + m->num_mask, FILE_T_LOCAL, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint32_t);
break;
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
if (file_printf(ms, F(ms, m, "%s"),
file_fmttime(p->l + m->num_mask, 0, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint32_t);
break;
case FILE_QDATE:
case FILE_BEQDATE:
case FILE_LEQDATE:
if (file_printf(ms, F(ms, m, "%s"),
file_fmttime(p->q + m->num_mask, FILE_T_LOCAL, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint64_t);
break;
case FILE_QLDATE:
case FILE_BEQLDATE:
case FILE_LEQLDATE:
if (file_printf(ms, F(ms, m, "%s"),
file_fmttime(p->q + m->num_mask, 0, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint64_t);
break;
case FILE_QWDATE:
case FILE_BEQWDATE:
case FILE_LEQWDATE:
if (file_printf(ms, F(ms, m, "%s"),
file_fmttime(p->q + m->num_mask, FILE_T_WINDOWS, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint64_t);
break;
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
vf = p->f;
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%g", vf);
if (file_printf(ms, F(ms, m, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, m, "%g"), vf) == -1)
return -1;
break;
}
t = ms->offset + sizeof(float);
break;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
vd = p->d;
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%g", vd);
if (file_printf(ms, F(ms, m, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, m, "%g"), vd) == -1)
return -1;
break;
}
t = ms->offset + sizeof(double);
break;
case FILE_REGEX: {
char *cp;
int rval;
cp = strndup((const char *)ms->search.s, ms->search.rm_len);
if (cp == NULL) {
file_oomem(ms, ms->search.rm_len);
return -1;
}
rval = file_printf(ms, F(ms, m, "%s"), cp);
free(cp);
if (rval == -1)
return -1;
if ((m->str_flags & REGEX_OFFSET_START))
t = ms->search.offset;
else
t = ms->search.offset + ms->search.rm_len;
break;
}
case FILE_SEARCH:
if (file_printf(ms, F(ms, m, "%s"), m->value.s) == -1)
return -1;
if ((m->str_flags & REGEX_OFFSET_START))
t = ms->search.offset;
else
t = ms->search.offset + m->vallen;
break;
case FILE_DEFAULT:
case FILE_CLEAR:
if (file_printf(ms, "%s", m->desc) == -1)
return -1;
t = ms->offset;
break;
case FILE_INDIRECT:
case FILE_USE:
case FILE_NAME:
t = ms->offset;
break;
default:
file_magerror(ms, "invalid m->type (%d) in mprint()", m->type);
return -1;
}
return (int32_t)t;
}
private int32_t
moffset(struct magic_set *ms, struct magic *m)
{
switch (m->type) {
case FILE_BYTE:
return CAST(int32_t, (ms->offset + sizeof(char)));
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
return CAST(int32_t, (ms->offset + sizeof(short)));
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
return CAST(int32_t, (ms->offset + sizeof(int32_t)));
case FILE_QUAD:
case FILE_BEQUAD:
case FILE_LEQUAD:
return CAST(int32_t, (ms->offset + sizeof(int64_t)));
case FILE_STRING:
case FILE_PSTRING:
case FILE_BESTRING16:
case FILE_LESTRING16:
if (m->reln == '=' || m->reln == '!')
return ms->offset + m->vallen;
else {
union VALUETYPE *p = &ms->ms_value;
uint32_t t;
if (*m->value.s == '\0')
p->s[strcspn(p->s, "\n")] = '\0';
t = CAST(uint32_t, (ms->offset + strlen(p->s)));
if (m->type == FILE_PSTRING)
t += (uint32_t)file_pstring_length_size(m);
return t;
}
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
return CAST(int32_t, (ms->offset + sizeof(uint32_t)));
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
return CAST(int32_t, (ms->offset + sizeof(uint32_t)));
case FILE_QDATE:
case FILE_BEQDATE:
case FILE_LEQDATE:
return CAST(int32_t, (ms->offset + sizeof(uint64_t)));
case FILE_QLDATE:
case FILE_BEQLDATE:
case FILE_LEQLDATE:
return CAST(int32_t, (ms->offset + sizeof(uint64_t)));
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
return CAST(int32_t, (ms->offset + sizeof(float)));
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
return CAST(int32_t, (ms->offset + sizeof(double)));
case FILE_REGEX:
if ((m->str_flags & REGEX_OFFSET_START) != 0)
return CAST(int32_t, ms->search.offset);
else
return CAST(int32_t, (ms->search.offset +
ms->search.rm_len));
case FILE_SEARCH:
if ((m->str_flags & REGEX_OFFSET_START) != 0)
return CAST(int32_t, ms->search.offset);
else
return CAST(int32_t, (ms->search.offset + m->vallen));
case FILE_CLEAR:
case FILE_DEFAULT:
case FILE_INDIRECT:
return ms->offset;
default:
return 0;
}
}
private int
cvt_flip(int type, int flip)
{
if (flip == 0)
return type;
switch (type) {
case FILE_BESHORT:
return FILE_LESHORT;
case FILE_BELONG:
return FILE_LELONG;
case FILE_BEDATE:
return FILE_LEDATE;
case FILE_BELDATE:
return FILE_LELDATE;
case FILE_BEQUAD:
return FILE_LEQUAD;
case FILE_BEQDATE:
return FILE_LEQDATE;
case FILE_BEQLDATE:
return FILE_LEQLDATE;
case FILE_BEQWDATE:
return FILE_LEQWDATE;
case FILE_LESHORT:
return FILE_BESHORT;
case FILE_LELONG:
return FILE_BELONG;
case FILE_LEDATE:
return FILE_BEDATE;
case FILE_LELDATE:
return FILE_BELDATE;
case FILE_LEQUAD:
return FILE_BEQUAD;
case FILE_LEQDATE:
return FILE_BEQDATE;
case FILE_LEQLDATE:
return FILE_BEQLDATE;
case FILE_LEQWDATE:
return FILE_BEQWDATE;
case FILE_BEFLOAT:
return FILE_LEFLOAT;
case FILE_LEFLOAT:
return FILE_BEFLOAT;
case FILE_BEDOUBLE:
return FILE_LEDOUBLE;
case FILE_LEDOUBLE:
return FILE_BEDOUBLE;
default:
return type;
}
}
#define DO_CVT(fld, cast) \
if (m->num_mask) \
switch (m->mask_op & FILE_OPS_MASK) { \
case FILE_OPAND: \
p->fld &= cast m->num_mask; \
break; \
case FILE_OPOR: \
p->fld |= cast m->num_mask; \
break; \
case FILE_OPXOR: \
p->fld ^= cast m->num_mask; \
break; \
case FILE_OPADD: \
p->fld += cast m->num_mask; \
break; \
case FILE_OPMINUS: \
p->fld -= cast m->num_mask; \
break; \
case FILE_OPMULTIPLY: \
p->fld *= cast m->num_mask; \
break; \
case FILE_OPDIVIDE: \
p->fld /= cast m->num_mask; \
break; \
case FILE_OPMODULO: \
p->fld %= cast m->num_mask; \
break; \
} \
if (m->mask_op & FILE_OPINVERSE) \
p->fld = ~p->fld \
private void
cvt_8(union VALUETYPE *p, const struct magic *m)
{
DO_CVT(b, (uint8_t));
}
private void
cvt_16(union VALUETYPE *p, const struct magic *m)
{
DO_CVT(h, (uint16_t));
}
private void
cvt_32(union VALUETYPE *p, const struct magic *m)
{
DO_CVT(l, (uint32_t));
}
private void
cvt_64(union VALUETYPE *p, const struct magic *m)
{
DO_CVT(q, (uint64_t));
}
#define DO_CVT2(fld, cast) \
if (m->num_mask) \
switch (m->mask_op & FILE_OPS_MASK) { \
case FILE_OPADD: \
p->fld += cast m->num_mask; \
break; \
case FILE_OPMINUS: \
p->fld -= cast m->num_mask; \
break; \
case FILE_OPMULTIPLY: \
p->fld *= cast m->num_mask; \
break; \
case FILE_OPDIVIDE: \
p->fld /= cast m->num_mask; \
break; \
} \
private void
cvt_float(union VALUETYPE *p, const struct magic *m)
{
DO_CVT2(f, (float));
}
private void
cvt_double(union VALUETYPE *p, const struct magic *m)
{
DO_CVT2(d, (double));
}
/*
* Convert the byte order of the data we are looking at
* While we're here, let's apply the mask operation
* (unless you have a better idea)
*/
private int
mconvert(struct magic_set *ms, struct magic *m, int flip)
{
union VALUETYPE *p = &ms->ms_value;
uint8_t type;
switch (type = cvt_flip(m->type, flip)) {
case FILE_BYTE:
cvt_8(p, m);
return 1;
case FILE_SHORT:
cvt_16(p, m);
return 1;
case FILE_LONG:
case FILE_DATE:
case FILE_LDATE:
cvt_32(p, m);
return 1;
case FILE_QUAD:
case FILE_QDATE:
case FILE_QLDATE:
case FILE_QWDATE:
cvt_64(p, m);
return 1;
case FILE_STRING:
case FILE_BESTRING16:
case FILE_LESTRING16: {
/* Null terminate and eat *trailing* return */
p->s[sizeof(p->s) - 1] = '\0';
return 1;
}
case FILE_PSTRING: {
size_t sz = file_pstring_length_size(m);
char *ptr1 = p->s, *ptr2 = ptr1 + sz;
size_t len = file_pstring_get_length(m, ptr1);
if (len >= sizeof(p->s)) {
/*
* The size of the pascal string length (sz)
* is 1, 2, or 4. We need at least 1 byte for NUL
* termination, but we've already truncated the
* string by p->s, so we need to deduct sz.
*/
len = sizeof(p->s) - sz;
}
while (len--)
*ptr1++ = *ptr2++;
*ptr1 = '\0';
return 1;
}
case FILE_BESHORT:
p->h = (short)((p->hs[0]<<8)|(p->hs[1]));
cvt_16(p, m);
return 1;
case FILE_BELONG:
case FILE_BEDATE:
case FILE_BELDATE:
p->l = (int32_t)
((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3]));
if (type == FILE_BELONG)
cvt_32(p, m);
return 1;
case FILE_BEQUAD:
case FILE_BEQDATE:
case FILE_BEQLDATE:
case FILE_BEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7]));
if (type == FILE_BEQUAD)
cvt_64(p, m);
return 1;
case FILE_LESHORT:
p->h = (short)((p->hs[1]<<8)|(p->hs[0]));
cvt_16(p, m);
return 1;
case FILE_LELONG:
case FILE_LEDATE:
case FILE_LELDATE:
p->l = (int32_t)
((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0]));
if (type == FILE_LELONG)
cvt_32(p, m);
return 1;
case FILE_LEQUAD:
case FILE_LEQDATE:
case FILE_LEQLDATE:
case FILE_LEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0]));
if (type == FILE_LEQUAD)
cvt_64(p, m);
return 1;
case FILE_MELONG:
case FILE_MEDATE:
case FILE_MELDATE:
p->l = (int32_t)
((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2]));
if (type == FILE_MELONG)
cvt_32(p, m);
return 1;
case FILE_FLOAT:
cvt_float(p, m);
return 1;
case FILE_BEFLOAT:
p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)|
((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]);
cvt_float(p, m);
return 1;
case FILE_LEFLOAT:
p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)|
((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]);
cvt_float(p, m);
return 1;
case FILE_DOUBLE:
cvt_double(p, m);
return 1;
case FILE_BEDOUBLE:
p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]);
cvt_double(p, m);
return 1;
case FILE_LEDOUBLE:
p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]);
cvt_double(p, m);
return 1;
case FILE_REGEX:
case FILE_SEARCH:
case FILE_DEFAULT:
case FILE_CLEAR:
case FILE_NAME:
case FILE_USE:
return 1;
default:
file_magerror(ms, "invalid type %d in mconvert()", m->type);
return 0;
}
}
private void
mdebug(uint32_t offset, const char *str, size_t len)
{
(void) fprintf(stderr, "mget/%" SIZE_T_FORMAT "u @%d: ", len, offset);
file_showstr(stderr, str, len);
(void) fputc('\n', stderr);
(void) fputc('\n', stderr);
}
private int
mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir,
const unsigned char *s, uint32_t offset, size_t nbytes, struct magic *m)
{
/*
* Note: FILE_SEARCH and FILE_REGEX do not actually copy
* anything, but setup pointers into the source
*/
if (indir == 0) {
switch (type) {
case FILE_SEARCH:
ms->search.s = RCAST(const char *, s) + offset;
ms->search.s_len = nbytes - offset;
ms->search.offset = offset;
return 0;
case FILE_REGEX: {
const char *b;
const char *c;
const char *last; /* end of search region */
const char *buf; /* start of search region */
const char *end;
size_t lines, linecnt, bytecnt;
if (s == NULL) {
ms->search.s_len = 0;
ms->search.s = NULL;
return 0;
}
if (m->str_flags & REGEX_LINE_COUNT) {
linecnt = m->str_range;
bytecnt = linecnt * 80;
} else {
linecnt = 0;
bytecnt = m->str_range;
}
if (bytecnt == 0)
bytecnt = 8192;
if (bytecnt > nbytes)
bytecnt = nbytes;
buf = RCAST(const char *, s) + offset;
end = last = RCAST(const char *, s) + bytecnt;
/* mget() guarantees buf <= last */
for (lines = linecnt, b = buf; lines && b < end &&
((b = CAST(const char *,
memchr(c = b, '\n', CAST(size_t, (end - b)))))
|| (b = CAST(const char *,
memchr(c, '\r', CAST(size_t, (end - c))))));
lines--, b++) {
last = b;
if (b[0] == '\r' && b[1] == '\n')
b++;
}
if (lines)
last = RCAST(const char *, s) + bytecnt;
ms->search.s = buf;
ms->search.s_len = last - buf;
ms->search.offset = offset;
ms->search.rm_len = 0;
return 0;
}
case FILE_BESTRING16:
case FILE_LESTRING16: {
const unsigned char *src = s + offset;
const unsigned char *esrc = s + nbytes;
char *dst = p->s;
char *edst = &p->s[sizeof(p->s) - 1];
if (type == FILE_BESTRING16)
src++;
/* check that offset is within range */
if (offset >= nbytes)
break;
for (/*EMPTY*/; src < esrc; src += 2, dst++) {
if (dst < edst)
*dst = *src;
else
break;
if (*dst == '\0') {
if (type == FILE_BESTRING16 ?
*(src - 1) != '\0' :
*(src + 1) != '\0')
*dst = ' ';
}
}
*edst = '\0';
return 0;
}
case FILE_STRING: /* XXX - these two should not need */
case FILE_PSTRING: /* to copy anything, but do anyway. */
default:
break;
}
}
if (offset >= nbytes) {
(void)memset(p, '\0', sizeof(*p));
return 0;
}
if (nbytes - offset < sizeof(*p))
nbytes = nbytes - offset;
else
nbytes = sizeof(*p);
(void)memcpy(p, s + offset, nbytes);
/*
* the usefulness of padding with zeroes eludes me, it
* might even cause problems
*/
if (nbytes < sizeof(*p))
(void)memset(((char *)(void *)p) + nbytes, '\0',
sizeof(*p) - nbytes);
return 0;
}
private int
mget(struct magic_set *ms, const unsigned char *s, struct magic *m,
size_t nbytes, size_t o, unsigned int cont_level, int mode, int text,
int flip, int recursion_level, int *printed_something,
int *need_separator, int *returnval)
{
uint32_t soffset, offset = ms->offset;
uint32_t lhs;
int rv, oneed_separator, in_type;
char *sbuf, *rbuf;
union VALUETYPE *p = &ms->ms_value;
struct mlist ml;
if (recursion_level >= 20) {
file_error(ms, 0, "recursion nesting exceeded");
return -1;
}
if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o),
(uint32_t)nbytes, m) == -1)
return -1;
if ((ms->flags & MAGIC_DEBUG) != 0) {
fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%"
SIZE_T_FORMAT "u, " "nbytes=%" SIZE_T_FORMAT "u)\n",
m->type, m->flag, offset, o, nbytes);
mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE));
#ifndef COMPILE_ONLY
file_mdump(m);
#endif
}
if (m->flag & INDIR) {
int off = m->in_offset;
if (m->in_op & FILE_OPINDIRECT) {
const union VALUETYPE *q = CAST(const union VALUETYPE *,
((const void *)(s + offset + off)));
switch (cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
off = q->b;
break;
case FILE_SHORT:
off = q->h;
break;
case FILE_BESHORT:
off = (short)((q->hs[0]<<8)|(q->hs[1]));
break;
case FILE_LESHORT:
off = (short)((q->hs[1]<<8)|(q->hs[0]));
break;
case FILE_LONG:
off = q->l;
break;
case FILE_BELONG:
case FILE_BEID3:
off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)|
(q->hl[2]<<8)|(q->hl[3]));
break;
case FILE_LEID3:
case FILE_LELONG:
off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)|
(q->hl[1]<<8)|(q->hl[0]));
break;
case FILE_MELONG:
off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)|
(q->hl[3]<<8)|(q->hl[2]));
break;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect offs=%u\n", off);
}
switch (in_type = cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
if (OFFSET_OOB(nbytes, offset, 1))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->b & off;
break;
case FILE_OPOR:
offset = p->b | off;
break;
case FILE_OPXOR:
offset = p->b ^ off;
break;
case FILE_OPADD:
offset = p->b + off;
break;
case FILE_OPMINUS:
offset = p->b - off;
break;
case FILE_OPMULTIPLY:
offset = p->b * off;
break;
case FILE_OPDIVIDE:
offset = p->b / off;
break;
case FILE_OPMODULO:
offset = p->b % off;
break;
}
} else
offset = p->b;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
lhs = (p->hs[0] << 8) | p->hs[1];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
lhs = (p->hs[1] << 8) | p->hs[0];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_SHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->h & off;
break;
case FILE_OPOR:
offset = p->h | off;
break;
case FILE_OPXOR:
offset = p->h ^ off;
break;
case FILE_OPADD:
offset = p->h + off;
break;
case FILE_OPMINUS:
offset = p->h - off;
break;
case FILE_OPMULTIPLY:
offset = p->h * off;
break;
case FILE_OPDIVIDE:
offset = p->h / off;
break;
case FILE_OPMODULO:
offset = p->h % off;
break;
}
}
else
offset = p->h;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BELONG:
case FILE_BEID3:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
lhs = (p->hl[0] << 24) | (p->hl[1] << 16) |
(p->hl[2] << 8) | p->hl[3];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LELONG:
case FILE_LEID3:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
lhs = (p->hl[3] << 24) | (p->hl[2] << 16) |
(p->hl[1] << 8) | p->hl[0];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_MELONG:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
lhs = (p->hl[1] << 24) | (p->hl[0] << 16) |
(p->hl[3] << 8) | p->hl[2];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LONG:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->l & off;
break;
case FILE_OPOR:
offset = p->l | off;
break;
case FILE_OPXOR:
offset = p->l ^ off;
break;
case FILE_OPADD:
offset = p->l + off;
break;
case FILE_OPMINUS:
offset = p->l - off;
break;
case FILE_OPMULTIPLY:
offset = p->l * off;
break;
case FILE_OPDIVIDE:
offset = p->l / off;
break;
case FILE_OPMODULO:
offset = p->l % off;
break;
}
} else
offset = p->l;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
default:
break;
}
switch (in_type) {
case FILE_LEID3:
case FILE_BEID3:
offset = ((((offset >> 0) & 0x7f) << 0) |
(((offset >> 8) & 0x7f) << 7) |
(((offset >> 16) & 0x7f) << 14) |
(((offset >> 24) & 0x7f) << 21)) + 10;
break;
default:
break;
}
if (m->flag & INDIROFFADD) {
offset += ms->c.li[cont_level-1].off;
if (offset == 0) {
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr,
"indirect *zero* offset\n");
return 0;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect +offs=%u\n", offset);
}
if (mcopy(ms, p, m->type, 0, s, offset, nbytes, m) == -1)
return -1;
ms->offset = offset;
if ((ms->flags & MAGIC_DEBUG) != 0) {
mdebug(offset, (char *)(void *)p,
sizeof(union VALUETYPE));
#ifndef COMPILE_ONLY
file_mdump(m);
#endif
}
}
/* Verify we have enough data to match magic type */
switch (m->type) {
case FILE_BYTE:
if (OFFSET_OOB(nbytes, offset, 1))
return 0;
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
break;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
if (OFFSET_OOB(nbytes, offset, 8))
return 0;
break;
case FILE_STRING:
case FILE_PSTRING:
case FILE_SEARCH:
if (OFFSET_OOB(nbytes, offset, m->vallen))
return 0;
break;
case FILE_REGEX:
if (nbytes < offset)
return 0;
break;
case FILE_INDIRECT:
if (offset == 0)
return 0;
if (nbytes < offset)
return 0;
sbuf = ms->o.buf;
soffset = ms->offset;
ms->o.buf = NULL;
ms->offset = 0;
rv = file_softmagic(ms, s + offset, nbytes - offset,
recursion_level, BINTEST, text);
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv);
rbuf = ms->o.buf;
ms->o.buf = sbuf;
ms->offset = soffset;
if (rv == 1) {
if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 &&
file_printf(ms, F(ms, m, "%u"), offset) == -1) {
free(rbuf);
return -1;
}
if (file_printf(ms, "%s", rbuf) == -1) {
free(rbuf);
return -1;
}
}
free(rbuf);
return rv;
case FILE_USE:
if (nbytes < offset)
return 0;
sbuf = m->value.s;
if (*sbuf == '^') {
sbuf++;
flip = !flip;
}
if (file_magicfind(ms, sbuf, &ml) == -1) {
file_error(ms, 0, "cannot find entry `%s'", sbuf);
return -1;
}
oneed_separator = *need_separator;
if (m->flag & NOSPACE)
*need_separator = 0;
rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o,
mode, text, flip, recursion_level, printed_something,
need_separator, returnval);
if (rv != 1)
*need_separator = oneed_separator;
return rv;
case FILE_NAME:
if (file_printf(ms, "%s", m->desc) == -1)
return -1;
return 1;
case FILE_DEFAULT: /* nothing to check */
case FILE_CLEAR:
default:
break;
}
if (!mconvert(ms, m, flip))
return 0;
return 1;
}
private uint64_t
file_strncmp(const char *s1, const char *s2, size_t len, uint32_t flags)
{
/*
* Convert the source args to unsigned here so that (1) the
* compare will be unsigned as it is in strncmp() and (2) so
* the ctype functions will work correctly without extra
* casting.
*/
const unsigned char *a = (const unsigned char *)s1;
const unsigned char *b = (const unsigned char *)s2;
uint64_t v;
/*
* What we want here is v = strncmp(s1, s2, len),
* but ignoring any nulls.
*/
v = 0;
if (0L == flags) { /* normal string: do it fast */
while (len-- > 0)
if ((v = *b++ - *a++) != '\0')
break;
}
else { /* combine the others */
while (len-- > 0) {
if ((flags & STRING_IGNORE_LOWERCASE) &&
islower(*a)) {
if ((v = tolower(*b++) - *a++) != '\0')
break;
}
else if ((flags & STRING_IGNORE_UPPERCASE) &&
isupper(*a)) {
if ((v = toupper(*b++) - *a++) != '\0')
break;
}
else if ((flags & STRING_COMPACT_WHITESPACE) &&
isspace(*a)) {
a++;
if (isspace(*b++)) {
if (!isspace(*a))
while (isspace(*b))
b++;
}
else {
v = 1;
break;
}
}
else if ((flags & STRING_COMPACT_OPTIONAL_WHITESPACE) &&
isspace(*a)) {
a++;
while (isspace(*b))
b++;
}
else {
if ((v = *b++ - *a++) != '\0')
break;
}
}
}
return v;
}
private uint64_t
file_strncmp16(const char *a, const char *b, size_t len, uint32_t flags)
{
/*
* XXX - The 16-bit string compare probably needs to be done
* differently, especially if the flags are to be supported.
* At the moment, I am unsure.
*/
flags = 0;
return file_strncmp(a, b, len, flags);
}
private int
magiccheck(struct magic_set *ms, struct magic *m)
{
uint64_t l = m->value.q;
uint64_t v;
float fl, fv;
double dl, dv;
int matched;
union VALUETYPE *p = &ms->ms_value;
switch (m->type) {
case FILE_BYTE:
v = p->b;
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
v = p->h;
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
v = p->l;
break;
case FILE_QUAD:
case FILE_LEQUAD:
case FILE_BEQUAD:
case FILE_QDATE:
case FILE_BEQDATE:
case FILE_LEQDATE:
case FILE_QLDATE:
case FILE_BEQLDATE:
case FILE_LEQLDATE:
case FILE_QWDATE:
case FILE_BEQWDATE:
case FILE_LEQWDATE:
v = p->q;
break;
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
fl = m->value.f;
fv = p->f;
switch (m->reln) {
case 'x':
matched = 1;
break;
case '!':
matched = fv != fl;
break;
case '=':
matched = fv == fl;
break;
case '>':
matched = fv > fl;
break;
case '<':
matched = fv < fl;
break;
default:
file_magerror(ms, "cannot happen with float: invalid relation `%c'",
m->reln);
return -1;
}
return matched;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
dl = m->value.d;
dv = p->d;
switch (m->reln) {
case 'x':
matched = 1;
break;
case '!':
matched = dv != dl;
break;
case '=':
matched = dv == dl;
break;
case '>':
matched = dv > dl;
break;
case '<':
matched = dv < dl;
break;
default:
file_magerror(ms, "cannot happen with double: invalid relation `%c'", m->reln);
return -1;
}
return matched;
case FILE_DEFAULT:
case FILE_CLEAR:
l = 0;
v = 0;
break;
case FILE_STRING:
case FILE_PSTRING:
l = 0;
v = file_strncmp(m->value.s, p->s, (size_t)m->vallen, m->str_flags);
break;
case FILE_BESTRING16:
case FILE_LESTRING16:
l = 0;
v = file_strncmp16(m->value.s, p->s, (size_t)m->vallen, m->str_flags);
break;
case FILE_SEARCH: { /* search ms->search.s for the string m->value.s */
size_t slen;
size_t idx;
if (ms->search.s == NULL)
return 0;
slen = MIN(m->vallen, sizeof(m->value.s));
l = 0;
v = 0;
for (idx = 0; m->str_range == 0 || idx < m->str_range; idx++) {
if (slen + idx > ms->search.s_len)
break;
v = file_strncmp(m->value.s, ms->search.s + idx, slen,
m->str_flags);
if (v == 0) { /* found match */
ms->search.offset += idx;
break;
}
}
break;
}
case FILE_REGEX: {
int rc;
file_regex_t rx;
const char *search;
if (ms->search.s == NULL)
return 0;
l = 0;
rc = file_regcomp(&rx, m->value.s,
REG_EXTENDED|REG_NEWLINE|
((m->str_flags & STRING_IGNORE_CASE) ? REG_ICASE : 0));
if (rc) {
file_regerror(&rx, rc, ms);
v = (uint64_t)-1;
} else {
regmatch_t pmatch[1];
size_t slen = ms->search.s_len;
#ifndef REG_STARTEND
#define REG_STARTEND 0
char *copy;
if (slen != 0) {
copy = malloc(slen);
if (copy == NULL) {
file_error(ms, errno,
"can't allocate %" SIZE_T_FORMAT "u bytes",
slen);
return -1;
}
memcpy(copy, ms->search.s, slen);
copy[--slen] = '\0';
search = copy;
} else {
search = ms->search.s;
copy = NULL;
}
#else
search = ms->search.s;
pmatch[0].rm_so = 0;
pmatch[0].rm_eo = slen;
#endif
rc = file_regexec(&rx, (const char *)search,
1, pmatch, REG_STARTEND);
#if REG_STARTEND == 0
free(copy);
#endif
switch (rc) {
case 0:
ms->search.s += (int)pmatch[0].rm_so;
ms->search.offset += (size_t)pmatch[0].rm_so;
ms->search.rm_len =
(size_t)(pmatch[0].rm_eo - pmatch[0].rm_so);
v = 0;
break;
case REG_NOMATCH:
v = 1;
break;
default:
file_regerror(&rx, rc, ms);
v = (uint64_t)-1;
break;
}
}
file_regfree(&rx);
if (v == (uint64_t)-1)
return -1;
break;
}
case FILE_INDIRECT:
case FILE_USE:
case FILE_NAME:
return 1;
default:
file_magerror(ms, "invalid type %d in magiccheck()", m->type);
return -1;
}
v = file_signextend(ms, m, v);
switch (m->reln) {
case 'x':
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u == *any* = 1\n", (unsigned long long)v);
matched = 1;
break;
case '!':
matched = v != l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT "u != %"
INT64_T_FORMAT "u = %d\n", (unsigned long long)v,
(unsigned long long)l, matched);
break;
case '=':
matched = v == l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT "u == %"
INT64_T_FORMAT "u = %d\n", (unsigned long long)v,
(unsigned long long)l, matched);
break;
case '>':
if (m->flag & UNSIGNED) {
matched = v > l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u > %" INT64_T_FORMAT "u = %d\n",
(unsigned long long)v,
(unsigned long long)l, matched);
}
else {
matched = (int64_t) v > (int64_t) l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"d > %" INT64_T_FORMAT "d = %d\n",
(long long)v, (long long)l, matched);
}
break;
case '<':
if (m->flag & UNSIGNED) {
matched = v < l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u < %" INT64_T_FORMAT "u = %d\n",
(unsigned long long)v,
(unsigned long long)l, matched);
}
else {
matched = (int64_t) v < (int64_t) l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"d < %" INT64_T_FORMAT "d = %d\n",
(long long)v, (long long)l, matched);
}
break;
case '&':
matched = (v & l) == l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %"
INT64_T_FORMAT "x) == %" INT64_T_FORMAT
"x) = %d\n", (unsigned long long)v,
(unsigned long long)l, (unsigned long long)l,
matched);
break;
case '^':
matched = (v & l) != l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %"
INT64_T_FORMAT "x) != %" INT64_T_FORMAT
"x) = %d\n", (unsigned long long)v,
(unsigned long long)l, (unsigned long long)l,
matched);
break;
default:
file_magerror(ms, "cannot happen: invalid relation `%c'",
m->reln);
return -1;
}
return matched;
}
private int
handle_annotation(struct magic_set *ms, struct magic *m)
{
if (ms->flags & MAGIC_APPLE) {
if (file_printf(ms, "%.8s", m->apple) == -1)
return -1;
return 1;
}
if ((ms->flags & MAGIC_MIME_TYPE) && m->mimetype[0]) {
if (file_printf(ms, "%s", m->mimetype) == -1)
return -1;
return 1;
}
return 0;
}
private int
print_sep(struct magic_set *ms, int firstline)
{
if (ms->flags & MAGIC_MIME)
return 0;
if (firstline)
return 0;
/*
* we found another match
* put a newline and '-' to do some simple formatting
*/
return file_printf(ms, "\n- ");
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2400_0 |
crossvul-cpp_data_bad_2899_0 | /* radare - LGPL - Copyright 2008-2017 - nibble, pancake, alvaro_fe */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <r_types.h>
#include <r_util.h>
#include "elf.h"
#ifdef IFDBG
#undef IFDBG
#endif
#define DO_THE_DBG 0
#define IFDBG if (DO_THE_DBG)
#define IFINT if (0)
#define ELF_PAGE_MASK 0xFFFFFFFFFFFFF000LL
#define ELF_PAGE_SIZE 12
#define R_ELF_NO_RELRO 0
#define R_ELF_PART_RELRO 1
#define R_ELF_FULL_RELRO 2
#define bprintf if(bin->verbose)eprintf
#define READ8(x, i) r_read_ble8(x + i); i += 1;
#define READ16(x, i) r_read_ble16(x + i, bin->endian); i += 2;
#define READ32(x, i) r_read_ble32(x + i, bin->endian); i += 4;
#define READ64(x, i) r_read_ble64(x + i, bin->endian); i += 8;
#define GROWTH_FACTOR (1.5)
static inline int __strnlen(const char *str, int len) {
int l = 0;
while (IS_PRINTABLE (*str) && --len) {
if (((ut8)*str) == 0xff) {
break;
}
str++;
l++;
}
return l + 1;
}
static int handle_e_ident(ELFOBJ *bin) {
return !strncmp ((char *)bin->ehdr.e_ident, ELFMAG, SELFMAG) ||
!strncmp ((char *)bin->ehdr.e_ident, CGCMAG, SCGCMAG);
}
static int init_ehdr(ELFOBJ *bin) {
ut8 e_ident[EI_NIDENT];
ut8 ehdr[sizeof (Elf_(Ehdr))] = {0};
int i, len;
if (r_buf_read_at (bin->b, 0, e_ident, EI_NIDENT) == -1) {
bprintf ("Warning: read (magic)\n");
return false;
}
sdb_set (bin->kv, "elf_type.cparse", "enum elf_type { ET_NONE=0, ET_REL=1,"
" ET_EXEC=2, ET_DYN=3, ET_CORE=4, ET_LOOS=0xfe00, ET_HIOS=0xfeff,"
" ET_LOPROC=0xff00, ET_HIPROC=0xffff };", 0);
sdb_set (bin->kv, "elf_machine.cparse", "enum elf_machine{EM_NONE=0, EM_M32=1,"
" EM_SPARC=2, EM_386=3, EM_68K=4, EM_88K=5, EM_486=6, "
" EM_860=7, EM_MIPS=8, EM_S370=9, EM_MIPS_RS3_LE=10, EM_RS6000=11,"
" EM_UNKNOWN12=12, EM_UNKNOWN13=13, EM_UNKNOWN14=14, "
" EM_PA_RISC=15, EM_PARISC=EM_PA_RISC, EM_nCUBE=16, EM_VPP500=17,"
" EM_SPARC32PLUS=18, EM_960=19, EM_PPC=20, EM_PPC64=21, "
" EM_S390=22, EM_UNKNOWN22=EM_S390, EM_UNKNOWN23=23, EM_UNKNOWN24=24,"
" EM_UNKNOWN25=25, EM_UNKNOWN26=26, EM_UNKNOWN27=27, EM_UNKNOWN28=28,"
" EM_UNKNOWN29=29, EM_UNKNOWN30=30, EM_UNKNOWN31=31, EM_UNKNOWN32=32,"
" EM_UNKNOWN33=33, EM_UNKNOWN34=34, EM_UNKNOWN35=35, EM_V800=36,"
" EM_FR20=37, EM_RH32=38, EM_RCE=39, EM_ARM=40, EM_ALPHA=41, EM_SH=42,"
" EM_SPARCV9=43, EM_TRICORE=44, EM_ARC=45, EM_H8_300=46, EM_H8_300H=47,"
" EM_H8S=48, EM_H8_500=49, EM_IA_64=50, EM_MIPS_X=51, EM_COLDFIRE=52,"
" EM_68HC12=53, EM_MMA=54, EM_PCP=55, EM_NCPU=56, EM_NDR1=57,"
" EM_STARCORE=58, EM_ME16=59, EM_ST100=60, EM_TINYJ=61, EM_AMD64=62,"
" EM_X86_64=EM_AMD64, EM_PDSP=63, EM_UNKNOWN64=64, EM_UNKNOWN65=65,"
" EM_FX66=66, EM_ST9PLUS=67, EM_ST7=68, EM_68HC16=69, EM_68HC11=70,"
" EM_68HC08=71, EM_68HC05=72, EM_SVX=73, EM_ST19=74, EM_VAX=75, "
" EM_CRIS=76, EM_JAVELIN=77, EM_FIREPATH=78, EM_ZSP=79, EM_MMIX=80,"
" EM_HUANY=81, EM_PRISM=82, EM_AVR=83, EM_FR30=84, EM_D10V=85, EM_D30V=86,"
" EM_V850=87, EM_M32R=88, EM_MN10300=89, EM_MN10200=90, EM_PJ=91,"
" EM_OPENRISC=92, EM_ARC_A5=93, EM_XTENSA=94, EM_NUM=95};", 0);
sdb_num_set (bin->kv, "elf_header.offset", 0, 0);
sdb_num_set (bin->kv, "elf_header.size", sizeof (Elf_(Ehdr)), 0);
#if R_BIN_ELF64
sdb_set (bin->kv, "elf_header.format", "[16]z[2]E[2]Exqqqxwwwwww"
" ident (elf_type)type (elf_machine)machine version entry phoff shoff flags ehsize"
" phentsize phnum shentsize shnum shstrndx", 0);
#else
sdb_set (bin->kv, "elf_header.format", "[16]z[2]E[2]Exxxxxwwwwww"
" ident (elf_type)type (elf_machine)machine version entry phoff shoff flags ehsize"
" phentsize phnum shentsize shnum shstrndx", 0);
#endif
bin->endian = (e_ident[EI_DATA] == ELFDATA2MSB)? 1: 0;
memset (&bin->ehdr, 0, sizeof (Elf_(Ehdr)));
len = r_buf_read_at (bin->b, 0, ehdr, sizeof (Elf_(Ehdr)));
if (len < 1) {
bprintf ("Warning: read (ehdr)\n");
return false;
}
memcpy (&bin->ehdr.e_ident, ehdr, 16);
i = 16;
bin->ehdr.e_type = READ16 (ehdr, i)
bin->ehdr.e_machine = READ16 (ehdr, i)
bin->ehdr.e_version = READ32 (ehdr, i)
#if R_BIN_ELF64
bin->ehdr.e_entry = READ64 (ehdr, i)
bin->ehdr.e_phoff = READ64 (ehdr, i)
bin->ehdr.e_shoff = READ64 (ehdr, i)
#else
bin->ehdr.e_entry = READ32 (ehdr, i)
bin->ehdr.e_phoff = READ32 (ehdr, i)
bin->ehdr.e_shoff = READ32 (ehdr, i)
#endif
bin->ehdr.e_flags = READ32 (ehdr, i)
bin->ehdr.e_ehsize = READ16 (ehdr, i)
bin->ehdr.e_phentsize = READ16 (ehdr, i)
bin->ehdr.e_phnum = READ16 (ehdr, i)
bin->ehdr.e_shentsize = READ16 (ehdr, i)
bin->ehdr.e_shnum = READ16 (ehdr, i)
bin->ehdr.e_shstrndx = READ16 (ehdr, i)
return handle_e_ident (bin);
// Usage example:
// > td `k bin/cur/info/elf_type.cparse`; td `k bin/cur/info/elf_machine.cparse`
// > pf `k bin/cur/info/elf_header.format` @ `k bin/cur/info/elf_header.offset`
}
static int init_phdr(ELFOBJ *bin) {
ut32 phdr_size;
ut8 phdr[sizeof (Elf_(Phdr))] = {0};
int i, j, len;
if (!bin->ehdr.e_phnum) {
return false;
}
if (bin->phdr) {
return true;
}
if (!UT32_MUL (&phdr_size, (ut32)bin->ehdr.e_phnum, sizeof (Elf_(Phdr)))) {
return false;
}
if (!phdr_size) {
return false;
}
if (phdr_size > bin->size) {
return false;
}
if (phdr_size > (ut32)bin->size) {
return false;
}
if (bin->ehdr.e_phoff > bin->size) {
return false;
}
if (bin->ehdr.e_phoff + phdr_size > bin->size) {
return false;
}
if (!(bin->phdr = calloc (phdr_size, 1))) {
perror ("malloc (phdr)");
return false;
}
for (i = 0; i < bin->ehdr.e_phnum; i++) {
j = 0;
len = r_buf_read_at (bin->b, bin->ehdr.e_phoff + i * sizeof (Elf_(Phdr)), phdr, sizeof (Elf_(Phdr)));
if (len < 1) {
bprintf ("Warning: read (phdr)\n");
R_FREE (bin->phdr);
return false;
}
bin->phdr[i].p_type = READ32 (phdr, j)
#if R_BIN_ELF64
bin->phdr[i].p_flags = READ32 (phdr, j)
bin->phdr[i].p_offset = READ64 (phdr, j)
bin->phdr[i].p_vaddr = READ64 (phdr, j)
bin->phdr[i].p_paddr = READ64 (phdr, j)
bin->phdr[i].p_filesz = READ64 (phdr, j)
bin->phdr[i].p_memsz = READ64 (phdr, j)
bin->phdr[i].p_align = READ64 (phdr, j)
#else
bin->phdr[i].p_offset = READ32 (phdr, j)
bin->phdr[i].p_vaddr = READ32 (phdr, j)
bin->phdr[i].p_paddr = READ32 (phdr, j)
bin->phdr[i].p_filesz = READ32 (phdr, j)
bin->phdr[i].p_memsz = READ32 (phdr, j)
bin->phdr[i].p_flags = READ32 (phdr, j)
bin->phdr[i].p_align = READ32 (phdr, j)
#endif
}
sdb_num_set (bin->kv, "elf_phdr.offset", bin->ehdr.e_phoff, 0);
sdb_num_set (bin->kv, "elf_phdr.size", sizeof (Elf_(Phdr)), 0);
sdb_set (bin->kv, "elf_p_type.cparse", "enum elf_p_type {PT_NULL=0,PT_LOAD=1,PT_DYNAMIC=2,"
"PT_INTERP=3,PT_NOTE=4,PT_SHLIB=5,PT_PHDR=6,PT_LOOS=0x60000000,"
"PT_HIOS=0x6fffffff,PT_LOPROC=0x70000000,PT_HIPROC=0x7fffffff};", 0);
sdb_set (bin->kv, "elf_p_flags.cparse", "enum elf_p_flags {PF_None=0,PF_Exec=1,"
"PF_Write=2,PF_Write_Exec=3,PF_Read=4,PF_Read_Exec=5,PF_Read_Write=6,"
"PF_Read_Write_Exec=7};", 0);
#if R_BIN_ELF64
sdb_set (bin->kv, "elf_phdr.format", "[4]E[4]Eqqqqqq (elf_p_type)type (elf_p_flags)flags"
" offset vaddr paddr filesz memsz align", 0);
#else
sdb_set (bin->kv, "elf_phdr.format", "[4]Exxxxx[4]Ex (elf_p_type)type offset vaddr paddr"
" filesz memsz (elf_p_flags)flags align", 0);
#endif
return true;
// Usage example:
// > td `k bin/cur/info/elf_p_type.cparse`; td `k bin/cur/info/elf_p_flags.cparse`
// > pf `k bin/cur/info/elf_phdr.format` @ `k bin/cur/info/elf_phdr.offset`
}
static int init_shdr(ELFOBJ *bin) {
ut32 shdr_size;
ut8 shdr[sizeof (Elf_(Shdr))] = {0};
int i, j, len;
if (!bin || bin->shdr) {
return true;
}
if (!UT32_MUL (&shdr_size, bin->ehdr.e_shnum, sizeof (Elf_(Shdr)))) {
return false;
}
if (shdr_size < 1) {
return false;
}
if (shdr_size > bin->size) {
return false;
}
if (bin->ehdr.e_shoff > bin->size) {
return false;
}
if (bin->ehdr.e_shoff + shdr_size > bin->size) {
return false;
}
if (!(bin->shdr = calloc (1, shdr_size + 1))) {
perror ("malloc (shdr)");
return false;
}
sdb_num_set (bin->kv, "elf_shdr.offset", bin->ehdr.e_shoff, 0);
sdb_num_set (bin->kv, "elf_shdr.size", sizeof (Elf_(Shdr)), 0);
sdb_set (bin->kv, "elf_s_type.cparse", "enum elf_s_type {SHT_NULL=0,SHT_PROGBITS=1,"
"SHT_SYMTAB=2,SHT_STRTAB=3,SHT_RELA=4,SHT_HASH=5,SHT_DYNAMIC=6,SHT_NOTE=7,"
"SHT_NOBITS=8,SHT_REL=9,SHT_SHLIB=10,SHT_DYNSYM=11,SHT_LOOS=0x60000000,"
"SHT_HIOS=0x6fffffff,SHT_LOPROC=0x70000000,SHT_HIPROC=0x7fffffff};", 0);
for (i = 0; i < bin->ehdr.e_shnum; i++) {
j = 0;
len = r_buf_read_at (bin->b, bin->ehdr.e_shoff + i * sizeof (Elf_(Shdr)), shdr, sizeof (Elf_(Shdr)));
if (len < 1) {
bprintf ("Warning: read (shdr) at 0x%"PFMT64x"\n", (ut64) bin->ehdr.e_shoff);
R_FREE (bin->shdr);
return false;
}
bin->shdr[i].sh_name = READ32 (shdr, j)
bin->shdr[i].sh_type = READ32 (shdr, j)
#if R_BIN_ELF64
bin->shdr[i].sh_flags = READ64 (shdr, j)
bin->shdr[i].sh_addr = READ64 (shdr, j)
bin->shdr[i].sh_offset = READ64 (shdr, j)
bin->shdr[i].sh_size = READ64 (shdr, j)
bin->shdr[i].sh_link = READ32 (shdr, j)
bin->shdr[i].sh_info = READ32 (shdr, j)
bin->shdr[i].sh_addralign = READ64 (shdr, j)
bin->shdr[i].sh_entsize = READ64 (shdr, j)
#else
bin->shdr[i].sh_flags = READ32 (shdr, j)
bin->shdr[i].sh_addr = READ32 (shdr, j)
bin->shdr[i].sh_offset = READ32 (shdr, j)
bin->shdr[i].sh_size = READ32 (shdr, j)
bin->shdr[i].sh_link = READ32 (shdr, j)
bin->shdr[i].sh_info = READ32 (shdr, j)
bin->shdr[i].sh_addralign = READ32 (shdr, j)
bin->shdr[i].sh_entsize = READ32 (shdr, j)
#endif
}
#if R_BIN_ELF64
sdb_set (bin->kv, "elf_s_flags_64.cparse", "enum elf_s_flags_64 {SF64_None=0,SF64_Exec=1,"
"SF64_Alloc=2,SF64_Alloc_Exec=3,SF64_Write=4,SF64_Write_Exec=5,"
"SF64_Write_Alloc=6,SF64_Write_Alloc_Exec=7};", 0);
sdb_set (bin->kv, "elf_shdr.format", "x[4]E[8]Eqqqxxqq name (elf_s_type)type"
" (elf_s_flags_64)flags addr offset size link info addralign entsize", 0);
#else
sdb_set (bin->kv, "elf_s_flags_32.cparse", "enum elf_s_flags_32 {SF32_None=0,SF32_Exec=1,"
"SF32_Alloc=2,SF32_Alloc_Exec=3,SF32_Write=4,SF32_Write_Exec=5,"
"SF32_Write_Alloc=6,SF32_Write_Alloc_Exec=7};", 0);
sdb_set (bin->kv, "elf_shdr.format", "x[4]E[4]Exxxxxxx name (elf_s_type)type"
" (elf_s_flags_32)flags addr offset size link info addralign entsize", 0);
#endif
return true;
// Usage example:
// > td `k bin/cur/info/elf_s_type.cparse`; td `k bin/cur/info/elf_s_flags_64.cparse`
// > pf `k bin/cur/info/elf_shdr.format` @ `k bin/cur/info/elf_shdr.offset`
}
static int init_strtab(ELFOBJ *bin) {
if (bin->strtab || !bin->shdr) {
return false;
}
if (bin->ehdr.e_shstrndx != SHN_UNDEF &&
(bin->ehdr.e_shstrndx >= bin->ehdr.e_shnum ||
(bin->ehdr.e_shstrndx >= SHN_LORESERVE &&
bin->ehdr.e_shstrndx < SHN_HIRESERVE)))
return false;
/* sh_size must be lower than UT32_MAX and not equal to zero, to avoid bugs on malloc() */
if (bin->shdr[bin->ehdr.e_shstrndx].sh_size > UT32_MAX) {
return false;
}
if (!bin->shdr[bin->ehdr.e_shstrndx].sh_size) {
return false;
}
bin->shstrtab_section = bin->strtab_section = &bin->shdr[bin->ehdr.e_shstrndx];
bin->shstrtab_size = bin->strtab_section->sh_size;
if (bin->shstrtab_size > bin->size) {
return false;
}
if (!(bin->shstrtab = calloc (1, bin->shstrtab_size + 1))) {
perror ("malloc");
bin->shstrtab = NULL;
return false;
}
if (bin->shstrtab_section->sh_offset > bin->size) {
R_FREE (bin->shstrtab);
return false;
}
if (bin->shstrtab_section->sh_offset +
bin->shstrtab_section->sh_size > bin->size) {
R_FREE (bin->shstrtab);
return false;
}
if (r_buf_read_at (bin->b, bin->shstrtab_section->sh_offset, (ut8*)bin->shstrtab,
bin->shstrtab_section->sh_size + 1) < 1) {
bprintf ("Warning: read (shstrtab) at 0x%"PFMT64x"\n",
(ut64) bin->shstrtab_section->sh_offset);
R_FREE (bin->shstrtab);
return false;
}
bin->shstrtab[bin->shstrtab_section->sh_size] = '\0';
sdb_num_set (bin->kv, "elf_shstrtab.offset", bin->shstrtab_section->sh_offset, 0);
sdb_num_set (bin->kv, "elf_shstrtab.size", bin->shstrtab_section->sh_size, 0);
return true;
}
static int init_dynamic_section(struct Elf_(r_bin_elf_obj_t) *bin) {
Elf_(Dyn) *dyn = NULL;
Elf_(Dyn) d = {0};
Elf_(Addr) strtabaddr = 0;
ut64 offset = 0;
char *strtab = NULL;
size_t relentry = 0, strsize = 0;
int entries;
int i, j, len, r;
ut8 sdyn[sizeof (Elf_(Dyn))] = {0};
ut32 dyn_size = 0;
if (!bin || !bin->phdr || !bin->ehdr.e_phnum) {
return false;
}
for (i = 0; i < bin->ehdr.e_phnum ; i++) {
if (bin->phdr[i].p_type == PT_DYNAMIC) {
dyn_size = bin->phdr[i].p_filesz;
break;
}
}
if (i == bin->ehdr.e_phnum) {
return false;
}
if (bin->phdr[i].p_filesz > bin->size) {
return false;
}
if (bin->phdr[i].p_offset > bin->size) {
return false;
}
if (bin->phdr[i].p_offset + sizeof(Elf_(Dyn)) > bin->size) {
return false;
}
for (entries = 0; entries < (dyn_size / sizeof (Elf_(Dyn))); entries++) {
j = 0;
len = r_buf_read_at (bin->b, bin->phdr[i].p_offset + entries * sizeof (Elf_(Dyn)), sdyn, sizeof (Elf_(Dyn)));
if (len < 1) {
goto beach;
}
#if R_BIN_ELF64
d.d_tag = READ64 (sdyn, j)
#else
d.d_tag = READ32 (sdyn, j)
#endif
if (d.d_tag == DT_NULL) {
break;
}
}
if (entries < 1) {
return false;
}
dyn = (Elf_(Dyn)*)calloc (entries, sizeof (Elf_(Dyn)));
if (!dyn) {
return false;
}
if (!UT32_MUL (&dyn_size, entries, sizeof (Elf_(Dyn)))) {
goto beach;
}
if (!dyn_size) {
goto beach;
}
offset = Elf_(r_bin_elf_v2p) (bin, bin->phdr[i].p_vaddr);
if (offset > bin->size || offset + dyn_size > bin->size) {
goto beach;
}
for (i = 0; i < entries; i++) {
j = 0;
r_buf_read_at (bin->b, offset + i * sizeof (Elf_(Dyn)), sdyn, sizeof (Elf_(Dyn)));
if (len < 1) {
bprintf("Warning: read (dyn)\n");
}
#if R_BIN_ELF64
dyn[i].d_tag = READ64 (sdyn, j)
dyn[i].d_un.d_ptr = READ64 (sdyn, j)
#else
dyn[i].d_tag = READ32 (sdyn, j)
dyn[i].d_un.d_ptr = READ32 (sdyn, j)
#endif
switch (dyn[i].d_tag) {
case DT_STRTAB: strtabaddr = Elf_(r_bin_elf_v2p) (bin, dyn[i].d_un.d_ptr); break;
case DT_STRSZ: strsize = dyn[i].d_un.d_val; break;
case DT_PLTREL: bin->is_rela = dyn[i].d_un.d_val; break;
case DT_RELAENT: relentry = dyn[i].d_un.d_val; break;
default:
if ((dyn[i].d_tag >= DT_VERSYM) && (dyn[i].d_tag <= DT_VERNEEDNUM)) {
bin->version_info[DT_VERSIONTAGIDX (dyn[i].d_tag)] = dyn[i].d_un.d_val;
}
break;
}
}
if (!bin->is_rela) {
bin->is_rela = sizeof (Elf_(Rela)) == relentry? DT_RELA : DT_REL;
}
if (!strtabaddr || strtabaddr > bin->size || strsize > ST32_MAX || !strsize || strsize > bin->size) {
if (!strtabaddr) {
bprintf ("Warning: section.shstrtab not found or invalid\n");
}
goto beach;
}
strtab = (char *)calloc (1, strsize + 1);
if (!strtab) {
goto beach;
}
if (strtabaddr + strsize > bin->size) {
free (strtab);
goto beach;
}
r = r_buf_read_at (bin->b, strtabaddr, (ut8 *)strtab, strsize);
if (r < 1) {
free (strtab);
goto beach;
}
bin->dyn_buf = dyn;
bin->dyn_entries = entries;
bin->strtab = strtab;
bin->strtab_size = strsize;
r = Elf_(r_bin_elf_has_relro)(bin);
switch (r) {
case R_ELF_FULL_RELRO:
sdb_set (bin->kv, "elf.relro", "full", 0);
break;
case R_ELF_PART_RELRO:
sdb_set (bin->kv, "elf.relro", "partial", 0);
break;
default:
sdb_set (bin->kv, "elf.relro", "no", 0);
break;
}
sdb_num_set (bin->kv, "elf_strtab.offset", strtabaddr, 0);
sdb_num_set (bin->kv, "elf_strtab.size", strsize, 0);
return true;
beach:
free (dyn);
return false;
}
static RBinElfSection* get_section_by_name(ELFOBJ *bin, const char *section_name) {
int i;
if (!bin->g_sections) {
return NULL;
}
for (i = 0; !bin->g_sections[i].last; i++) {
if (!strncmp (bin->g_sections[i].name, section_name, ELF_STRING_LENGTH-1)) {
return &bin->g_sections[i];
}
}
return NULL;
}
static char *get_ver_flags(ut32 flags) {
static char buff[32];
buff[0] = 0;
if (!flags) {
return "none";
}
if (flags & VER_FLG_BASE) {
strcpy (buff, "BASE ");
}
if (flags & VER_FLG_WEAK) {
if (flags & VER_FLG_BASE) {
strcat (buff, "| ");
}
strcat (buff, "WEAK ");
}
if (flags & ~(VER_FLG_BASE | VER_FLG_WEAK)) {
strcat (buff, "| <unknown>");
}
return buff;
}
static Sdb *store_versioninfo_gnu_versym(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
int i;
const ut64 num_entries = sz / sizeof (Elf_(Versym));
const char *section_name = "";
const char *link_section_name = "";
Elf_(Shdr) *link_shdr = NULL;
Sdb *sdb = sdb_new0();
if (!sdb) {
return NULL;
}
if (!bin->version_info[DT_VERSIONTAGIDX (DT_VERSYM)]) {
sdb_free (sdb);
return NULL;
}
if (shdr->sh_link > bin->ehdr.e_shnum) {
sdb_free (sdb);
return NULL;
}
link_shdr = &bin->shdr[shdr->sh_link];
ut8 *edata = (ut8*) calloc (R_MAX (1, num_entries), sizeof (ut16));
if (!edata) {
sdb_free (sdb);
return NULL;
}
ut16 *data = (ut16*) calloc (R_MAX (1, num_entries), sizeof (ut16));
if (!data) {
free (edata);
sdb_free (sdb);
return NULL;
}
ut64 off = Elf_(r_bin_elf_v2p) (bin, bin->version_info[DT_VERSIONTAGIDX (DT_VERSYM)]);
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
r_buf_read_at (bin->b, off, edata, sizeof (ut16) * num_entries);
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "num_entries", num_entries, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (i = num_entries; i--;) {
data[i] = r_read_ble16 (&edata[i * sizeof (ut16)], bin->endian);
}
R_FREE (edata);
for (i = 0; i < num_entries; i += 4) {
int j;
int check_def;
char key[32] = {0};
Sdb *sdb_entry = sdb_new0 ();
snprintf (key, sizeof (key), "entry%d", i / 4);
sdb_ns_set (sdb, key, sdb_entry);
sdb_num_set (sdb_entry, "idx", i, 0);
for (j = 0; (j < 4) && (i + j) < num_entries; ++j) {
int k;
char *tmp_val = NULL;
snprintf (key, sizeof (key), "value%d", j);
switch (data[i + j]) {
case 0:
sdb_set (sdb_entry, key, "0 (*local*)", 0);
break;
case 1:
sdb_set (sdb_entry, key, "1 (*global*)", 0);
break;
default:
tmp_val = sdb_fmt (0, "%x ", data[i+j] & 0x7FFF);
check_def = true;
if (bin->version_info[DT_VERSIONTAGIDX (DT_VERNEED)]) {
Elf_(Verneed) vn;
ut8 svn[sizeof (Elf_(Verneed))] = {0};
ut64 offset = Elf_(r_bin_elf_v2p) (bin, bin->version_info[DT_VERSIONTAGIDX (DT_VERNEED)]);
do {
Elf_(Vernaux) vna;
ut8 svna[sizeof (Elf_(Vernaux))] = {0};
ut64 a_off;
if (offset > bin->size || offset + sizeof (vn) > bin->size) {
goto beach;
}
if (r_buf_read_at (bin->b, offset, svn, sizeof (svn)) < 0) {
bprintf ("Warning: Cannot read Verneed for Versym\n");
goto beach;
}
k = 0;
vn.vn_version = READ16 (svn, k)
vn.vn_cnt = READ16 (svn, k)
vn.vn_file = READ32 (svn, k)
vn.vn_aux = READ32 (svn, k)
vn.vn_next = READ32 (svn, k)
a_off = offset + vn.vn_aux;
do {
if (a_off > bin->size || a_off + sizeof (vna) > bin->size) {
goto beach;
}
if (r_buf_read_at (bin->b, a_off, svna, sizeof (svna)) < 0) {
bprintf ("Warning: Cannot read Vernaux for Versym\n");
goto beach;
}
k = 0;
vna.vna_hash = READ32 (svna, k)
vna.vna_flags = READ16 (svna, k)
vna.vna_other = READ16 (svna, k)
vna.vna_name = READ32 (svna, k)
vna.vna_next = READ32 (svna, k)
a_off += vna.vna_next;
} while (vna.vna_other != data[i + j] && vna.vna_next != 0);
if (vna.vna_other == data[i + j]) {
if (vna.vna_name > bin->strtab_size) {
goto beach;
}
sdb_set (sdb_entry, key, sdb_fmt (0, "%s(%s)", tmp_val, bin->strtab + vna.vna_name), 0);
check_def = false;
break;
}
offset += vn.vn_next;
} while (vn.vn_next);
}
ut64 vinfoaddr = bin->version_info[DT_VERSIONTAGIDX (DT_VERDEF)];
if (check_def && data[i + j] != 0x8001 && vinfoaddr) {
Elf_(Verdef) vd;
ut8 svd[sizeof (Elf_(Verdef))] = {0};
ut64 offset = Elf_(r_bin_elf_v2p) (bin, vinfoaddr);
if (offset > bin->size || offset + sizeof (vd) > bin->size) {
goto beach;
}
do {
if (r_buf_read_at (bin->b, offset, svd, sizeof (svd)) < 0) {
bprintf ("Warning: Cannot read Verdef for Versym\n");
goto beach;
}
k = 0;
vd.vd_version = READ16 (svd, k)
vd.vd_flags = READ16 (svd, k)
vd.vd_ndx = READ16 (svd, k)
vd.vd_cnt = READ16 (svd, k)
vd.vd_hash = READ32 (svd, k)
vd.vd_aux = READ32 (svd, k)
vd.vd_next = READ32 (svd, k)
offset += vd.vd_next;
} while (vd.vd_ndx != (data[i + j] & 0x7FFF) && vd.vd_next != 0);
if (vd.vd_ndx == (data[i + j] & 0x7FFF)) {
Elf_(Verdaux) vda;
ut8 svda[sizeof (Elf_(Verdaux))] = {0};
ut64 off_vda = offset - vd.vd_next + vd.vd_aux;
if (off_vda > bin->size || off_vda + sizeof (vda) > bin->size) {
goto beach;
}
if (r_buf_read_at (bin->b, off_vda, svda, sizeof (svda)) < 0) {
bprintf ("Warning: Cannot read Verdaux for Versym\n");
goto beach;
}
k = 0;
vda.vda_name = READ32 (svda, k)
vda.vda_next = READ32 (svda, k)
if (vda.vda_name > bin->strtab_size) {
goto beach;
}
const char *name = bin->strtab + vda.vda_name;
sdb_set (sdb_entry, key, sdb_fmt (0,"%s(%s%-*s)", tmp_val, name, (int)(12 - strlen (name)),")") , 0);
}
}
}
}
}
beach:
free (data);
return sdb;
}
static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (shdr->sh_size < 1) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
int vdaux = verdef->vd_aux;
if (vdaux < 1) {
sdb_free (sdb_verdef);
goto out_error;
}
vstart += vdaux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
ut8 *end, *need = NULL;
const char *section_name = "";
Elf_(Shdr) *link_shdr = NULL;
const char *link_section_name = "";
Sdb *sdb_vernaux = NULL;
Sdb *sdb_version = NULL;
Sdb *sdb = NULL;
int i, cnt;
if (!bin || !bin->dynstr) {
return NULL;
}
if (shdr->sh_link > bin->ehdr.e_shnum) {
return NULL;
}
if (shdr->sh_size < 1) {
return NULL;
}
sdb = sdb_new0 ();
if (!sdb) {
return NULL;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) {
bprintf ("Warning: Cannot allocate memory for Elf_(Verneed)\n");
goto beach;
}
end = need + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "num_entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) {
goto beach;
}
if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) {
goto beach;
}
i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size);
if (i < 0)
goto beach;
//XXX we should use DT_VERNEEDNUM instead of sh_info
//TODO https://sourceware.org/ml/binutils/2014-11/msg00353.html
for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) {
int j, isum;
ut8 *vstart = need + i;
Elf_(Verneed) vvn = {0};
if (vstart + sizeof (Elf_(Verneed)) > end) {
goto beach;
}
Elf_(Verneed) *entry = &vvn;
char key[32] = {0};
sdb_version = sdb_new0 ();
if (!sdb_version) {
goto beach;
}
j = 0;
vvn.vn_version = READ16 (vstart, j)
vvn.vn_cnt = READ16 (vstart, j)
vvn.vn_file = READ32 (vstart, j)
vvn.vn_aux = READ32 (vstart, j)
vvn.vn_next = READ32 (vstart, j)
sdb_num_set (sdb_version, "vn_version", entry->vn_version, 0);
sdb_num_set (sdb_version, "idx", i, 0);
if (entry->vn_file > bin->dynstr_size) {
goto beach;
}
{
char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16);
sdb_set (sdb_version, "file_name", s, 0);
free (s);
}
sdb_num_set (sdb_version, "cnt", entry->vn_cnt, 0);
st32 vnaux = entry->vn_aux;
if (vnaux < 1) {
goto beach;
}
vstart += vnaux;
for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) {
int k;
Elf_(Vernaux) * aux = NULL;
Elf_(Vernaux) vaux = {0};
sdb_vernaux = sdb_new0 ();
if (!sdb_vernaux) {
goto beach;
}
aux = (Elf_(Vernaux)*)&vaux;
k = 0;
vaux.vna_hash = READ32 (vstart, k)
vaux.vna_flags = READ16 (vstart, k)
vaux.vna_other = READ16 (vstart, k)
vaux.vna_name = READ32 (vstart, k)
vaux.vna_next = READ32 (vstart, k)
if (aux->vna_name > bin->dynstr_size) {
goto beach;
}
sdb_num_set (sdb_vernaux, "idx", isum, 0);
if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) {
char name [16];
strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1);
name[sizeof(name)-1] = 0;
sdb_set (sdb_vernaux, "name", name, 0);
}
sdb_set (sdb_vernaux, "flags", get_ver_flags (aux->vna_flags), 0);
sdb_num_set (sdb_vernaux, "version", aux->vna_other, 0);
isum += aux->vna_next;
vstart += aux->vna_next;
snprintf (key, sizeof (key), "vernaux%d", j);
sdb_ns_set (sdb_version, key, sdb_vernaux);
}
if ((int)entry->vn_next < 0) {
bprintf ("Invalid vn_next\n");
break;
}
i += entry->vn_next;
snprintf (key, sizeof (key), "version%d", cnt );
sdb_ns_set (sdb, key, sdb_version);
//if entry->vn_next is 0 it iterate infinitely
if (!entry->vn_next) {
break;
}
}
free (need);
return sdb;
beach:
free (need);
sdb_free (sdb_vernaux);
sdb_free (sdb_version);
sdb_free (sdb);
return NULL;
}
static Sdb *store_versioninfo(ELFOBJ *bin) {
Sdb *sdb_versioninfo = NULL;
int num_verdef = 0;
int num_verneed = 0;
int num_versym = 0;
int i;
if (!bin || !bin->shdr) {
return NULL;
}
if (!(sdb_versioninfo = sdb_new0 ())) {
return NULL;
}
for (i = 0; i < bin->ehdr.e_shnum; i++) {
Sdb *sdb = NULL;
char key[32] = {0};
int size = bin->shdr[i].sh_size;
if (size - (i*sizeof(Elf_(Shdr)) > bin->size)) {
size = bin->size - (i*sizeof(Elf_(Shdr)));
}
int left = size - (i * sizeof (Elf_(Shdr)));
left = R_MIN (left, bin->shdr[i].sh_size);
if (left < 0) {
break;
}
switch (bin->shdr[i].sh_type) {
case SHT_GNU_verdef:
sdb = store_versioninfo_gnu_verdef (bin, &bin->shdr[i], left);
snprintf (key, sizeof (key), "verdef%d", num_verdef++);
sdb_ns_set (sdb_versioninfo, key, sdb);
break;
case SHT_GNU_verneed:
sdb = store_versioninfo_gnu_verneed (bin, &bin->shdr[i], left);
snprintf (key, sizeof (key), "verneed%d", num_verneed++);
sdb_ns_set (sdb_versioninfo, key, sdb);
break;
case SHT_GNU_versym:
sdb = store_versioninfo_gnu_versym (bin, &bin->shdr[i], left);
snprintf (key, sizeof (key), "versym%d", num_versym++);
sdb_ns_set (sdb_versioninfo, key, sdb);
break;
}
}
return sdb_versioninfo;
}
static bool init_dynstr(ELFOBJ *bin) {
int i, r;
const char *section_name = NULL;
if (!bin || !bin->shdr) {
return false;
}
if (!bin->shstrtab) {
return false;
}
for (i = 0; i < bin->ehdr.e_shnum; ++i) {
if (bin->shdr[i].sh_name > bin->shstrtab_size) {
return false;
}
section_name = &bin->shstrtab[bin->shdr[i].sh_name];
if (bin->shdr[i].sh_type == SHT_STRTAB && !strcmp (section_name, ".dynstr")) {
if (!(bin->dynstr = (char*) calloc (bin->shdr[i].sh_size + 1, sizeof (char)))) {
bprintf("Warning: Cannot allocate memory for dynamic strings\n");
return false;
}
if (bin->shdr[i].sh_offset > bin->size) {
return false;
}
if (bin->shdr[i].sh_offset + bin->shdr[i].sh_size > bin->size) {
return false;
}
if (bin->shdr[i].sh_offset + bin->shdr[i].sh_size < bin->shdr[i].sh_size) {
return false;
}
r = r_buf_read_at (bin->b, bin->shdr[i].sh_offset, (ut8*)bin->dynstr, bin->shdr[i].sh_size);
if (r < 1) {
R_FREE (bin->dynstr);
bin->dynstr_size = 0;
return false;
}
bin->dynstr_size = bin->shdr[i].sh_size;
return true;
}
}
return false;
}
static int elf_init(ELFOBJ *bin) {
bin->phdr = NULL;
bin->shdr = NULL;
bin->strtab = NULL;
bin->shstrtab = NULL;
bin->strtab_size = 0;
bin->strtab_section = NULL;
bin->dyn_buf = NULL;
bin->dynstr = NULL;
ZERO_FILL (bin->version_info);
bin->g_sections = NULL;
bin->g_symbols = NULL;
bin->g_imports = NULL;
/* bin is not an ELF */
if (!init_ehdr (bin)) {
return false;
}
if (!init_phdr (bin)) {
bprintf ("Warning: Cannot initialize program headers\n");
}
if (!init_shdr (bin)) {
bprintf ("Warning: Cannot initialize section headers\n");
}
if (!init_strtab (bin)) {
bprintf ("Warning: Cannot initialize strings table\n");
}
if (!init_dynstr (bin)) {
bprintf ("Warning: Cannot initialize dynamic strings\n");
}
bin->baddr = Elf_(r_bin_elf_get_baddr) (bin);
if (!init_dynamic_section (bin) && !Elf_(r_bin_elf_get_static)(bin))
bprintf ("Warning: Cannot initialize dynamic section\n");
bin->imports_by_ord_size = 0;
bin->imports_by_ord = NULL;
bin->symbols_by_ord_size = 0;
bin->symbols_by_ord = NULL;
bin->g_sections = Elf_(r_bin_elf_get_sections) (bin);
bin->boffset = Elf_(r_bin_elf_get_boffset) (bin);
sdb_ns_set (bin->kv, "versioninfo", store_versioninfo (bin));
return true;
}
ut64 Elf_(r_bin_elf_get_section_offset)(ELFOBJ *bin, const char *section_name) {
RBinElfSection *section = get_section_by_name (bin, section_name);
if (!section) return UT64_MAX;
return section->offset;
}
ut64 Elf_(r_bin_elf_get_section_addr)(ELFOBJ *bin, const char *section_name) {
RBinElfSection *section = get_section_by_name (bin, section_name);
return section? section->rva: UT64_MAX;
}
ut64 Elf_(r_bin_elf_get_section_addr_end)(ELFOBJ *bin, const char *section_name) {
RBinElfSection *section = get_section_by_name (bin, section_name);
return section? section->rva + section->size: UT64_MAX;
}
#define REL (is_rela ? (void*)rela : (void*)rel)
#define REL_BUF is_rela ? (ut8*)(&rela[k]) : (ut8*)(&rel[k])
#define REL_OFFSET is_rela ? rela[k].r_offset : rel[k].r_offset
#define REL_TYPE is_rela ? rela[k].r_info : rel[k].r_info
static ut64 get_import_addr(ELFOBJ *bin, int sym) {
Elf_(Rel) *rel = NULL;
Elf_(Rela) *rela = NULL;
ut8 rl[sizeof (Elf_(Rel))] = {0};
ut8 rla[sizeof (Elf_(Rela))] = {0};
RBinElfSection *rel_sec = NULL;
Elf_(Addr) plt_sym_addr = -1;
ut64 got_addr, got_offset;
ut64 plt_addr;
int j, k, tsize, len, nrel;
bool is_rela = false;
const char *rel_sect[] = { ".rel.plt", ".rela.plt", ".rel.dyn", ".rela.dyn", NULL };
const char *rela_sect[] = { ".rela.plt", ".rel.plt", ".rela.dyn", ".rel.dyn", NULL };
if ((!bin->shdr || !bin->strtab) && !bin->phdr) {
return -1;
}
if ((got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got")) == -1 &&
(got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got.plt")) == -1) {
return -1;
}
if ((got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got")) == -1 &&
(got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got.plt")) == -1) {
return -1;
}
if (bin->is_rela == DT_REL) {
j = 0;
while (!rel_sec && rel_sect[j]) {
rel_sec = get_section_by_name (bin, rel_sect[j++]);
}
tsize = sizeof (Elf_(Rel));
} else if (bin->is_rela == DT_RELA) {
j = 0;
while (!rel_sec && rela_sect[j]) {
rel_sec = get_section_by_name (bin, rela_sect[j++]);
}
is_rela = true;
tsize = sizeof (Elf_(Rela));
}
if (!rel_sec) {
return -1;
}
if (rel_sec->size < 1) {
return -1;
}
nrel = (ut32)((int)rel_sec->size / (int)tsize);
if (nrel < 1) {
return -1;
}
if (is_rela) {
rela = calloc (nrel, tsize);
if (!rela) {
return -1;
}
} else {
rel = calloc (nrel, tsize);
if (!rel) {
return -1;
}
}
for (j = k = 0; j < rel_sec->size && k < nrel; j += tsize, k++) {
int l = 0;
if (rel_sec->offset + j > bin->size) {
goto out;
}
if (rel_sec->offset + j + tsize > bin->size) {
goto out;
}
len = r_buf_read_at (
bin->b, rel_sec->offset + j, is_rela ? rla : rl,
is_rela ? sizeof (Elf_ (Rela)) : sizeof (Elf_ (Rel)));
if (len < 1) {
goto out;
}
#if R_BIN_ELF64
if (is_rela) {
rela[k].r_offset = READ64 (rla, l)
rela[k].r_info = READ64 (rla, l)
rela[k].r_addend = READ64 (rla, l)
} else {
rel[k].r_offset = READ64 (rl, l)
rel[k].r_info = READ64 (rl, l)
}
#else
if (is_rela) {
rela[k].r_offset = READ32 (rla, l)
rela[k].r_info = READ32 (rla, l)
rela[k].r_addend = READ32 (rla, l)
} else {
rel[k].r_offset = READ32 (rl, l)
rel[k].r_info = READ32 (rl, l)
}
#endif
int reloc_type = ELF_R_TYPE (REL_TYPE);
int reloc_sym = ELF_R_SYM (REL_TYPE);
if (reloc_sym == sym) {
int of = REL_OFFSET;
of = of - got_addr + got_offset;
switch (bin->ehdr.e_machine) {
case EM_PPC:
case EM_PPC64:
{
RBinElfSection *s = get_section_by_name (bin, ".plt");
if (s) {
ut8 buf[4];
ut64 base;
len = r_buf_read_at (bin->b, s->offset, buf, sizeof (buf));
if (len < 4) {
goto out;
}
base = r_read_be32 (buf);
base -= (nrel * 16);
base += (k * 16);
plt_addr = base;
free (REL);
return plt_addr;
}
}
break;
case EM_SPARC:
case EM_SPARCV9:
case EM_SPARC32PLUS:
plt_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".plt");
if (plt_addr == -1) {
free (rela);
return -1;
}
if (reloc_type == R_386_PC16) {
plt_addr += k * 12 + 20;
// thumb symbol
if (plt_addr & 1) {
plt_addr--;
}
free (REL);
return plt_addr;
} else {
bprintf ("Unknown sparc reloc type %d\n", reloc_type);
}
/* SPARC */
break;
case EM_ARM:
case EM_AARCH64:
plt_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".plt");
if (plt_addr == -1) {
free (rela);
return UT32_MAX;
}
switch (reloc_type) {
case R_386_8:
{
plt_addr += k * 12 + 20;
// thumb symbol
if (plt_addr & 1) {
plt_addr--;
}
free (REL);
return plt_addr;
}
break;
case 1026: // arm64 aarch64
plt_sym_addr = plt_addr + k * 16 + 32;
goto done;
default:
bprintf ("Unsupported relocation type for imports %d\n", reloc_type);
break;
}
break;
case EM_386:
case EM_X86_64:
switch (reloc_type) {
case 1: // unknown relocs found in voidlinux for x86-64
// break;
case R_386_GLOB_DAT:
case R_386_JMP_SLOT:
{
ut8 buf[8];
if (of + sizeof(Elf_(Addr)) < bin->size) {
// ONLY FOR X86
if (of > bin->size || of + sizeof (Elf_(Addr)) > bin->size) {
goto out;
}
len = r_buf_read_at (bin->b, of, buf, sizeof (Elf_(Addr)));
if (len < -1) {
goto out;
}
plt_sym_addr = sizeof (Elf_(Addr)) == 4
? r_read_le32 (buf)
: r_read_le64 (buf);
if (!plt_sym_addr) {
//XXX HACK ALERT!!!! full relro?? try to fix it
//will there always be .plt.got, what would happen if is .got.plt?
RBinElfSection *s = get_section_by_name (bin, ".plt.got");
if (Elf_(r_bin_elf_has_relro)(bin) < R_ELF_PART_RELRO || !s) {
goto done;
}
plt_addr = s->offset;
of = of + got_addr - got_offset;
while (plt_addr + 2 + 4 < s->offset + s->size) {
/*we try to locate the plt entry that correspond with the relocation
since got does not point back to .plt. In this case it has the following
form
ff253a152000 JMP QWORD [RIP + 0x20153A]
6690 NOP
----
ff25ec9f0408 JMP DWORD [reloc.puts_236]
plt_addr + 2 to remove jmp opcode and get the imm reading 4
and if RIP (plt_addr + 6) + imm == rel->offset
return plt_addr, that will be our sym addr
perhaps this hack doesn't work on 32 bits
*/
len = r_buf_read_at (bin->b, plt_addr + 2, buf, 4);
if (len < -1) {
goto out;
}
plt_sym_addr = sizeof (Elf_(Addr)) == 4
? r_read_le32 (buf)
: r_read_le64 (buf);
//relative address
if ((plt_addr + 6 + Elf_(r_bin_elf_v2p) (bin, plt_sym_addr)) == of) {
plt_sym_addr = plt_addr;
goto done;
} else if (plt_sym_addr == of) {
plt_sym_addr = plt_addr;
goto done;
}
plt_addr += 8;
}
} else {
plt_sym_addr -= 6;
}
goto done;
}
break;
}
default:
bprintf ("Unsupported relocation type for imports %d\n", reloc_type);
free (REL);
return of;
break;
}
break;
case 8:
// MIPS32 BIG ENDIAN relocs
{
RBinElfSection *s = get_section_by_name (bin, ".rela.plt");
if (s) {
ut8 buf[1024];
const ut8 *base;
plt_addr = s->rva + s->size;
len = r_buf_read_at (bin->b, s->offset + s->size, buf, sizeof (buf));
if (len != sizeof (buf)) {
// oops
}
base = r_mem_mem_aligned (buf, sizeof (buf), (const ut8*)"\x3c\x0f\x00", 3, 4);
if (base) {
plt_addr += (int)(size_t)(base - buf);
} else {
plt_addr += 108 + 8; // HARDCODED HACK
}
plt_addr += k * 16;
free (REL);
return plt_addr;
}
}
break;
default:
bprintf ("Unsupported relocs type %d for arch %d\n",
reloc_type, bin->ehdr.e_machine);
break;
}
}
}
done:
free (REL);
return plt_sym_addr;
out:
free (REL);
return -1;
}
int Elf_(r_bin_elf_has_nx)(ELFOBJ *bin) {
int i;
if (bin && bin->phdr) {
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_GNU_STACK) {
return (!(bin->phdr[i].p_flags & 1))? 1: 0;
}
}
}
return 0;
}
int Elf_(r_bin_elf_has_relro)(ELFOBJ *bin) {
int i;
bool haveBindNow = false;
bool haveGnuRelro = false;
if (bin && bin->dyn_buf) {
for (i = 0; i < bin->dyn_entries; i++) {
switch (bin->dyn_buf[i].d_tag) {
case DT_BIND_NOW:
haveBindNow = true;
break;
case DT_FLAGS:
for (i++; i < bin->dyn_entries ; i++) {
ut32 dTag = bin->dyn_buf[i].d_tag;
if (!dTag) {
break;
}
switch (dTag) {
case DT_FLAGS_1:
if (bin->dyn_buf[i].d_un.d_val & DF_1_NOW) {
haveBindNow = true;
break;
}
}
}
break;
}
}
}
if (bin && bin->phdr) {
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_GNU_RELRO) {
haveGnuRelro = true;
break;
}
}
}
if (haveGnuRelro) {
if (haveBindNow) {
return R_ELF_FULL_RELRO;
}
return R_ELF_PART_RELRO;
}
return R_ELF_NO_RELRO;
}
/*
To compute the base address, one determines the memory
address associated with the lowest p_vaddr value for a
PT_LOAD segment. One then obtains the base address by
truncating the memory address to the nearest multiple
of the maximum page size
*/
ut64 Elf_(r_bin_elf_get_baddr)(ELFOBJ *bin) {
int i;
ut64 tmp, base = UT64_MAX;
if (!bin) {
return 0;
}
if (bin->phdr) {
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_LOAD) {
tmp = (ut64)bin->phdr[i].p_vaddr & ELF_PAGE_MASK;
tmp = tmp - (tmp % (1 << ELF_PAGE_SIZE));
if (tmp < base) {
base = tmp;
}
}
}
}
if (base == UT64_MAX && bin->ehdr.e_type == ET_REL) {
//we return our own base address for ET_REL type
//we act as a loader for ELF
return 0x08000000;
}
return base == UT64_MAX ? 0 : base;
}
ut64 Elf_(r_bin_elf_get_boffset)(ELFOBJ *bin) {
int i;
ut64 tmp, base = UT64_MAX;
if (bin && bin->phdr) {
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_LOAD) {
tmp = (ut64)bin->phdr[i].p_offset & ELF_PAGE_MASK;
tmp = tmp - (tmp % (1 << ELF_PAGE_SIZE));
if (tmp < base) {
base = tmp;
}
}
}
}
return base == UT64_MAX ? 0 : base;
}
ut64 Elf_(r_bin_elf_get_init_offset)(ELFOBJ *bin) {
ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin);
ut8 buf[512];
if (!bin) {
return 0LL;
}
if (r_buf_read_at (bin->b, entry + 16, buf, sizeof (buf)) < 1) {
bprintf ("Warning: read (init_offset)\n");
return 0;
}
if (buf[0] == 0x68) { // push // x86 only
ut64 addr;
memmove (buf, buf+1, 4);
addr = (ut64)r_read_le32 (buf);
return Elf_(r_bin_elf_v2p) (bin, addr);
}
return 0;
}
ut64 Elf_(r_bin_elf_get_fini_offset)(ELFOBJ *bin) {
ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin);
ut8 buf[512];
if (!bin) {
return 0LL;
}
if (r_buf_read_at (bin->b, entry+11, buf, sizeof (buf)) == -1) {
bprintf ("Warning: read (get_fini)\n");
return 0;
}
if (*buf == 0x68) { // push // x86/32 only
ut64 addr;
memmove (buf, buf+1, 4);
addr = (ut64)r_read_le32 (buf);
return Elf_(r_bin_elf_v2p) (bin, addr);
}
return 0;
}
ut64 Elf_(r_bin_elf_get_entry_offset)(ELFOBJ *bin) {
ut64 entry;
if (!bin) {
return 0LL;
}
entry = bin->ehdr.e_entry;
if (!entry) {
entry = Elf_(r_bin_elf_get_section_offset)(bin, ".init.text");
if (entry != UT64_MAX) {
return entry;
}
entry = Elf_(r_bin_elf_get_section_offset)(bin, ".text");
if (entry != UT64_MAX) {
return entry;
}
entry = Elf_(r_bin_elf_get_section_offset)(bin, ".init");
if (entry != UT64_MAX) {
return entry;
}
if (entry == UT64_MAX) {
return 0;
}
}
return Elf_(r_bin_elf_v2p) (bin, entry);
}
static ut64 getmainsymbol(ELFOBJ *bin) {
struct r_bin_elf_symbol_t *symbol;
int i;
if (!(symbol = Elf_(r_bin_elf_get_symbols) (bin))) {
return UT64_MAX;
}
for (i = 0; !symbol[i].last; i++) {
if (!strcmp (symbol[i].name, "main")) {
ut64 paddr = symbol[i].offset;
return Elf_(r_bin_elf_p2v) (bin, paddr);
}
}
return UT64_MAX;
}
ut64 Elf_(r_bin_elf_get_main_offset)(ELFOBJ *bin) {
ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin);
ut8 buf[512];
if (!bin) {
return 0LL;
}
if (entry > bin->size || (entry + sizeof (buf)) > bin->size) {
return 0;
}
if (r_buf_read_at (bin->b, entry, buf, sizeof (buf)) < 1) {
bprintf ("Warning: read (main)\n");
return 0;
}
// ARM64
if (buf[0x18+3] == 0x58 && buf[0x2f] == 0x00) {
ut32 entry_vaddr = Elf_(r_bin_elf_p2v) (bin, entry);
ut32 main_addr = r_read_le32 (&buf[0x30]);
if ((main_addr >> 16) == (entry_vaddr >> 16)) {
return Elf_(r_bin_elf_v2p) (bin, main_addr);
}
}
// TODO: Use arch to identify arch before memcmp's
// ARM
ut64 text = Elf_(r_bin_elf_get_section_offset)(bin, ".text");
ut64 text_end = text + bin->size;
// ARM-Thumb-Linux
if (entry & 1 && !memcmp (buf, "\xf0\x00\x0b\x4f\xf0\x00", 6)) {
ut32 * ptr = (ut32*)(buf+40-1);
if (*ptr &1) {
return Elf_(r_bin_elf_v2p) (bin, *ptr -1);
}
}
if (!memcmp (buf, "\x00\xb0\xa0\xe3\x00\xe0\xa0\xe3", 8)) {
// endian stuff here
ut32 *addr = (ut32*)(buf+0x34);
/*
0x00012000 00b0a0e3 mov fp, 0
0x00012004 00e0a0e3 mov lr, 0
*/
if (*addr > text && *addr < (text_end)) {
return Elf_(r_bin_elf_v2p) (bin, *addr);
}
}
// MIPS
/* get .got, calculate offset of main symbol */
if (!memcmp (buf, "\x21\x00\xe0\x03\x01\x00\x11\x04", 8)) {
/*
assuming the startup code looks like
got = gp-0x7ff0
got[index__libc_start_main] ( got[index_main] );
looking for the instruction generating the first argument to find main
lw a0, offset(gp)
*/
ut64 got_offset;
if ((got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got")) != -1 ||
(got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got.plt")) != -1)
{
const ut64 gp = got_offset + 0x7ff0;
unsigned i;
for (i = 0; i < sizeof(buf) / sizeof(buf[0]); i += 4) {
const ut32 instr = r_read_le32 (&buf[i]);
if ((instr & 0xffff0000) == 0x8f840000) { // lw a0, offset(gp)
const short delta = instr & 0x0000ffff;
r_buf_read_at (bin->b, /* got_entry_offset = */ gp + delta, buf, 4);
return Elf_(r_bin_elf_v2p) (bin, r_read_le32 (&buf[0]));
}
}
}
return 0;
}
// ARM
if (!memcmp (buf, "\x24\xc0\x9f\xe5\x00\xb0\xa0\xe3", 8)) {
ut64 addr = r_read_le32 (&buf[48]);
return Elf_(r_bin_elf_v2p) (bin, addr);
}
// X86-CGC
if (buf[0] == 0xe8 && !memcmp (buf + 5, "\x50\xe8\x00\x00\x00\x00\xb8\x01\x00\x00\x00\x53", 12)) {
size_t SIZEOF_CALL = 5;
ut64 rel_addr = (ut64)((int)(buf[1] + (buf[2] << 8) + (buf[3] << 16) + (buf[4] << 24)));
ut64 addr = Elf_(r_bin_elf_p2v)(bin, entry + SIZEOF_CALL);
addr += rel_addr;
return Elf_(r_bin_elf_v2p) (bin, addr);
}
// X86-PIE
if (buf[0x00] == 0x48 && buf[0x1e] == 0x8d && buf[0x11] == 0xe8) {
ut32 *pmain = (ut32*)(buf + 0x30);
ut64 vmain = Elf_(r_bin_elf_p2v) (bin, (ut64)*pmain);
ut64 ventry = Elf_(r_bin_elf_p2v) (bin, entry);
if (vmain >> 16 == ventry >> 16) {
return (ut64)vmain;
}
}
// X86-PIE
if (buf[0x1d] == 0x48 && buf[0x1e] == 0x8b) {
if (!memcmp (buf, "\x31\xed\x49\x89", 4)) {// linux
ut64 maddr, baddr;
ut8 n32s[sizeof (ut32)] = {0};
maddr = entry + 0x24 + r_read_le32 (buf + 0x20);
if (r_buf_read_at (bin->b, maddr, n32s, sizeof (ut32)) == -1) {
bprintf ("Warning: read (maddr) 2\n");
return 0;
}
maddr = (ut64)r_read_le32 (&n32s[0]);
baddr = (bin->ehdr.e_entry >> 16) << 16;
if (bin->phdr) {
baddr = Elf_(r_bin_elf_get_baddr) (bin);
}
maddr += baddr;
return maddr;
}
}
// X86-NONPIE
#if R_BIN_ELF64
if (!memcmp (buf, "\x49\x89\xd9", 3) && buf[156] == 0xe8) { // openbsd
return r_read_le32 (&buf[157]) + entry + 156 + 5;
}
if (!memcmp (buf+29, "\x48\xc7\xc7", 3)) { // linux
ut64 addr = (ut64)r_read_le32 (&buf[29 + 3]);
return Elf_(r_bin_elf_v2p) (bin, addr);
}
#else
if (buf[23] == '\x68') {
ut64 addr = (ut64)r_read_le32 (&buf[23 + 1]);
return Elf_(r_bin_elf_v2p) (bin, addr);
}
#endif
/* linux64 pie main -- probably buggy in some cases */
if (buf[29] == 0x48 && buf[30] == 0x8d) { // lea rdi, qword [rip-0x21c4]
ut8 *p = buf + 32;
st32 maindelta = (st32)r_read_le32 (p);
ut64 vmain = (ut64)(entry + 29 + maindelta) + 7;
ut64 ventry = Elf_(r_bin_elf_p2v) (bin, entry);
if (vmain>>16 == ventry>>16) {
return (ut64)vmain;
}
}
/* find sym.main if possible */
{
ut64 m = getmainsymbol (bin);
if (m != UT64_MAX) return m;
}
return UT64_MAX;
}
int Elf_(r_bin_elf_get_stripped)(ELFOBJ *bin) {
int i;
if (!bin->shdr) {
return false;
}
for (i = 0; i < bin->ehdr.e_shnum; i++) {
if (bin->shdr[i].sh_type == SHT_SYMTAB) {
return false;
}
}
return true;
}
char *Elf_(r_bin_elf_intrp)(ELFOBJ *bin) {
int i;
if (!bin || !bin->phdr) {
return NULL;
}
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_INTERP) {
char *str = NULL;
ut64 addr = bin->phdr[i].p_offset;
int sz = bin->phdr[i].p_memsz;
sdb_num_set (bin->kv, "elf_header.intrp_addr", addr, 0);
sdb_num_set (bin->kv, "elf_header.intrp_size", sz, 0);
if (sz < 1) {
return NULL;
}
str = malloc (sz + 1);
if (!str) {
return NULL;
}
if (r_buf_read_at (bin->b, addr, (ut8*)str, sz) < 1) {
bprintf ("Warning: read (main)\n");
return 0;
}
str[sz] = 0;
sdb_set (bin->kv, "elf_header.intrp", str, 0);
return str;
}
}
return NULL;
}
int Elf_(r_bin_elf_get_static)(ELFOBJ *bin) {
int i;
if (!bin->phdr) {
return false;
}
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_INTERP) {
return false;
}
}
return true;
}
char* Elf_(r_bin_elf_get_data_encoding)(ELFOBJ *bin) {
switch (bin->ehdr.e_ident[EI_DATA]) {
case ELFDATANONE: return strdup ("none");
case ELFDATA2LSB: return strdup ("2's complement, little endian");
case ELFDATA2MSB: return strdup ("2's complement, big endian");
default: return r_str_newf ("<unknown: %x>", bin->ehdr.e_ident[EI_DATA]);
}
}
int Elf_(r_bin_elf_has_va)(ELFOBJ *bin) {
return true;
}
char* Elf_(r_bin_elf_get_arch)(ELFOBJ *bin) {
switch (bin->ehdr.e_machine) {
case EM_ARC:
case EM_ARC_A5:
return strdup ("arc");
case EM_AVR: return strdup ("avr");
case EM_CRIS: return strdup ("cris");
case EM_68K: return strdup ("m68k");
case EM_MIPS:
case EM_MIPS_RS3_LE:
case EM_MIPS_X:
return strdup ("mips");
case EM_MCST_ELBRUS:
return strdup ("elbrus");
case EM_TRICORE:
return strdup ("tricore");
case EM_ARM:
case EM_AARCH64:
return strdup ("arm");
case EM_HEXAGON:
return strdup ("hexagon");
case EM_BLACKFIN:
return strdup ("blackfin");
case EM_SPARC:
case EM_SPARC32PLUS:
case EM_SPARCV9:
return strdup ("sparc");
case EM_PPC:
case EM_PPC64:
return strdup ("ppc");
case EM_PARISC:
return strdup ("hppa");
case EM_PROPELLER:
return strdup ("propeller");
case EM_MICROBLAZE:
return strdup ("microblaze.gnu");
case EM_RISCV:
return strdup ("riscv");
case EM_VAX:
return strdup ("vax");
case EM_XTENSA:
return strdup ("xtensa");
case EM_LANAI:
return strdup ("lanai");
case EM_VIDEOCORE3:
case EM_VIDEOCORE4:
return strdup ("vc4");
case EM_SH:
return strdup ("sh");
case EM_V850:
return strdup ("v850");
case EM_IA_64:
return strdup("ia64");
default: return strdup ("x86");
}
}
char* Elf_(r_bin_elf_get_machine_name)(ELFOBJ *bin) {
switch (bin->ehdr.e_machine) {
case EM_NONE: return strdup ("No machine");
case EM_M32: return strdup ("AT&T WE 32100");
case EM_SPARC: return strdup ("SUN SPARC");
case EM_386: return strdup ("Intel 80386");
case EM_68K: return strdup ("Motorola m68k family");
case EM_88K: return strdup ("Motorola m88k family");
case EM_860: return strdup ("Intel 80860");
case EM_MIPS: return strdup ("MIPS R3000");
case EM_S370: return strdup ("IBM System/370");
case EM_MIPS_RS3_LE: return strdup ("MIPS R3000 little-endian");
case EM_PARISC: return strdup ("HPPA");
case EM_VPP500: return strdup ("Fujitsu VPP500");
case EM_SPARC32PLUS: return strdup ("Sun's \"v8plus\"");
case EM_960: return strdup ("Intel 80960");
case EM_PPC: return strdup ("PowerPC");
case EM_PPC64: return strdup ("PowerPC 64-bit");
case EM_S390: return strdup ("IBM S390");
case EM_V800: return strdup ("NEC V800 series");
case EM_FR20: return strdup ("Fujitsu FR20");
case EM_RH32: return strdup ("TRW RH-32");
case EM_RCE: return strdup ("Motorola RCE");
case EM_ARM: return strdup ("ARM");
case EM_BLACKFIN: return strdup ("Analog Devices Blackfin");
case EM_FAKE_ALPHA: return strdup ("Digital Alpha");
case EM_SH: return strdup ("Hitachi SH");
case EM_SPARCV9: return strdup ("SPARC v9 64-bit");
case EM_TRICORE: return strdup ("Siemens Tricore");
case EM_ARC: return strdup ("Argonaut RISC Core");
case EM_H8_300: return strdup ("Hitachi H8/300");
case EM_H8_300H: return strdup ("Hitachi H8/300H");
case EM_H8S: return strdup ("Hitachi H8S");
case EM_H8_500: return strdup ("Hitachi H8/500");
case EM_IA_64: return strdup ("Intel Merced");
case EM_MIPS_X: return strdup ("Stanford MIPS-X");
case EM_COLDFIRE: return strdup ("Motorola Coldfire");
case EM_68HC12: return strdup ("Motorola M68HC12");
case EM_MMA: return strdup ("Fujitsu MMA Multimedia Accelerator");
case EM_PCP: return strdup ("Siemens PCP");
case EM_NCPU: return strdup ("Sony nCPU embeeded RISC");
case EM_NDR1: return strdup ("Denso NDR1 microprocessor");
case EM_STARCORE: return strdup ("Motorola Start*Core processor");
case EM_ME16: return strdup ("Toyota ME16 processor");
case EM_ST100: return strdup ("STMicroelectronic ST100 processor");
case EM_TINYJ: return strdup ("Advanced Logic Corp. Tinyj emb.fam");
case EM_X86_64: return strdup ("AMD x86-64 architecture");
case EM_LANAI: return strdup ("32bit LANAI architecture");
case EM_PDSP: return strdup ("Sony DSP Processor");
case EM_FX66: return strdup ("Siemens FX66 microcontroller");
case EM_ST9PLUS: return strdup ("STMicroelectronics ST9+ 8/16 mc");
case EM_ST7: return strdup ("STmicroelectronics ST7 8 bit mc");
case EM_68HC16: return strdup ("Motorola MC68HC16 microcontroller");
case EM_68HC11: return strdup ("Motorola MC68HC11 microcontroller");
case EM_68HC08: return strdup ("Motorola MC68HC08 microcontroller");
case EM_68HC05: return strdup ("Motorola MC68HC05 microcontroller");
case EM_SVX: return strdup ("Silicon Graphics SVx");
case EM_ST19: return strdup ("STMicroelectronics ST19 8 bit mc");
case EM_VAX: return strdup ("Digital VAX");
case EM_CRIS: return strdup ("Axis Communications 32-bit embedded processor");
case EM_JAVELIN: return strdup ("Infineon Technologies 32-bit embedded processor");
case EM_FIREPATH: return strdup ("Element 14 64-bit DSP Processor");
case EM_ZSP: return strdup ("LSI Logic 16-bit DSP Processor");
case EM_MMIX: return strdup ("Donald Knuth's educational 64-bit processor");
case EM_HUANY: return strdup ("Harvard University machine-independent object files");
case EM_PRISM: return strdup ("SiTera Prism");
case EM_AVR: return strdup ("Atmel AVR 8-bit microcontroller");
case EM_FR30: return strdup ("Fujitsu FR30");
case EM_D10V: return strdup ("Mitsubishi D10V");
case EM_D30V: return strdup ("Mitsubishi D30V");
case EM_V850: return strdup ("NEC v850");
case EM_M32R: return strdup ("Mitsubishi M32R");
case EM_MN10300: return strdup ("Matsushita MN10300");
case EM_MN10200: return strdup ("Matsushita MN10200");
case EM_PJ: return strdup ("picoJava");
case EM_OPENRISC: return strdup ("OpenRISC 32-bit embedded processor");
case EM_ARC_A5: return strdup ("ARC Cores Tangent-A5");
case EM_XTENSA: return strdup ("Tensilica Xtensa Architecture");
case EM_AARCH64: return strdup ("ARM aarch64");
case EM_PROPELLER: return strdup ("Parallax Propeller");
case EM_MICROBLAZE: return strdup ("Xilinx MicroBlaze");
case EM_RISCV: return strdup ("RISC V");
case EM_VIDEOCORE3: return strdup ("VideoCore III");
case EM_VIDEOCORE4: return strdup ("VideoCore IV");
default: return r_str_newf ("<unknown>: 0x%x", bin->ehdr.e_machine);
}
}
char* Elf_(r_bin_elf_get_file_type)(ELFOBJ *bin) {
ut32 e_type;
if (!bin) {
return NULL;
}
e_type = (ut32)bin->ehdr.e_type; // cast to avoid warn in iphone-gcc, must be ut16
switch (e_type) {
case ET_NONE: return strdup ("NONE (None)");
case ET_REL: return strdup ("REL (Relocatable file)");
case ET_EXEC: return strdup ("EXEC (Executable file)");
case ET_DYN: return strdup ("DYN (Shared object file)");
case ET_CORE: return strdup ("CORE (Core file)");
}
if ((e_type >= ET_LOPROC) && (e_type <= ET_HIPROC)) {
return r_str_newf ("Processor Specific: %x", e_type);
}
if ((e_type >= ET_LOOS) && (e_type <= ET_HIOS)) {
return r_str_newf ("OS Specific: %x", e_type);
}
return r_str_newf ("<unknown>: %x", e_type);
}
char* Elf_(r_bin_elf_get_elf_class)(ELFOBJ *bin) {
switch (bin->ehdr.e_ident[EI_CLASS]) {
case ELFCLASSNONE: return strdup ("none");
case ELFCLASS32: return strdup ("ELF32");
case ELFCLASS64: return strdup ("ELF64");
default: return r_str_newf ("<unknown: %x>", bin->ehdr.e_ident[EI_CLASS]);
}
}
int Elf_(r_bin_elf_get_bits)(ELFOBJ *bin) {
/* Hack for ARCompact */
if (bin->ehdr.e_machine == EM_ARC_A5) {
return 16;
}
/* Hack for Ps2 */
if (bin->phdr && bin->ehdr.e_machine == EM_MIPS) {
const ut32 mipsType = bin->ehdr.e_flags & EF_MIPS_ARCH;
if (bin->ehdr.e_type == ET_EXEC) {
int i;
bool haveInterp = false;
for (i = 0; i < bin->ehdr.e_phnum; i++) {
if (bin->phdr[i].p_type == PT_INTERP) {
haveInterp = true;
}
}
if (!haveInterp && mipsType == EF_MIPS_ARCH_3) {
// Playstation2 Hack
return 64;
}
}
// TODO: show this specific asm.cpu somewhere in bininfo (mips1, mips2, mips3, mips32r2, ...)
switch (mipsType) {
case EF_MIPS_ARCH_1:
case EF_MIPS_ARCH_2:
case EF_MIPS_ARCH_3:
case EF_MIPS_ARCH_4:
case EF_MIPS_ARCH_5:
case EF_MIPS_ARCH_32:
return 32;
case EF_MIPS_ARCH_64:
return 64;
case EF_MIPS_ARCH_32R2:
return 32;
case EF_MIPS_ARCH_64R2:
return 64;
break;
}
return 32;
}
/* Hack for Thumb */
if (bin->ehdr.e_machine == EM_ARM) {
if (bin->ehdr.e_type != ET_EXEC) {
struct r_bin_elf_symbol_t *symbol;
if ((symbol = Elf_(r_bin_elf_get_symbols) (bin))) {
int i = 0;
for (i = 0; !symbol[i].last; i++) {
ut64 paddr = symbol[i].offset;
if (paddr & 1) {
return 16;
}
}
}
}
{
ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin);
if (entry & 1) {
return 16;
}
}
}
switch (bin->ehdr.e_ident[EI_CLASS]) {
case ELFCLASS32: return 32;
case ELFCLASS64: return 64;
case ELFCLASSNONE:
default: return 32; // defaults
}
}
static inline int noodle(ELFOBJ *bin, const char *s) {
const ut8 *p = bin->b->buf;
if (bin->b->length > 64) {
p += bin->b->length - 64;
} else {
return 0;
}
return r_mem_mem (p, 64, (const ut8 *)s, strlen (s)) != NULL;
}
static inline int needle(ELFOBJ *bin, const char *s) {
if (bin->shstrtab) {
ut32 len = bin->shstrtab_size;
if (len > 4096) {
len = 4096; // avoid slow loading .. can be buggy?
}
return r_mem_mem ((const ut8*)bin->shstrtab, len,
(const ut8*)s, strlen (s)) != NULL;
}
return 0;
}
// TODO: must return const char * all those strings must be const char os[LINUX] or so
char* Elf_(r_bin_elf_get_osabi_name)(ELFOBJ *bin) {
switch (bin->ehdr.e_ident[EI_OSABI]) {
case ELFOSABI_LINUX: return strdup("linux");
case ELFOSABI_SOLARIS: return strdup("solaris");
case ELFOSABI_FREEBSD: return strdup("freebsd");
case ELFOSABI_HPUX: return strdup("hpux");
}
/* Hack to identify OS */
if (needle (bin, "openbsd")) return strdup ("openbsd");
if (needle (bin, "netbsd")) return strdup ("netbsd");
if (needle (bin, "freebsd")) return strdup ("freebsd");
if (noodle (bin, "BEOS:APP_VERSION")) return strdup ("beos");
if (needle (bin, "GNU")) return strdup ("linux");
return strdup ("linux");
}
ut8 *Elf_(r_bin_elf_grab_regstate)(ELFOBJ *bin, int *len) {
if (bin->phdr) {
int i;
int num = bin->ehdr.e_phnum;
for (i = 0; i < num; i++) {
if (bin->phdr[i].p_type != PT_NOTE) {
continue;
}
int bits = Elf_(r_bin_elf_get_bits)(bin);
int regdelta = (bits == 64)? 0x84: 0x40; // x64 vs x32
int regsize = 160; // for x86-64
ut8 *buf = malloc (regsize);
if (r_buf_read_at (bin->b, bin->phdr[i].p_offset + regdelta, buf, regsize) != regsize) {
free (buf);
bprintf ("Cannot read register state from CORE file\n");
return NULL;
}
if (len) {
*len = regsize;
}
return buf;
}
}
bprintf ("Cannot find NOTE section\n");
return NULL;
}
int Elf_(r_bin_elf_is_big_endian)(ELFOBJ *bin) {
return (bin->ehdr.e_ident[EI_DATA] == ELFDATA2MSB);
}
/* XXX Init dt_strtab? */
char *Elf_(r_bin_elf_get_rpath)(ELFOBJ *bin) {
char *ret = NULL;
int j;
if (!bin || !bin->phdr || !bin->dyn_buf || !bin->strtab) {
return NULL;
}
for (j = 0; j< bin->dyn_entries; j++) {
if (bin->dyn_buf[j].d_tag == DT_RPATH || bin->dyn_buf[j].d_tag == DT_RUNPATH) {
if (!(ret = calloc (1, ELF_STRING_LENGTH))) {
perror ("malloc (rpath)");
return NULL;
}
if (bin->dyn_buf[j].d_un.d_val > bin->strtab_size) {
free (ret);
return NULL;
}
strncpy (ret, bin->strtab + bin->dyn_buf[j].d_un.d_val, ELF_STRING_LENGTH);
ret[ELF_STRING_LENGTH - 1] = '\0';
break;
}
}
return ret;
}
static size_t get_relocs_num(ELFOBJ *bin) {
size_t i, size, ret = 0;
/* we need to be careful here, in malformed files the section size might
* not be a multiple of a Rel/Rela size; round up so we allocate enough
* space.
*/
#define NUMENTRIES_ROUNDUP(sectionsize, entrysize) (((sectionsize)+(entrysize)-1)/(entrysize))
if (!bin->g_sections) {
return 0;
}
size = bin->is_rela == DT_REL ? sizeof (Elf_(Rel)) : sizeof (Elf_(Rela));
for (i = 0; !bin->g_sections[i].last; i++) {
if (!strncmp (bin->g_sections[i].name, ".rela.", strlen (".rela."))) {
if (!bin->is_rela) {
size = sizeof (Elf_(Rela));
}
ret += NUMENTRIES_ROUNDUP (bin->g_sections[i].size, size);
} else if (!strncmp (bin->g_sections[i].name, ".rel.", strlen (".rel."))){
if (!bin->is_rela) {
size = sizeof (Elf_(Rel));
}
ret += NUMENTRIES_ROUNDUP (bin->g_sections[i].size, size);
}
}
return ret;
#undef NUMENTRIES_ROUNDUP
}
static int read_reloc(ELFOBJ *bin, RBinElfReloc *r, int is_rela, ut64 offset) {
ut8 *buf = bin->b->buf;
int j = 0;
if (offset + sizeof (Elf_ (Rela)) >
bin->size || offset + sizeof (Elf_(Rela)) < offset) {
return -1;
}
if (is_rela == DT_RELA) {
Elf_(Rela) rela;
#if R_BIN_ELF64
rela.r_offset = READ64 (buf + offset, j)
rela.r_info = READ64 (buf + offset, j)
rela.r_addend = READ64 (buf + offset, j)
#else
rela.r_offset = READ32 (buf + offset, j)
rela.r_info = READ32 (buf + offset, j)
rela.r_addend = READ32 (buf + offset, j)
#endif
r->is_rela = is_rela;
r->offset = rela.r_offset;
r->type = ELF_R_TYPE (rela.r_info);
r->sym = ELF_R_SYM (rela.r_info);
r->last = 0;
r->addend = rela.r_addend;
return sizeof (Elf_(Rela));
} else {
Elf_(Rel) rel;
#if R_BIN_ELF64
rel.r_offset = READ64 (buf + offset, j)
rel.r_info = READ64 (buf + offset, j)
#else
rel.r_offset = READ32 (buf + offset, j)
rel.r_info = READ32 (buf + offset, j)
#endif
r->is_rela = is_rela;
r->offset = rel.r_offset;
r->type = ELF_R_TYPE (rel.r_info);
r->sym = ELF_R_SYM (rel.r_info);
r->last = 0;
return sizeof (Elf_(Rel));
}
}
RBinElfReloc* Elf_(r_bin_elf_get_relocs)(ELFOBJ *bin) {
int res, rel, rela, i, j;
size_t reloc_num = 0;
RBinElfReloc *ret = NULL;
if (!bin || !bin->g_sections) {
return NULL;
}
reloc_num = get_relocs_num (bin);
if (!reloc_num) {
return NULL;
}
bin->reloc_num = reloc_num;
ret = (RBinElfReloc*)calloc ((size_t)reloc_num + 1, sizeof(RBinElfReloc));
if (!ret) {
return NULL;
}
#if DEAD_CODE
ut64 section_text_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".text");
if (section_text_offset == -1) {
section_text_offset = 0;
}
#endif
for (i = 0, rel = 0; !bin->g_sections[i].last && rel < reloc_num ; i++) {
bool is_rela = 0 == strncmp (bin->g_sections[i].name, ".rela.", strlen (".rela."));
bool is_rel = 0 == strncmp (bin->g_sections[i].name, ".rel.", strlen (".rel."));
if (!is_rela && !is_rel) {
continue;
}
for (j = 0; j < bin->g_sections[i].size; j += res) {
if (bin->g_sections[i].size > bin->size) {
break;
}
if (bin->g_sections[i].offset > bin->size) {
break;
}
if (rel >= reloc_num) {
bprintf ("Internal error: ELF relocation buffer too small,"
"please file a bug report.");
break;
}
if (!bin->is_rela) {
rela = is_rela? DT_RELA : DT_REL;
} else {
rela = bin->is_rela;
}
res = read_reloc (bin, &ret[rel], rela, bin->g_sections[i].offset + j);
if (j + res > bin->g_sections[i].size) {
bprintf ("Warning: malformed file, relocation entry #%u is partially beyond the end of section %u.\n", rel, i);
}
if (bin->ehdr.e_type == ET_REL) {
if (bin->g_sections[i].info < bin->ehdr.e_shnum && bin->shdr) {
ret[rel].rva = bin->shdr[bin->g_sections[i].info].sh_offset + ret[rel].offset;
ret[rel].rva = Elf_(r_bin_elf_p2v) (bin, ret[rel].rva);
} else {
ret[rel].rva = ret[rel].offset;
}
} else {
ret[rel].rva = ret[rel].offset;
ret[rel].offset = Elf_(r_bin_elf_v2p) (bin, ret[rel].offset);
}
ret[rel].last = 0;
if (res < 0) {
break;
}
rel++;
}
}
ret[reloc_num].last = 1;
return ret;
}
RBinElfLib* Elf_(r_bin_elf_get_libs)(ELFOBJ *bin) {
RBinElfLib *ret = NULL;
int j, k;
if (!bin || !bin->phdr || !bin->dyn_buf || !bin->strtab || *(bin->strtab+1) == '0') {
return NULL;
}
for (j = 0, k = 0; j < bin->dyn_entries; j++)
if (bin->dyn_buf[j].d_tag == DT_NEEDED) {
RBinElfLib *r = realloc (ret, (k + 1) * sizeof (RBinElfLib));
if (!r) {
perror ("realloc (libs)");
free (ret);
return NULL;
}
ret = r;
if (bin->dyn_buf[j].d_un.d_val > bin->strtab_size) {
free (ret);
return NULL;
}
strncpy (ret[k].name, bin->strtab + bin->dyn_buf[j].d_un.d_val, ELF_STRING_LENGTH);
ret[k].name[ELF_STRING_LENGTH - 1] = '\0';
ret[k].last = 0;
if (ret[k].name[0]) {
k++;
}
}
RBinElfLib *r = realloc (ret, (k + 1) * sizeof (RBinElfLib));
if (!r) {
perror ("realloc (libs)");
free (ret);
return NULL;
}
ret = r;
ret[k].last = 1;
return ret;
}
static RBinElfSection* get_sections_from_phdr(ELFOBJ *bin) {
RBinElfSection *ret;
int i, num_sections = 0;
ut64 reldyn = 0, relava = 0, pltgotva = 0, relva = 0;
ut64 reldynsz = 0, relasz = 0, pltgotsz = 0;
if (!bin || !bin->phdr || !bin->ehdr.e_phnum)
return NULL;
for (i = 0; i < bin->dyn_entries; i++) {
switch (bin->dyn_buf[i].d_tag) {
case DT_REL:
reldyn = bin->dyn_buf[i].d_un.d_ptr;
num_sections++;
break;
case DT_RELA:
relva = bin->dyn_buf[i].d_un.d_ptr;
num_sections++;
break;
case DT_RELSZ:
reldynsz = bin->dyn_buf[i].d_un.d_val;
break;
case DT_RELASZ:
relasz = bin->dyn_buf[i].d_un.d_val;
break;
case DT_PLTGOT:
pltgotva = bin->dyn_buf[i].d_un.d_ptr;
num_sections++;
break;
case DT_PLTRELSZ:
pltgotsz = bin->dyn_buf[i].d_un.d_val;
break;
case DT_JMPREL:
relava = bin->dyn_buf[i].d_un.d_ptr;
num_sections++;
break;
default: break;
}
}
ret = calloc (num_sections + 1, sizeof(RBinElfSection));
if (!ret) {
return NULL;
}
i = 0;
if (reldyn) {
ret[i].offset = Elf_(r_bin_elf_v2p) (bin, reldyn);
ret[i].rva = reldyn;
ret[i].size = reldynsz;
strcpy (ret[i].name, ".rel.dyn");
ret[i].last = 0;
i++;
}
if (relava) {
ret[i].offset = Elf_(r_bin_elf_v2p) (bin, relava);
ret[i].rva = relava;
ret[i].size = pltgotsz;
strcpy (ret[i].name, ".rela.plt");
ret[i].last = 0;
i++;
}
if (relva) {
ret[i].offset = Elf_(r_bin_elf_v2p) (bin, relva);
ret[i].rva = relva;
ret[i].size = relasz;
strcpy (ret[i].name, ".rel.plt");
ret[i].last = 0;
i++;
}
if (pltgotva) {
ret[i].offset = Elf_(r_bin_elf_v2p) (bin, pltgotva);
ret[i].rva = pltgotva;
ret[i].size = pltgotsz;
strcpy (ret[i].name, ".got.plt");
ret[i].last = 0;
i++;
}
ret[i].last = 1;
return ret;
}
RBinElfSection* Elf_(r_bin_elf_get_sections)(ELFOBJ *bin) {
RBinElfSection *ret = NULL;
char unknown_s[20], invalid_s[20];
int i, nidx, unknown_c=0, invalid_c=0;
if (!bin) {
return NULL;
}
if (bin->g_sections) {
return bin->g_sections;
}
if (!bin->shdr) {
//we don't give up search in phdr section
return get_sections_from_phdr (bin);
}
if (!(ret = calloc ((bin->ehdr.e_shnum + 1), sizeof (RBinElfSection)))) {
return NULL;
}
for (i = 0; i < bin->ehdr.e_shnum; i++) {
ret[i].offset = bin->shdr[i].sh_offset;
ret[i].size = bin->shdr[i].sh_size;
ret[i].align = bin->shdr[i].sh_addralign;
ret[i].flags = bin->shdr[i].sh_flags;
ret[i].link = bin->shdr[i].sh_link;
ret[i].info = bin->shdr[i].sh_info;
ret[i].type = bin->shdr[i].sh_type;
if (bin->ehdr.e_type == ET_REL) {
ret[i].rva = bin->baddr + bin->shdr[i].sh_offset;
} else {
ret[i].rva = bin->shdr[i].sh_addr;
}
nidx = bin->shdr[i].sh_name;
#define SHNAME (int)bin->shdr[i].sh_name
#define SHNLEN ELF_STRING_LENGTH - 4
#define SHSIZE (int)bin->shstrtab_size
if (nidx < 0 || !bin->shstrtab_section || !bin->shstrtab_size || nidx > bin->shstrtab_size) {
snprintf (invalid_s, sizeof (invalid_s) - 4, "invalid%d", invalid_c);
strncpy (ret[i].name, invalid_s, SHNLEN);
invalid_c++;
} else {
if (bin->shstrtab && (SHNAME > 0) && (SHNAME < SHSIZE)) {
strncpy (ret[i].name, &bin->shstrtab[SHNAME], SHNLEN);
} else {
if (bin->shdr[i].sh_type == SHT_NULL) {
//to follow the same behaviour as readelf
strncpy (ret[i].name, "", sizeof (ret[i].name) - 4);
} else {
snprintf (unknown_s, sizeof (unknown_s)-4, "unknown%d", unknown_c);
strncpy (ret[i].name, unknown_s, sizeof (ret[i].name)-4);
unknown_c++;
}
}
}
ret[i].name[ELF_STRING_LENGTH-2] = '\0';
ret[i].last = 0;
}
ret[i].last = 1;
return ret;
}
static void fill_symbol_bind_and_type (struct r_bin_elf_symbol_t *ret, Elf_(Sym) *sym) {
#define s_bind(x) ret->bind = x
#define s_type(x) ret->type = x
switch (ELF_ST_BIND(sym->st_info)) {
case STB_LOCAL: s_bind ("LOCAL"); break;
case STB_GLOBAL: s_bind ("GLOBAL"); break;
case STB_WEAK: s_bind ("WEAK"); break;
case STB_NUM: s_bind ("NUM"); break;
case STB_LOOS: s_bind ("LOOS"); break;
case STB_HIOS: s_bind ("HIOS"); break;
case STB_LOPROC: s_bind ("LOPROC"); break;
case STB_HIPROC: s_bind ("HIPROC"); break;
default: s_bind ("UNKNOWN");
}
switch (ELF_ST_TYPE (sym->st_info)) {
case STT_NOTYPE: s_type ("NOTYPE"); break;
case STT_OBJECT: s_type ("OBJECT"); break;
case STT_FUNC: s_type ("FUNC"); break;
case STT_SECTION: s_type ("SECTION"); break;
case STT_FILE: s_type ("FILE"); break;
case STT_COMMON: s_type ("COMMON"); break;
case STT_TLS: s_type ("TLS"); break;
case STT_NUM: s_type ("NUM"); break;
case STT_LOOS: s_type ("LOOS"); break;
case STT_HIOS: s_type ("HIOS"); break;
case STT_LOPROC: s_type ("LOPROC"); break;
case STT_HIPROC: s_type ("HIPROC"); break;
default: s_type ("UNKNOWN");
}
}
static RBinElfSymbol* get_symbols_from_phdr(ELFOBJ *bin, int type) {
Elf_(Sym) *sym = NULL;
Elf_(Addr) addr_sym_table = 0;
ut8 s[sizeof (Elf_(Sym))] = {0};
RBinElfSymbol *ret = NULL;
int i, j, r, tsize, nsym, ret_ctr;
ut64 toffset = 0, tmp_offset;
ut32 size, sym_size = 0;
if (!bin || !bin->phdr || !bin->ehdr.e_phnum) {
return NULL;
}
for (j = 0; j < bin->dyn_entries; j++) {
switch (bin->dyn_buf[j].d_tag) {
case (DT_SYMTAB):
addr_sym_table = Elf_(r_bin_elf_v2p) (bin, bin->dyn_buf[j].d_un.d_ptr);
break;
case (DT_SYMENT):
sym_size = bin->dyn_buf[j].d_un.d_val;
break;
default:
break;
}
}
if (!addr_sym_table) {
return NULL;
}
if (!sym_size) {
return NULL;
}
//since ELF doesn't specify the symbol table size we may read until the end of the buffer
nsym = (bin->size - addr_sym_table) / sym_size;
if (!UT32_MUL (&size, nsym, sizeof (Elf_ (Sym)))) {
goto beach;
}
if (size < 1) {
goto beach;
}
if (addr_sym_table > bin->size || addr_sym_table + size > bin->size) {
goto beach;
}
if (nsym < 1) {
return NULL;
}
// we reserve room for 4096 and grow as needed.
size_t capacity1 = 4096;
size_t capacity2 = 4096;
sym = (Elf_(Sym)*) calloc (capacity1, sym_size);
ret = (RBinElfSymbol *) calloc (capacity2, sizeof (struct r_bin_elf_symbol_t));
if (!sym || !ret) {
goto beach;
}
for (i = 1, ret_ctr = 0; i < nsym; i++) {
if (i >= capacity1) { // maybe grow
// You take what you want, but you eat what you take.
Elf_(Sym)* temp_sym = (Elf_(Sym)*) realloc(sym, (capacity1 * GROWTH_FACTOR) * sym_size);
if (!temp_sym) {
goto beach;
}
sym = temp_sym;
capacity1 *= GROWTH_FACTOR;
}
if (ret_ctr >= capacity2) { // maybe grow
RBinElfSymbol *temp_ret = realloc (ret, capacity2 * GROWTH_FACTOR * sizeof (struct r_bin_elf_symbol_t));
if (!temp_ret) {
goto beach;
}
ret = temp_ret;
capacity2 *= GROWTH_FACTOR;
}
// read in one entry
r = r_buf_read_at (bin->b, addr_sym_table + i * sizeof (Elf_ (Sym)), s, sizeof (Elf_ (Sym)));
if (r < 1) {
goto beach;
}
int j = 0;
#if R_BIN_ELF64
sym[i].st_name = READ32 (s, j);
sym[i].st_info = READ8 (s, j);
sym[i].st_other = READ8 (s, j);
sym[i].st_shndx = READ16 (s, j);
sym[i].st_value = READ64 (s, j);
sym[i].st_size = READ64 (s, j);
#else
sym[i].st_name = READ32 (s, j);
sym[i].st_value = READ32 (s, j);
sym[i].st_size = READ32 (s, j);
sym[i].st_info = READ8 (s, j);
sym[i].st_other = READ8 (s, j);
sym[i].st_shndx = READ16 (s, j);
#endif
// zero symbol is always empty
// Examine entry and maybe store
if (type == R_BIN_ELF_IMPORTS && sym[i].st_shndx == STN_UNDEF) {
if (sym[i].st_value) {
toffset = sym[i].st_value;
} else if ((toffset = get_import_addr (bin, i)) == -1){
toffset = 0;
}
tsize = 16;
} else if (type == R_BIN_ELF_SYMBOLS &&
sym[i].st_shndx != STN_UNDEF &&
ELF_ST_TYPE (sym[i].st_info) != STT_SECTION &&
ELF_ST_TYPE (sym[i].st_info) != STT_FILE) {
tsize = sym[i].st_size;
toffset = (ut64) sym[i].st_value;
} else {
continue;
}
tmp_offset = Elf_(r_bin_elf_v2p) (bin, toffset);
if (tmp_offset > bin->size) {
goto done;
}
if (sym[i].st_name + 2 > bin->strtab_size) {
// Since we are reading beyond the symbol table what's happening
// is that some entry is trying to dereference the strtab beyond its capacity
// is not a symbol so is the end
goto done;
}
ret[ret_ctr].offset = tmp_offset;
ret[ret_ctr].size = tsize;
{
int rest = ELF_STRING_LENGTH - 1;
int st_name = sym[i].st_name;
int maxsize = R_MIN (bin->size, bin->strtab_size);
if (st_name < 0 || st_name >= maxsize) {
ret[ret_ctr].name[0] = 0;
} else {
const int len = __strnlen (bin->strtab + st_name, rest);
memcpy (ret[ret_ctr].name, &bin->strtab[st_name], len);
}
}
ret[ret_ctr].ordinal = i;
ret[ret_ctr].in_shdr = false;
ret[ret_ctr].name[ELF_STRING_LENGTH - 2] = '\0';
fill_symbol_bind_and_type (&ret[ret_ctr], &sym[i]);
ret[ret_ctr].last = 0;
ret_ctr++;
}
done:
ret[ret_ctr].last = 1;
// Size everything down to only what is used
{
nsym = i > 0 ? i : 1;
Elf_ (Sym) * temp_sym = (Elf_ (Sym)*) realloc (sym, (nsym * GROWTH_FACTOR) * sym_size);
if (!temp_sym) {
goto beach;
}
sym = temp_sym;
}
{
ret_ctr = ret_ctr > 0 ? ret_ctr : 1;
RBinElfSymbol *p = (RBinElfSymbol *) realloc (ret, (ret_ctr + 1) * sizeof (RBinElfSymbol));
if (!p) {
goto beach;
}
ret = p;
}
if (type == R_BIN_ELF_IMPORTS && !bin->imports_by_ord_size) {
bin->imports_by_ord_size = ret_ctr + 1;
if (ret_ctr > 0) {
bin->imports_by_ord = (RBinImport * *) calloc (ret_ctr + 1, sizeof (RBinImport*));
} else {
bin->imports_by_ord = NULL;
}
} else if (type == R_BIN_ELF_SYMBOLS && !bin->symbols_by_ord_size && ret_ctr) {
bin->symbols_by_ord_size = ret_ctr + 1;
if (ret_ctr > 0) {
bin->symbols_by_ord = (RBinSymbol * *) calloc (ret_ctr + 1, sizeof (RBinSymbol*));
}else {
bin->symbols_by_ord = NULL;
}
}
free (sym);
return ret;
beach:
free (sym);
free (ret);
return NULL;
}
static RBinElfSymbol *Elf_(r_bin_elf_get_phdr_symbols)(ELFOBJ *bin) {
if (!bin) {
return NULL;
}
if (bin->phdr_symbols) {
return bin->phdr_symbols;
}
bin->phdr_symbols = get_symbols_from_phdr (bin, R_BIN_ELF_SYMBOLS);
return bin->phdr_symbols;
}
static RBinElfSymbol *Elf_(r_bin_elf_get_phdr_imports)(ELFOBJ *bin) {
if (!bin) {
return NULL;
}
if (bin->phdr_imports) {
return bin->phdr_imports;
}
bin->phdr_imports = get_symbols_from_phdr (bin, R_BIN_ELF_IMPORTS);
return bin->phdr_imports;
}
static int Elf_(fix_symbols)(ELFOBJ *bin, int nsym, int type, RBinElfSymbol **sym) {
int count = 0;
RBinElfSymbol *ret = *sym;
RBinElfSymbol *phdr_symbols = (type == R_BIN_ELF_SYMBOLS)
? Elf_(r_bin_elf_get_phdr_symbols) (bin)
: Elf_(r_bin_elf_get_phdr_imports) (bin);
RBinElfSymbol *tmp, *p;
if (phdr_symbols) {
RBinElfSymbol *d = ret;
while (!d->last) {
/* find match in phdr */
p = phdr_symbols;
while (!p->last) {
if (p->offset && d->offset == p->offset) {
p->in_shdr = true;
if (*p->name && strcmp (d->name, p->name)) {
strcpy (d->name, p->name);
}
}
p++;
}
d++;
}
p = phdr_symbols;
while (!p->last) {
if (!p->in_shdr) {
count++;
}
p++;
}
/*Take those symbols that are not present in the shdr but yes in phdr*/
/*This should only should happen with fucked up binaries*/
if (count > 0) {
/*what happens if a shdr says it has only one symbol? we should look anyway into phdr*/
tmp = (RBinElfSymbol*)realloc (ret, (nsym + count + 1) * sizeof (RBinElfSymbol));
if (!tmp) {
return -1;
}
ret = tmp;
ret[nsym--].last = 0;
p = phdr_symbols;
while (!p->last) {
if (!p->in_shdr) {
memcpy (&ret[++nsym], p, sizeof (RBinElfSymbol));
}
p++;
}
ret[nsym + 1].last = 1;
}
*sym = ret;
return nsym + 1;
}
return nsym;
}
static RBinElfSymbol* Elf_(_r_bin_elf_get_symbols_imports)(ELFOBJ *bin, int type) {
ut32 shdr_size;
int tsize, nsym, ret_ctr = 0, i, j, r, k, newsize;
ut64 toffset;
ut32 size = 0;
RBinElfSymbol *ret = NULL;
Elf_(Shdr) *strtab_section = NULL;
Elf_(Sym) *sym = NULL;
ut8 s[sizeof (Elf_(Sym))] = { 0 };
char *strtab = NULL;
if (!bin || !bin->shdr || !bin->ehdr.e_shnum || bin->ehdr.e_shnum == 0xffff) {
return (type == R_BIN_ELF_SYMBOLS)
? Elf_(r_bin_elf_get_phdr_symbols) (bin)
: Elf_(r_bin_elf_get_phdr_imports) (bin);
}
if (!UT32_MUL (&shdr_size, bin->ehdr.e_shnum, sizeof (Elf_(Shdr)))) {
return false;
}
if (shdr_size + 8 > bin->size) {
return false;
}
for (i = 0; i < bin->ehdr.e_shnum; i++) {
if ((type == R_BIN_ELF_IMPORTS && bin->shdr[i].sh_type == (bin->ehdr.e_type == ET_REL ? SHT_SYMTAB : SHT_DYNSYM)) ||
(type == R_BIN_ELF_SYMBOLS && bin->shdr[i].sh_type == (Elf_(r_bin_elf_get_stripped) (bin) ? SHT_DYNSYM : SHT_SYMTAB))) {
if (bin->shdr[i].sh_link < 1) {
/* oops. fix out of range pointers */
continue;
}
// hack to avoid asan cry
if ((bin->shdr[i].sh_link * sizeof(Elf_(Shdr))) >= shdr_size) {
/* oops. fix out of range pointers */
continue;
}
strtab_section = &bin->shdr[bin->shdr[i].sh_link];
if (strtab_section->sh_size > ST32_MAX || strtab_section->sh_size+8 > bin->size) {
bprintf ("size (syms strtab)");
free (ret);
free (strtab);
return NULL;
}
if (!strtab) {
if (!(strtab = (char *)calloc (1, 8 + strtab_section->sh_size))) {
bprintf ("malloc (syms strtab)");
goto beach;
}
if (strtab_section->sh_offset > bin->size ||
strtab_section->sh_offset + strtab_section->sh_size > bin->size) {
goto beach;
}
if (r_buf_read_at (bin->b, strtab_section->sh_offset,
(ut8*)strtab, strtab_section->sh_size) == -1) {
bprintf ("Warning: read (syms strtab)\n");
goto beach;
}
}
newsize = 1 + bin->shdr[i].sh_size;
if (newsize < 0 || newsize > bin->size) {
bprintf ("invalid shdr %d size\n", i);
goto beach;
}
nsym = (int)(bin->shdr[i].sh_size / sizeof (Elf_(Sym)));
if (nsym < 0) {
goto beach;
}
if (!(sym = (Elf_(Sym) *)calloc (nsym, sizeof (Elf_(Sym))))) {
bprintf ("calloc (syms)");
goto beach;
}
if (!UT32_MUL (&size, nsym, sizeof (Elf_(Sym)))) {
goto beach;
}
if (size < 1 || size > bin->size) {
goto beach;
}
if (bin->shdr[i].sh_offset > bin->size) {
goto beach;
}
if (bin->shdr[i].sh_offset + size > bin->size) {
goto beach;
}
for (j = 0; j < nsym; j++) {
int k = 0;
r = r_buf_read_at (bin->b, bin->shdr[i].sh_offset + j * sizeof (Elf_(Sym)), s, sizeof (Elf_(Sym)));
if (r < 1) {
bprintf ("Warning: read (sym)\n");
goto beach;
}
#if R_BIN_ELF64
sym[j].st_name = READ32 (s, k)
sym[j].st_info = READ8 (s, k)
sym[j].st_other = READ8 (s, k)
sym[j].st_shndx = READ16 (s, k)
sym[j].st_value = READ64 (s, k)
sym[j].st_size = READ64 (s, k)
#else
sym[j].st_name = READ32 (s, k)
sym[j].st_value = READ32 (s, k)
sym[j].st_size = READ32 (s, k)
sym[j].st_info = READ8 (s, k)
sym[j].st_other = READ8 (s, k)
sym[j].st_shndx = READ16 (s, k)
#endif
}
free (ret);
ret = calloc (nsym, sizeof (RBinElfSymbol));
if (!ret) {
bprintf ("Cannot allocate %d symbols\n", nsym);
goto beach;
}
for (k = 1, ret_ctr = 0; k < nsym; k++) {
if (type == R_BIN_ELF_IMPORTS && sym[k].st_shndx == STN_UNDEF) {
if (sym[k].st_value) {
toffset = sym[k].st_value;
} else if ((toffset = get_import_addr (bin, k)) == -1){
toffset = 0;
}
tsize = 16;
} else if (type == R_BIN_ELF_SYMBOLS &&
sym[k].st_shndx != STN_UNDEF &&
ELF_ST_TYPE (sym[k].st_info) != STT_SECTION &&
ELF_ST_TYPE (sym[k].st_info) != STT_FILE) {
//int idx = sym[k].st_shndx;
tsize = sym[k].st_size;
toffset = (ut64)sym[k].st_value;
} else {
continue;
}
if (bin->ehdr.e_type == ET_REL) {
if (sym[k].st_shndx < bin->ehdr.e_shnum)
ret[ret_ctr].offset = sym[k].st_value + bin->shdr[sym[k].st_shndx].sh_offset;
} else {
ret[ret_ctr].offset = Elf_(r_bin_elf_v2p) (bin, toffset);
}
ret[ret_ctr].size = tsize;
if (sym[k].st_name + 2 > strtab_section->sh_size) {
bprintf ("Warning: index out of strtab range\n");
goto beach;
}
{
int rest = ELF_STRING_LENGTH - 1;
int st_name = sym[k].st_name;
int maxsize = R_MIN (bin->b->length, strtab_section->sh_size);
if (st_name < 0 || st_name >= maxsize) {
ret[ret_ctr].name[0] = 0;
} else {
const size_t len = __strnlen (strtab + sym[k].st_name, rest);
memcpy (ret[ret_ctr].name, &strtab[sym[k].st_name], len);
}
}
ret[ret_ctr].ordinal = k;
ret[ret_ctr].name[ELF_STRING_LENGTH - 2] = '\0';
fill_symbol_bind_and_type (&ret[ret_ctr], &sym[k]);
ret[ret_ctr].last = 0;
ret_ctr++;
}
ret[ret_ctr].last = 1; // ugly dirty hack :D
R_FREE (strtab);
R_FREE (sym);
}
}
if (!ret) {
return (type == R_BIN_ELF_SYMBOLS)
? Elf_(r_bin_elf_get_phdr_symbols) (bin)
: Elf_(r_bin_elf_get_phdr_imports) (bin);
}
int max = -1;
RBinElfSymbol *aux = NULL;
nsym = Elf_(fix_symbols) (bin, ret_ctr, type, &ret);
if (nsym == -1) {
goto beach;
}
aux = ret;
while (!aux->last) {
if ((int)aux->ordinal > max) {
max = aux->ordinal;
}
aux++;
}
nsym = max;
if (type == R_BIN_ELF_IMPORTS) {
R_FREE (bin->imports_by_ord);
bin->imports_by_ord_size = nsym + 1;
bin->imports_by_ord = (RBinImport**)calloc (R_MAX (1, nsym + 1), sizeof (RBinImport*));
} else if (type == R_BIN_ELF_SYMBOLS) {
R_FREE (bin->symbols_by_ord);
bin->symbols_by_ord_size = nsym + 1;
bin->symbols_by_ord = (RBinSymbol**)calloc (R_MAX (1, nsym + 1), sizeof (RBinSymbol*));
}
return ret;
beach:
free (ret);
free (sym);
free (strtab);
return NULL;
}
RBinElfSymbol *Elf_(r_bin_elf_get_symbols)(ELFOBJ *bin) {
if (!bin->g_symbols) {
bin->g_symbols = Elf_(_r_bin_elf_get_symbols_imports) (bin, R_BIN_ELF_SYMBOLS);
}
return bin->g_symbols;
}
RBinElfSymbol *Elf_(r_bin_elf_get_imports)(ELFOBJ *bin) {
if (!bin->g_imports) {
bin->g_imports = Elf_(_r_bin_elf_get_symbols_imports) (bin, R_BIN_ELF_IMPORTS);
}
return bin->g_imports;
}
RBinElfField* Elf_(r_bin_elf_get_fields)(ELFOBJ *bin) {
RBinElfField *ret = NULL;
int i = 0, j;
if (!bin || !(ret = calloc ((bin->ehdr.e_phnum + 3 + 1), sizeof (RBinElfField)))) {
return NULL;
}
strncpy (ret[i].name, "ehdr", ELF_STRING_LENGTH);
ret[i].offset = 0;
ret[i++].last = 0;
strncpy (ret[i].name, "shoff", ELF_STRING_LENGTH);
ret[i].offset = bin->ehdr.e_shoff;
ret[i++].last = 0;
strncpy (ret[i].name, "phoff", ELF_STRING_LENGTH);
ret[i].offset = bin->ehdr.e_phoff;
ret[i++].last = 0;
for (j = 0; bin->phdr && j < bin->ehdr.e_phnum; i++, j++) {
snprintf (ret[i].name, ELF_STRING_LENGTH, "phdr_%i", j);
ret[i].offset = bin->phdr[j].p_offset;
ret[i].last = 0;
}
ret[i].last = 1;
return ret;
}
void* Elf_(r_bin_elf_free)(ELFOBJ* bin) {
int i;
if (!bin) {
return NULL;
}
free (bin->phdr);
free (bin->shdr);
free (bin->strtab);
free (bin->dyn_buf);
free (bin->shstrtab);
free (bin->dynstr);
//free (bin->strtab_section);
if (bin->imports_by_ord) {
for (i = 0; i<bin->imports_by_ord_size; i++) {
free (bin->imports_by_ord[i]);
}
free (bin->imports_by_ord);
}
if (bin->symbols_by_ord) {
for (i = 0; i<bin->symbols_by_ord_size; i++) {
free (bin->symbols_by_ord[i]);
}
free (bin->symbols_by_ord);
}
r_buf_free (bin->b);
if (bin->g_symbols != bin->phdr_symbols) {
R_FREE (bin->phdr_symbols);
}
if (bin->g_imports != bin->phdr_imports) {
R_FREE (bin->phdr_imports);
}
R_FREE (bin->g_sections);
R_FREE (bin->g_symbols);
R_FREE (bin->g_imports);
free (bin);
return NULL;
}
ELFOBJ* Elf_(r_bin_elf_new)(const char* file, bool verbose) {
ut8 *buf;
int size;
ELFOBJ *bin = R_NEW0 (ELFOBJ);
if (!bin) {
return NULL;
}
memset (bin, 0, sizeof (ELFOBJ));
bin->file = file;
if (!(buf = (ut8*)r_file_slurp (file, &size))) {
return Elf_(r_bin_elf_free) (bin);
}
bin->size = size;
bin->verbose = verbose;
bin->b = r_buf_new ();
if (!r_buf_set_bytes (bin->b, buf, bin->size)) {
free (buf);
return Elf_(r_bin_elf_free) (bin);
}
if (!elf_init (bin)) {
free (buf);
return Elf_(r_bin_elf_free) (bin);
}
free (buf);
return bin;
}
ELFOBJ* Elf_(r_bin_elf_new_buf)(RBuffer *buf, bool verbose) {
ELFOBJ *bin = R_NEW0 (ELFOBJ);
bin->kv = sdb_new0 ();
bin->b = r_buf_new ();
bin->size = (ut32)buf->length;
bin->verbose = verbose;
if (!r_buf_set_bytes (bin->b, buf->buf, buf->length)) {
return Elf_(r_bin_elf_free) (bin);
}
if (!elf_init (bin)) {
return Elf_(r_bin_elf_free) (bin);
}
return bin;
}
static int is_in_pphdr (Elf_(Phdr) *p, ut64 addr) {
return addr >= p->p_offset && addr < p->p_offset + p->p_memsz;
}
static int is_in_vphdr (Elf_(Phdr) *p, ut64 addr) {
return addr >= p->p_vaddr && addr < p->p_vaddr + p->p_memsz;
}
/* converts a physical address to the virtual address, looking
* at the program headers in the binary bin */
ut64 Elf_(r_bin_elf_p2v) (ELFOBJ *bin, ut64 paddr) {
int i;
if (!bin) return 0;
if (!bin->phdr) {
if (bin->ehdr.e_type == ET_REL) {
return bin->baddr + paddr;
}
return paddr;
}
for (i = 0; i < bin->ehdr.e_phnum; ++i) {
Elf_(Phdr) *p = &bin->phdr[i];
if (!p) {
break;
}
if (p->p_type == PT_LOAD && is_in_pphdr (p, paddr)) {
if (!p->p_vaddr && !p->p_offset) {
continue;
}
return p->p_vaddr + paddr - p->p_offset;
}
}
return paddr;
}
/* converts a virtual address to the relative physical address, looking
* at the program headers in the binary bin */
ut64 Elf_(r_bin_elf_v2p) (ELFOBJ *bin, ut64 vaddr) {
int i;
if (!bin) {
return 0;
}
if (!bin->phdr) {
if (bin->ehdr.e_type == ET_REL) {
return vaddr - bin->baddr;
}
return vaddr;
}
for (i = 0; i < bin->ehdr.e_phnum; ++i) {
Elf_(Phdr) *p = &bin->phdr[i];
if (!p) {
break;
}
if (p->p_type == PT_LOAD && is_in_vphdr (p, vaddr)) {
if (!p->p_offset && !p->p_vaddr) {
continue;
}
return p->p_offset + vaddr - p->p_vaddr;
}
}
return vaddr;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2899_0 |
crossvul-cpp_data_good_2135_0 | /*
* Copyright (c) Ian F. Darwin 1986-1995.
* Software written by Ian F. Darwin and others;
* maintained 1995-present by Christos Zoulas and others.
*
* 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.
*/
/*
* softmagic - interpret variable magic from MAGIC
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: softmagic.c,v 1.190 2014/06/03 19:01:34 christos Exp $")
#endif /* lint */
#include "magic.h"
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>
#if defined(HAVE_LOCALE_H)
#include <locale.h>
#endif
private int match(struct magic_set *, struct magic *, uint32_t,
const unsigned char *, size_t, size_t, int, int, int, int, int *, int *,
int *);
private int mget(struct magic_set *, const unsigned char *,
struct magic *, size_t, size_t, unsigned int, int, int, int, int, int *,
int *, int *);
private int magiccheck(struct magic_set *, struct magic *);
private int32_t mprint(struct magic_set *, struct magic *);
private int32_t moffset(struct magic_set *, struct magic *);
private void mdebug(uint32_t, const char *, size_t);
private int mcopy(struct magic_set *, union VALUETYPE *, int, int,
const unsigned char *, uint32_t, size_t, struct magic *);
private int mconvert(struct magic_set *, struct magic *, int);
private int print_sep(struct magic_set *, int);
private int handle_annotation(struct magic_set *, struct magic *);
private void cvt_8(union VALUETYPE *, const struct magic *);
private void cvt_16(union VALUETYPE *, const struct magic *);
private void cvt_32(union VALUETYPE *, const struct magic *);
private void cvt_64(union VALUETYPE *, const struct magic *);
#define OFFSET_OOB(n, o, i) ((n) < (o) || (i) > ((n) - (o)))
/*
* softmagic - lookup one file in parsed, in-memory copy of database
* Passed the name and FILE * of one file to be typed.
*/
/*ARGSUSED1*/ /* nbytes passed for regularity, maybe need later */
protected int
file_softmagic(struct magic_set *ms, const unsigned char *buf, size_t nbytes,
size_t level, int mode, int text)
{
struct mlist *ml;
int rv, printed_something = 0, need_separator = 0;
for (ml = ms->mlist[0]->next; ml != ms->mlist[0]; ml = ml->next)
if ((rv = match(ms, ml->magic, ml->nmagic, buf, nbytes, 0, mode,
text, 0, level, &printed_something, &need_separator,
NULL)) != 0)
return rv;
return 0;
}
#define FILE_FMTDEBUG
#ifdef FILE_FMTDEBUG
#define F(a, b, c) file_fmtcheck((a), (b), (c), __FILE__, __LINE__)
private const char * __attribute__((__format_arg__(3)))
file_fmtcheck(struct magic_set *ms, const struct magic *m, const char *def,
const char *file, size_t line)
{
const char *ptr = fmtcheck(m->desc, def);
if (ptr == def)
file_magerror(ms,
"%s, %zu: format `%s' does not match with `%s'",
file, line, m->desc, def);
return ptr;
}
#else
#define F(a, b, c) fmtcheck((b)->desc, (c))
#endif
/*
* Go through the whole list, stopping if you find a match. Process all
* the continuations of that match before returning.
*
* We support multi-level continuations:
*
* At any time when processing a successful top-level match, there is a
* current continuation level; it represents the level of the last
* successfully matched continuation.
*
* Continuations above that level are skipped as, if we see one, it
* means that the continuation that controls them - i.e, the
* lower-level continuation preceding them - failed to match.
*
* Continuations below that level are processed as, if we see one,
* it means we've finished processing or skipping higher-level
* continuations under the control of a successful or unsuccessful
* lower-level continuation, and are now seeing the next lower-level
* continuation and should process it. The current continuation
* level reverts to the level of the one we're seeing.
*
* Continuations at the current level are processed as, if we see
* one, there's no lower-level continuation that may have failed.
*
* If a continuation matches, we bump the current continuation level
* so that higher-level continuations are processed.
*/
private int
match(struct magic_set *ms, struct magic *magic, uint32_t nmagic,
const unsigned char *s, size_t nbytes, size_t offset, int mode, int text,
int flip, int recursion_level, int *printed_something, int *need_separator,
int *returnval)
{
uint32_t magindex = 0;
unsigned int cont_level = 0;
int returnvalv = 0, e; /* if a match is found it is set to 1*/
int firstline = 1; /* a flag to print X\n X\n- X */
int print = (ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0;
if (returnval == NULL)
returnval = &returnvalv;
if (file_check_mem(ms, cont_level) == -1)
return -1;
for (magindex = 0; magindex < nmagic; magindex++) {
int flush = 0;
struct magic *m = &magic[magindex];
if (m->type != FILE_NAME)
if ((IS_STRING(m->type) &&
#define FLT (STRING_BINTEST | STRING_TEXTTEST)
((text && (m->str_flags & FLT) == STRING_BINTEST) ||
(!text && (m->str_flags & FLT) == STRING_TEXTTEST))) ||
(m->flag & mode) != mode) {
/* Skip sub-tests */
while (magindex + 1 < nmagic &&
magic[magindex + 1].cont_level != 0 &&
++magindex)
continue;
continue; /* Skip to next top-level test*/
}
ms->offset = m->offset;
ms->line = m->lineno;
/* if main entry matches, print it... */
switch (mget(ms, s, m, nbytes, offset, cont_level, mode, text,
flip, recursion_level + 1, printed_something,
need_separator, returnval)) {
case -1:
return -1;
case 0:
flush = m->reln != '!';
break;
default:
if (m->type == FILE_INDIRECT)
*returnval = 1;
switch (magiccheck(ms, m)) {
case -1:
return -1;
case 0:
flush++;
break;
default:
flush = 0;
break;
}
break;
}
if (flush) {
/*
* main entry didn't match,
* flush its continuations
*/
while (magindex < nmagic - 1 &&
magic[magindex + 1].cont_level != 0)
magindex++;
continue;
}
if ((e = handle_annotation(ms, m)) != 0) {
*need_separator = 1;
*printed_something = 1;
*returnval = 1;
return e;
}
/*
* If we are going to print something, we'll need to print
* a blank before we print something else.
*/
if (*m->desc) {
*need_separator = 1;
*printed_something = 1;
if (print_sep(ms, firstline) == -1)
return -1;
}
if (print && mprint(ms, m) == -1)
return -1;
ms->c.li[cont_level].off = moffset(ms, m);
/* and any continuations that match */
if (file_check_mem(ms, ++cont_level) == -1)
return -1;
while (++magindex < nmagic &&
magic[magindex].cont_level != 0) {
m = &magic[magindex];
ms->line = m->lineno; /* for messages */
if (cont_level < m->cont_level)
continue;
if (cont_level > m->cont_level) {
/*
* We're at the end of the level
* "cont_level" continuations.
*/
cont_level = m->cont_level;
}
ms->offset = m->offset;
if (m->flag & OFFADD) {
ms->offset +=
ms->c.li[cont_level - 1].off;
}
#ifdef ENABLE_CONDITIONALS
if (m->cond == COND_ELSE ||
m->cond == COND_ELIF) {
if (ms->c.li[cont_level].last_match == 1)
continue;
}
#endif
switch (mget(ms, s, m, nbytes, offset, cont_level, mode,
text, flip, recursion_level + 1, printed_something,
need_separator, returnval)) {
case -1:
return -1;
case 0:
if (m->reln != '!')
continue;
flush = 1;
break;
default:
if (m->type == FILE_INDIRECT)
*returnval = 1;
flush = 0;
break;
}
switch (flush ? 1 : magiccheck(ms, m)) {
case -1:
return -1;
case 0:
#ifdef ENABLE_CONDITIONALS
ms->c.li[cont_level].last_match = 0;
#endif
break;
default:
#ifdef ENABLE_CONDITIONALS
ms->c.li[cont_level].last_match = 1;
#endif
if (m->type == FILE_CLEAR)
ms->c.li[cont_level].got_match = 0;
else if (ms->c.li[cont_level].got_match) {
if (m->type == FILE_DEFAULT)
break;
} else
ms->c.li[cont_level].got_match = 1;
if ((e = handle_annotation(ms, m)) != 0) {
*need_separator = 1;
*printed_something = 1;
*returnval = 1;
return e;
}
/*
* If we are going to print something,
* make sure that we have a separator first.
*/
if (*m->desc) {
if (!*printed_something) {
*printed_something = 1;
if (print_sep(ms, firstline)
== -1)
return -1;
}
}
/*
* This continuation matched. Print
* its message, with a blank before it
* if the previous item printed and
* this item isn't empty.
*/
/* space if previous printed */
if (*need_separator
&& ((m->flag & NOSPACE) == 0)
&& *m->desc) {
if (print &&
file_printf(ms, " ") == -1)
return -1;
*need_separator = 0;
}
if (print && mprint(ms, m) == -1)
return -1;
ms->c.li[cont_level].off = moffset(ms, m);
if (*m->desc)
*need_separator = 1;
/*
* If we see any continuations
* at a higher level,
* process them.
*/
if (file_check_mem(ms, ++cont_level) == -1)
return -1;
break;
}
}
if (*printed_something) {
firstline = 0;
if (print)
*returnval = 1;
}
if ((ms->flags & MAGIC_CONTINUE) == 0 && *printed_something) {
return *returnval; /* don't keep searching */
}
}
return *returnval; /* This is hit if -k is set or there is no match */
}
private int
check_fmt(struct magic_set *ms, struct magic *m)
{
file_regex_t rx;
int rc, rv = -1;
if (strchr(m->desc, '%') == NULL)
return 0;
rc = file_regcomp(&rx, "%[-0-9\\.]*s", REG_EXTENDED|REG_NOSUB);
if (rc) {
file_regerror(&rx, rc, ms);
} else {
rc = file_regexec(&rx, m->desc, 0, 0, 0);
rv = !rc;
}
file_regfree(&rx);
return rv;
}
#ifndef HAVE_STRNDUP
char * strndup(const char *, size_t);
char *
strndup(const char *str, size_t n)
{
size_t len;
char *copy;
for (len = 0; len < n && str[len]; len++)
continue;
if ((copy = malloc(len + 1)) == NULL)
return NULL;
(void)memcpy(copy, str, len);
copy[len] = '\0';
return copy;
}
#endif /* HAVE_STRNDUP */
private int32_t
mprint(struct magic_set *ms, struct magic *m)
{
uint64_t v;
float vf;
double vd;
int64_t t = 0;
char buf[128], tbuf[26];
union VALUETYPE *p = &ms->ms_value;
switch (m->type) {
case FILE_BYTE:
v = file_signextend(ms, m, (uint64_t)p->b);
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%d",
(unsigned char)v);
if (file_printf(ms, F(ms, m, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, m, "%d"),
(unsigned char) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(char);
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
v = file_signextend(ms, m, (uint64_t)p->h);
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%u",
(unsigned short)v);
if (file_printf(ms, F(ms, m, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, m, "%u"),
(unsigned short) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(short);
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
v = file_signextend(ms, m, (uint64_t)p->l);
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%u", (uint32_t) v);
if (file_printf(ms, F(ms, m, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, m, "%u"), (uint32_t) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(int32_t);
break;
case FILE_QUAD:
case FILE_BEQUAD:
case FILE_LEQUAD:
v = file_signextend(ms, m, p->q);
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%" INT64_T_FORMAT "u",
(unsigned long long)v);
if (file_printf(ms, F(ms, m, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, m, "%" INT64_T_FORMAT "u"),
(unsigned long long) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(int64_t);
break;
case FILE_STRING:
case FILE_PSTRING:
case FILE_BESTRING16:
case FILE_LESTRING16:
if (m->reln == '=' || m->reln == '!') {
if (file_printf(ms, F(ms, m, "%s"), m->value.s) == -1)
return -1;
t = ms->offset + m->vallen;
}
else {
char *str = p->s;
/* compute t before we mangle the string? */
t = ms->offset + strlen(str);
if (*m->value.s == '\0')
str[strcspn(str, "\n")] = '\0';
if (m->str_flags & STRING_TRIM) {
char *last;
while (isspace((unsigned char)*str))
str++;
last = str;
while (*last)
last++;
--last;
while (isspace((unsigned char)*last))
last--;
*++last = '\0';
}
if (file_printf(ms, F(ms, m, "%s"), str) == -1)
return -1;
if (m->type == FILE_PSTRING)
t += file_pstring_length_size(m);
}
break;
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
if (file_printf(ms, F(ms, m, "%s"),
file_fmttime(p->l + m->num_mask, FILE_T_LOCAL, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint32_t);
break;
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
if (file_printf(ms, F(ms, m, "%s"),
file_fmttime(p->l + m->num_mask, 0, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint32_t);
break;
case FILE_QDATE:
case FILE_BEQDATE:
case FILE_LEQDATE:
if (file_printf(ms, F(ms, m, "%s"),
file_fmttime(p->q + m->num_mask, FILE_T_LOCAL, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint64_t);
break;
case FILE_QLDATE:
case FILE_BEQLDATE:
case FILE_LEQLDATE:
if (file_printf(ms, F(ms, m, "%s"),
file_fmttime(p->q + m->num_mask, 0, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint64_t);
break;
case FILE_QWDATE:
case FILE_BEQWDATE:
case FILE_LEQWDATE:
if (file_printf(ms, F(ms, m, "%s"),
file_fmttime(p->q + m->num_mask, FILE_T_WINDOWS, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint64_t);
break;
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
vf = p->f;
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%g", vf);
if (file_printf(ms, F(ms, m, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, m, "%g"), vf) == -1)
return -1;
break;
}
t = ms->offset + sizeof(float);
break;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
vd = p->d;
switch (check_fmt(ms, m)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%g", vd);
if (file_printf(ms, F(ms, m, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, m, "%g"), vd) == -1)
return -1;
break;
}
t = ms->offset + sizeof(double);
break;
case FILE_REGEX: {
char *cp;
int rval;
cp = strndup((const char *)ms->search.s, ms->search.rm_len);
if (cp == NULL) {
file_oomem(ms, ms->search.rm_len);
return -1;
}
rval = file_printf(ms, F(ms, m, "%s"), cp);
free(cp);
if (rval == -1)
return -1;
if ((m->str_flags & REGEX_OFFSET_START))
t = ms->search.offset;
else
t = ms->search.offset + ms->search.rm_len;
break;
}
case FILE_SEARCH:
if (file_printf(ms, F(ms, m, "%s"), m->value.s) == -1)
return -1;
if ((m->str_flags & REGEX_OFFSET_START))
t = ms->search.offset;
else
t = ms->search.offset + m->vallen;
break;
case FILE_DEFAULT:
case FILE_CLEAR:
if (file_printf(ms, "%s", m->desc) == -1)
return -1;
t = ms->offset;
break;
case FILE_INDIRECT:
case FILE_USE:
case FILE_NAME:
t = ms->offset;
break;
default:
file_magerror(ms, "invalid m->type (%d) in mprint()", m->type);
return -1;
}
return (int32_t)t;
}
private int32_t
moffset(struct magic_set *ms, struct magic *m)
{
switch (m->type) {
case FILE_BYTE:
return CAST(int32_t, (ms->offset + sizeof(char)));
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
return CAST(int32_t, (ms->offset + sizeof(short)));
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
return CAST(int32_t, (ms->offset + sizeof(int32_t)));
case FILE_QUAD:
case FILE_BEQUAD:
case FILE_LEQUAD:
return CAST(int32_t, (ms->offset + sizeof(int64_t)));
case FILE_STRING:
case FILE_PSTRING:
case FILE_BESTRING16:
case FILE_LESTRING16:
if (m->reln == '=' || m->reln == '!')
return ms->offset + m->vallen;
else {
union VALUETYPE *p = &ms->ms_value;
uint32_t t;
if (*m->value.s == '\0')
p->s[strcspn(p->s, "\n")] = '\0';
t = CAST(uint32_t, (ms->offset + strlen(p->s)));
if (m->type == FILE_PSTRING)
t += (uint32_t)file_pstring_length_size(m);
return t;
}
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
return CAST(int32_t, (ms->offset + sizeof(uint32_t)));
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
return CAST(int32_t, (ms->offset + sizeof(uint32_t)));
case FILE_QDATE:
case FILE_BEQDATE:
case FILE_LEQDATE:
return CAST(int32_t, (ms->offset + sizeof(uint64_t)));
case FILE_QLDATE:
case FILE_BEQLDATE:
case FILE_LEQLDATE:
return CAST(int32_t, (ms->offset + sizeof(uint64_t)));
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
return CAST(int32_t, (ms->offset + sizeof(float)));
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
return CAST(int32_t, (ms->offset + sizeof(double)));
case FILE_REGEX:
if ((m->str_flags & REGEX_OFFSET_START) != 0)
return CAST(int32_t, ms->search.offset);
else
return CAST(int32_t, (ms->search.offset +
ms->search.rm_len));
case FILE_SEARCH:
if ((m->str_flags & REGEX_OFFSET_START) != 0)
return CAST(int32_t, ms->search.offset);
else
return CAST(int32_t, (ms->search.offset + m->vallen));
case FILE_CLEAR:
case FILE_DEFAULT:
case FILE_INDIRECT:
return ms->offset;
default:
return 0;
}
}
private int
cvt_flip(int type, int flip)
{
if (flip == 0)
return type;
switch (type) {
case FILE_BESHORT:
return FILE_LESHORT;
case FILE_BELONG:
return FILE_LELONG;
case FILE_BEDATE:
return FILE_LEDATE;
case FILE_BELDATE:
return FILE_LELDATE;
case FILE_BEQUAD:
return FILE_LEQUAD;
case FILE_BEQDATE:
return FILE_LEQDATE;
case FILE_BEQLDATE:
return FILE_LEQLDATE;
case FILE_BEQWDATE:
return FILE_LEQWDATE;
case FILE_LESHORT:
return FILE_BESHORT;
case FILE_LELONG:
return FILE_BELONG;
case FILE_LEDATE:
return FILE_BEDATE;
case FILE_LELDATE:
return FILE_BELDATE;
case FILE_LEQUAD:
return FILE_BEQUAD;
case FILE_LEQDATE:
return FILE_BEQDATE;
case FILE_LEQLDATE:
return FILE_BEQLDATE;
case FILE_LEQWDATE:
return FILE_BEQWDATE;
case FILE_BEFLOAT:
return FILE_LEFLOAT;
case FILE_LEFLOAT:
return FILE_BEFLOAT;
case FILE_BEDOUBLE:
return FILE_LEDOUBLE;
case FILE_LEDOUBLE:
return FILE_BEDOUBLE;
default:
return type;
}
}
#define DO_CVT(fld, cast) \
if (m->num_mask) \
switch (m->mask_op & FILE_OPS_MASK) { \
case FILE_OPAND: \
p->fld &= cast m->num_mask; \
break; \
case FILE_OPOR: \
p->fld |= cast m->num_mask; \
break; \
case FILE_OPXOR: \
p->fld ^= cast m->num_mask; \
break; \
case FILE_OPADD: \
p->fld += cast m->num_mask; \
break; \
case FILE_OPMINUS: \
p->fld -= cast m->num_mask; \
break; \
case FILE_OPMULTIPLY: \
p->fld *= cast m->num_mask; \
break; \
case FILE_OPDIVIDE: \
p->fld /= cast m->num_mask; \
break; \
case FILE_OPMODULO: \
p->fld %= cast m->num_mask; \
break; \
} \
if (m->mask_op & FILE_OPINVERSE) \
p->fld = ~p->fld \
private void
cvt_8(union VALUETYPE *p, const struct magic *m)
{
DO_CVT(b, (uint8_t));
}
private void
cvt_16(union VALUETYPE *p, const struct magic *m)
{
DO_CVT(h, (uint16_t));
}
private void
cvt_32(union VALUETYPE *p, const struct magic *m)
{
DO_CVT(l, (uint32_t));
}
private void
cvt_64(union VALUETYPE *p, const struct magic *m)
{
DO_CVT(q, (uint64_t));
}
#define DO_CVT2(fld, cast) \
if (m->num_mask) \
switch (m->mask_op & FILE_OPS_MASK) { \
case FILE_OPADD: \
p->fld += cast m->num_mask; \
break; \
case FILE_OPMINUS: \
p->fld -= cast m->num_mask; \
break; \
case FILE_OPMULTIPLY: \
p->fld *= cast m->num_mask; \
break; \
case FILE_OPDIVIDE: \
p->fld /= cast m->num_mask; \
break; \
} \
private void
cvt_float(union VALUETYPE *p, const struct magic *m)
{
DO_CVT2(f, (float));
}
private void
cvt_double(union VALUETYPE *p, const struct magic *m)
{
DO_CVT2(d, (double));
}
/*
* Convert the byte order of the data we are looking at
* While we're here, let's apply the mask operation
* (unless you have a better idea)
*/
private int
mconvert(struct magic_set *ms, struct magic *m, int flip)
{
union VALUETYPE *p = &ms->ms_value;
uint8_t type;
switch (type = cvt_flip(m->type, flip)) {
case FILE_BYTE:
cvt_8(p, m);
return 1;
case FILE_SHORT:
cvt_16(p, m);
return 1;
case FILE_LONG:
case FILE_DATE:
case FILE_LDATE:
cvt_32(p, m);
return 1;
case FILE_QUAD:
case FILE_QDATE:
case FILE_QLDATE:
case FILE_QWDATE:
cvt_64(p, m);
return 1;
case FILE_STRING:
case FILE_BESTRING16:
case FILE_LESTRING16: {
/* Null terminate and eat *trailing* return */
p->s[sizeof(p->s) - 1] = '\0';
return 1;
}
case FILE_PSTRING: {
size_t sz = file_pstring_length_size(m);
char *ptr1 = p->s, *ptr2 = ptr1 + sz;
size_t len = file_pstring_get_length(m, ptr1);
if (len >= sizeof(p->s)) {
/*
* The size of the pascal string length (sz)
* is 1, 2, or 4. We need at least 1 byte for NUL
* termination, but we've already truncated the
* string by p->s, so we need to deduct sz.
*/
len = sizeof(p->s) - sz;
}
while (len--)
*ptr1++ = *ptr2++;
*ptr1 = '\0';
return 1;
}
case FILE_BESHORT:
p->h = (short)((p->hs[0]<<8)|(p->hs[1]));
cvt_16(p, m);
return 1;
case FILE_BELONG:
case FILE_BEDATE:
case FILE_BELDATE:
p->l = (int32_t)
((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3]));
if (type == FILE_BELONG)
cvt_32(p, m);
return 1;
case FILE_BEQUAD:
case FILE_BEQDATE:
case FILE_BEQLDATE:
case FILE_BEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7]));
if (type == FILE_BEQUAD)
cvt_64(p, m);
return 1;
case FILE_LESHORT:
p->h = (short)((p->hs[1]<<8)|(p->hs[0]));
cvt_16(p, m);
return 1;
case FILE_LELONG:
case FILE_LEDATE:
case FILE_LELDATE:
p->l = (int32_t)
((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0]));
if (type == FILE_LELONG)
cvt_32(p, m);
return 1;
case FILE_LEQUAD:
case FILE_LEQDATE:
case FILE_LEQLDATE:
case FILE_LEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0]));
if (type == FILE_LEQUAD)
cvt_64(p, m);
return 1;
case FILE_MELONG:
case FILE_MEDATE:
case FILE_MELDATE:
p->l = (int32_t)
((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2]));
if (type == FILE_MELONG)
cvt_32(p, m);
return 1;
case FILE_FLOAT:
cvt_float(p, m);
return 1;
case FILE_BEFLOAT:
p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)|
((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]);
cvt_float(p, m);
return 1;
case FILE_LEFLOAT:
p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)|
((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]);
cvt_float(p, m);
return 1;
case FILE_DOUBLE:
cvt_double(p, m);
return 1;
case FILE_BEDOUBLE:
p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]);
cvt_double(p, m);
return 1;
case FILE_LEDOUBLE:
p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]);
cvt_double(p, m);
return 1;
case FILE_REGEX:
case FILE_SEARCH:
case FILE_DEFAULT:
case FILE_CLEAR:
case FILE_NAME:
case FILE_USE:
return 1;
default:
file_magerror(ms, "invalid type %d in mconvert()", m->type);
return 0;
}
}
private void
mdebug(uint32_t offset, const char *str, size_t len)
{
(void) fprintf(stderr, "mget/%zu @%d: ", len, offset);
file_showstr(stderr, str, len);
(void) fputc('\n', stderr);
(void) fputc('\n', stderr);
}
private int
mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir,
const unsigned char *s, uint32_t offset, size_t nbytes, struct magic *m)
{
/*
* Note: FILE_SEARCH and FILE_REGEX do not actually copy
* anything, but setup pointers into the source
*/
if (indir == 0) {
switch (type) {
case FILE_SEARCH:
ms->search.s = RCAST(const char *, s) + offset;
ms->search.s_len = nbytes - offset;
ms->search.offset = offset;
return 0;
case FILE_REGEX: {
const char *b;
const char *c;
const char *last; /* end of search region */
const char *buf; /* start of search region */
const char *end;
size_t lines, linecnt, bytecnt;
if (s == NULL) {
ms->search.s_len = 0;
ms->search.s = NULL;
return 0;
}
if (m->str_flags & REGEX_LINE_COUNT) {
linecnt = m->str_range;
bytecnt = linecnt * 80;
} else {
linecnt = 0;
bytecnt = m->str_range;
}
if (bytecnt == 0)
bytecnt = 8192;
if (bytecnt > nbytes)
bytecnt = nbytes;
buf = RCAST(const char *, s) + offset;
end = last = RCAST(const char *, s) + bytecnt;
/* mget() guarantees buf <= last */
for (lines = linecnt, b = buf; lines && b < end &&
((b = CAST(const char *,
memchr(c = b, '\n', CAST(size_t, (end - b)))))
|| (b = CAST(const char *,
memchr(c, '\r', CAST(size_t, (end - c))))));
lines--, b++) {
last = b;
if (b[0] == '\r' && b[1] == '\n')
b++;
}
if (lines)
last = RCAST(const char *, s) + bytecnt;
ms->search.s = buf;
ms->search.s_len = last - buf;
ms->search.offset = offset;
ms->search.rm_len = 0;
return 0;
}
case FILE_BESTRING16:
case FILE_LESTRING16: {
const unsigned char *src = s + offset;
const unsigned char *esrc = s + nbytes;
char *dst = p->s;
char *edst = &p->s[sizeof(p->s) - 1];
if (type == FILE_BESTRING16)
src++;
/* check that offset is within range */
if (offset >= nbytes)
break;
for (/*EMPTY*/; src < esrc; src += 2, dst++) {
if (dst < edst)
*dst = *src;
else
break;
if (*dst == '\0') {
if (type == FILE_BESTRING16 ?
*(src - 1) != '\0' :
*(src + 1) != '\0')
*dst = ' ';
}
}
*edst = '\0';
return 0;
}
case FILE_STRING: /* XXX - these two should not need */
case FILE_PSTRING: /* to copy anything, but do anyway. */
default:
break;
}
}
if (offset >= nbytes) {
(void)memset(p, '\0', sizeof(*p));
return 0;
}
if (nbytes - offset < sizeof(*p))
nbytes = nbytes - offset;
else
nbytes = sizeof(*p);
(void)memcpy(p, s + offset, nbytes);
/*
* the usefulness of padding with zeroes eludes me, it
* might even cause problems
*/
if (nbytes < sizeof(*p))
(void)memset(((char *)(void *)p) + nbytes, '\0',
sizeof(*p) - nbytes);
return 0;
}
private int
mget(struct magic_set *ms, const unsigned char *s, struct magic *m,
size_t nbytes, size_t o, unsigned int cont_level, int mode, int text,
int flip, int recursion_level, int *printed_something,
int *need_separator, int *returnval)
{
uint32_t soffset, offset = ms->offset;
uint32_t lhs;
int rv, oneed_separator, in_type;
char *sbuf, *rbuf;
union VALUETYPE *p = &ms->ms_value;
struct mlist ml;
if (recursion_level >= 20) {
file_error(ms, 0, "recursion nesting exceeded");
return -1;
}
if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o),
(uint32_t)nbytes, m) == -1)
return -1;
if ((ms->flags & MAGIC_DEBUG) != 0) {
fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%zu, "
"nbytes=%zu)\n", m->type, m->flag, offset, o, nbytes);
mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE));
#ifndef COMPILE_ONLY
file_mdump(m);
#endif
}
if (m->flag & INDIR) {
int off = m->in_offset;
if (m->in_op & FILE_OPINDIRECT) {
const union VALUETYPE *q = CAST(const union VALUETYPE *,
((const void *)(s + offset + off)));
switch (cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
off = q->b;
break;
case FILE_SHORT:
off = q->h;
break;
case FILE_BESHORT:
off = (short)((q->hs[0]<<8)|(q->hs[1]));
break;
case FILE_LESHORT:
off = (short)((q->hs[1]<<8)|(q->hs[0]));
break;
case FILE_LONG:
off = q->l;
break;
case FILE_BELONG:
case FILE_BEID3:
off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)|
(q->hl[2]<<8)|(q->hl[3]));
break;
case FILE_LEID3:
case FILE_LELONG:
off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)|
(q->hl[1]<<8)|(q->hl[0]));
break;
case FILE_MELONG:
off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)|
(q->hl[3]<<8)|(q->hl[2]));
break;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect offs=%u\n", off);
}
switch (in_type = cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
if (OFFSET_OOB(nbytes, offset, 1))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->b & off;
break;
case FILE_OPOR:
offset = p->b | off;
break;
case FILE_OPXOR:
offset = p->b ^ off;
break;
case FILE_OPADD:
offset = p->b + off;
break;
case FILE_OPMINUS:
offset = p->b - off;
break;
case FILE_OPMULTIPLY:
offset = p->b * off;
break;
case FILE_OPDIVIDE:
offset = p->b / off;
break;
case FILE_OPMODULO:
offset = p->b % off;
break;
}
} else
offset = p->b;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
lhs = (p->hs[0] << 8) | p->hs[1];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
lhs = (p->hs[1] << 8) | p->hs[0];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_SHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->h & off;
break;
case FILE_OPOR:
offset = p->h | off;
break;
case FILE_OPXOR:
offset = p->h ^ off;
break;
case FILE_OPADD:
offset = p->h + off;
break;
case FILE_OPMINUS:
offset = p->h - off;
break;
case FILE_OPMULTIPLY:
offset = p->h * off;
break;
case FILE_OPDIVIDE:
offset = p->h / off;
break;
case FILE_OPMODULO:
offset = p->h % off;
break;
}
}
else
offset = p->h;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BELONG:
case FILE_BEID3:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
lhs = (p->hl[0] << 24) | (p->hl[1] << 16) |
(p->hl[2] << 8) | p->hl[3];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LELONG:
case FILE_LEID3:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
lhs = (p->hl[3] << 24) | (p->hl[2] << 16) |
(p->hl[1] << 8) | p->hl[0];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_MELONG:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
lhs = (p->hl[1] << 24) | (p->hl[0] << 16) |
(p->hl[3] << 8) | p->hl[2];
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = lhs & off;
break;
case FILE_OPOR:
offset = lhs | off;
break;
case FILE_OPXOR:
offset = lhs ^ off;
break;
case FILE_OPADD:
offset = lhs + off;
break;
case FILE_OPMINUS:
offset = lhs - off;
break;
case FILE_OPMULTIPLY:
offset = lhs * off;
break;
case FILE_OPDIVIDE:
offset = lhs / off;
break;
case FILE_OPMODULO:
offset = lhs % off;
break;
}
} else
offset = lhs;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LONG:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->l & off;
break;
case FILE_OPOR:
offset = p->l | off;
break;
case FILE_OPXOR:
offset = p->l ^ off;
break;
case FILE_OPADD:
offset = p->l + off;
break;
case FILE_OPMINUS:
offset = p->l - off;
break;
case FILE_OPMULTIPLY:
offset = p->l * off;
break;
case FILE_OPDIVIDE:
offset = p->l / off;
break;
case FILE_OPMODULO:
offset = p->l % off;
break;
}
} else
offset = p->l;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
default:
break;
}
switch (in_type) {
case FILE_LEID3:
case FILE_BEID3:
offset = ((((offset >> 0) & 0x7f) << 0) |
(((offset >> 8) & 0x7f) << 7) |
(((offset >> 16) & 0x7f) << 14) |
(((offset >> 24) & 0x7f) << 21)) + 10;
break;
default:
break;
}
if (m->flag & INDIROFFADD) {
offset += ms->c.li[cont_level-1].off;
if (offset == 0) {
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr,
"indirect *zero* offset\n");
return 0;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect +offs=%u\n", offset);
}
if (mcopy(ms, p, m->type, 0, s, offset, nbytes, m) == -1)
return -1;
ms->offset = offset;
if ((ms->flags & MAGIC_DEBUG) != 0) {
mdebug(offset, (char *)(void *)p,
sizeof(union VALUETYPE));
#ifndef COMPILE_ONLY
file_mdump(m);
#endif
}
}
/* Verify we have enough data to match magic type */
switch (m->type) {
case FILE_BYTE:
if (OFFSET_OOB(nbytes, offset, 1))
return 0;
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
break;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
if (OFFSET_OOB(nbytes, offset, 8))
return 0;
break;
case FILE_STRING:
case FILE_PSTRING:
case FILE_SEARCH:
if (OFFSET_OOB(nbytes, offset, m->vallen))
return 0;
break;
case FILE_REGEX:
if (nbytes < offset)
return 0;
break;
case FILE_INDIRECT:
if (offset == 0)
return 0;
if (nbytes < offset)
return 0;
sbuf = ms->o.buf;
soffset = ms->offset;
ms->o.buf = NULL;
ms->offset = 0;
rv = file_softmagic(ms, s + offset, nbytes - offset,
recursion_level, BINTEST, text);
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv);
rbuf = ms->o.buf;
ms->o.buf = sbuf;
ms->offset = soffset;
if (rv == 1) {
if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 &&
file_printf(ms, F(ms, m, "%u"), offset) == -1) {
free(rbuf);
return -1;
}
if (file_printf(ms, "%s", rbuf) == -1) {
free(rbuf);
return -1;
}
}
free(rbuf);
return rv;
case FILE_USE:
if (nbytes < offset)
return 0;
sbuf = m->value.s;
if (*sbuf == '^') {
sbuf++;
flip = !flip;
}
if (file_magicfind(ms, sbuf, &ml) == -1) {
file_error(ms, 0, "cannot find entry `%s'", sbuf);
return -1;
}
oneed_separator = *need_separator;
if (m->flag & NOSPACE)
*need_separator = 0;
rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o,
mode, text, flip, recursion_level, printed_something,
need_separator, returnval);
if (rv != 1)
*need_separator = oneed_separator;
return rv;
case FILE_NAME:
if (file_printf(ms, "%s", m->desc) == -1)
return -1;
return 1;
case FILE_DEFAULT: /* nothing to check */
case FILE_CLEAR:
default:
break;
}
if (!mconvert(ms, m, flip))
return 0;
return 1;
}
private uint64_t
file_strncmp(const char *s1, const char *s2, size_t len, uint32_t flags)
{
/*
* Convert the source args to unsigned here so that (1) the
* compare will be unsigned as it is in strncmp() and (2) so
* the ctype functions will work correctly without extra
* casting.
*/
const unsigned char *a = (const unsigned char *)s1;
const unsigned char *b = (const unsigned char *)s2;
uint64_t v;
/*
* What we want here is v = strncmp(s1, s2, len),
* but ignoring any nulls.
*/
v = 0;
if (0L == flags) { /* normal string: do it fast */
while (len-- > 0)
if ((v = *b++ - *a++) != '\0')
break;
}
else { /* combine the others */
while (len-- > 0) {
if ((flags & STRING_IGNORE_LOWERCASE) &&
islower(*a)) {
if ((v = tolower(*b++) - *a++) != '\0')
break;
}
else if ((flags & STRING_IGNORE_UPPERCASE) &&
isupper(*a)) {
if ((v = toupper(*b++) - *a++) != '\0')
break;
}
else if ((flags & STRING_COMPACT_WHITESPACE) &&
isspace(*a)) {
a++;
if (isspace(*b++)) {
if (!isspace(*a))
while (isspace(*b))
b++;
}
else {
v = 1;
break;
}
}
else if ((flags & STRING_COMPACT_OPTIONAL_WHITESPACE) &&
isspace(*a)) {
a++;
while (isspace(*b))
b++;
}
else {
if ((v = *b++ - *a++) != '\0')
break;
}
}
}
return v;
}
private uint64_t
file_strncmp16(const char *a, const char *b, size_t len, uint32_t flags)
{
/*
* XXX - The 16-bit string compare probably needs to be done
* differently, especially if the flags are to be supported.
* At the moment, I am unsure.
*/
flags = 0;
return file_strncmp(a, b, len, flags);
}
private int
magiccheck(struct magic_set *ms, struct magic *m)
{
uint64_t l = m->value.q;
uint64_t v;
float fl, fv;
double dl, dv;
int matched;
union VALUETYPE *p = &ms->ms_value;
switch (m->type) {
case FILE_BYTE:
v = p->b;
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
v = p->h;
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
v = p->l;
break;
case FILE_QUAD:
case FILE_LEQUAD:
case FILE_BEQUAD:
case FILE_QDATE:
case FILE_BEQDATE:
case FILE_LEQDATE:
case FILE_QLDATE:
case FILE_BEQLDATE:
case FILE_LEQLDATE:
case FILE_QWDATE:
case FILE_BEQWDATE:
case FILE_LEQWDATE:
v = p->q;
break;
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
fl = m->value.f;
fv = p->f;
switch (m->reln) {
case 'x':
matched = 1;
break;
case '!':
matched = fv != fl;
break;
case '=':
matched = fv == fl;
break;
case '>':
matched = fv > fl;
break;
case '<':
matched = fv < fl;
break;
default:
file_magerror(ms, "cannot happen with float: invalid relation `%c'",
m->reln);
return -1;
}
return matched;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
dl = m->value.d;
dv = p->d;
switch (m->reln) {
case 'x':
matched = 1;
break;
case '!':
matched = dv != dl;
break;
case '=':
matched = dv == dl;
break;
case '>':
matched = dv > dl;
break;
case '<':
matched = dv < dl;
break;
default:
file_magerror(ms, "cannot happen with double: invalid relation `%c'", m->reln);
return -1;
}
return matched;
case FILE_DEFAULT:
case FILE_CLEAR:
l = 0;
v = 0;
break;
case FILE_STRING:
case FILE_PSTRING:
l = 0;
v = file_strncmp(m->value.s, p->s, (size_t)m->vallen, m->str_flags);
break;
case FILE_BESTRING16:
case FILE_LESTRING16:
l = 0;
v = file_strncmp16(m->value.s, p->s, (size_t)m->vallen, m->str_flags);
break;
case FILE_SEARCH: { /* search ms->search.s for the string m->value.s */
size_t slen;
size_t idx;
if (ms->search.s == NULL)
return 0;
slen = MIN(m->vallen, sizeof(m->value.s));
l = 0;
v = 0;
for (idx = 0; m->str_range == 0 || idx < m->str_range; idx++) {
if (slen + idx > ms->search.s_len)
break;
v = file_strncmp(m->value.s, ms->search.s + idx, slen,
m->str_flags);
if (v == 0) { /* found match */
ms->search.offset += idx;
break;
}
}
break;
}
case FILE_REGEX: {
int rc;
file_regex_t rx;
if (ms->search.s == NULL)
return 0;
l = 0;
rc = file_regcomp(&rx, m->value.s,
REG_EXTENDED|REG_NEWLINE|
((m->str_flags & STRING_IGNORE_CASE) ? REG_ICASE : 0));
if (rc) {
file_regerror(&rx, rc, ms);
v = (uint64_t)-1;
} else {
regmatch_t pmatch[1];
size_t slen = ms->search.s_len;
#ifndef REG_STARTEND
#define REG_STARTEND 0
char c;
if (slen != 0)
slen--;
c = ms->search.s[slen];
((char *)(intptr_t)ms->search.s)[slen] = '\0';
#else
pmatch[0].rm_so = 0;
pmatch[0].rm_eo = slen;
#endif
rc = file_regexec(&rx, (const char *)ms->search.s,
1, pmatch, REG_STARTEND);
#if REG_STARTEND == 0
((char *)(intptr_t)ms->search.s)[l] = c;
#endif
switch (rc) {
case 0:
ms->search.s += (int)pmatch[0].rm_so;
ms->search.offset += (size_t)pmatch[0].rm_so;
ms->search.rm_len =
(size_t)(pmatch[0].rm_eo - pmatch[0].rm_so);
v = 0;
break;
case REG_NOMATCH:
v = 1;
break;
default:
file_regerror(&rx, rc, ms);
v = (uint64_t)-1;
break;
}
}
file_regfree(&rx);
if (v == (uint64_t)-1)
return -1;
break;
}
case FILE_INDIRECT:
case FILE_USE:
case FILE_NAME:
return 1;
default:
file_magerror(ms, "invalid type %d in magiccheck()", m->type);
return -1;
}
v = file_signextend(ms, m, v);
switch (m->reln) {
case 'x':
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u == *any* = 1\n", (unsigned long long)v);
matched = 1;
break;
case '!':
matched = v != l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT "u != %"
INT64_T_FORMAT "u = %d\n", (unsigned long long)v,
(unsigned long long)l, matched);
break;
case '=':
matched = v == l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT "u == %"
INT64_T_FORMAT "u = %d\n", (unsigned long long)v,
(unsigned long long)l, matched);
break;
case '>':
if (m->flag & UNSIGNED) {
matched = v > l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u > %" INT64_T_FORMAT "u = %d\n",
(unsigned long long)v,
(unsigned long long)l, matched);
}
else {
matched = (int64_t) v > (int64_t) l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"d > %" INT64_T_FORMAT "d = %d\n",
(long long)v, (long long)l, matched);
}
break;
case '<':
if (m->flag & UNSIGNED) {
matched = v < l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"u < %" INT64_T_FORMAT "u = %d\n",
(unsigned long long)v,
(unsigned long long)l, matched);
}
else {
matched = (int64_t) v < (int64_t) l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "%" INT64_T_FORMAT
"d < %" INT64_T_FORMAT "d = %d\n",
(long long)v, (long long)l, matched);
}
break;
case '&':
matched = (v & l) == l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %"
INT64_T_FORMAT "x) == %" INT64_T_FORMAT
"x) = %d\n", (unsigned long long)v,
(unsigned long long)l, (unsigned long long)l,
matched);
break;
case '^':
matched = (v & l) != l;
if ((ms->flags & MAGIC_DEBUG) != 0)
(void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %"
INT64_T_FORMAT "x) != %" INT64_T_FORMAT
"x) = %d\n", (unsigned long long)v,
(unsigned long long)l, (unsigned long long)l,
matched);
break;
default:
file_magerror(ms, "cannot happen: invalid relation `%c'",
m->reln);
return -1;
}
return matched;
}
private int
handle_annotation(struct magic_set *ms, struct magic *m)
{
if (ms->flags & MAGIC_APPLE) {
if (file_printf(ms, "%.8s", m->apple) == -1)
return -1;
return 1;
}
if ((ms->flags & MAGIC_MIME_TYPE) && m->mimetype[0]) {
if (file_printf(ms, "%s", m->mimetype) == -1)
return -1;
return 1;
}
return 0;
}
private int
print_sep(struct magic_set *ms, int firstline)
{
if (ms->flags & MAGIC_MIME)
return 0;
if (firstline)
return 0;
/*
* we found another match
* put a newline and '-' to do some simple formatting
*/
return file_printf(ms, "\n- ");
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2135_0 |
crossvul-cpp_data_good_2834_0 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* COPYRIGHT (C) 2006,2007
* THE REGENTS OF THE UNIVERSITY OF MICHIGAN
* ALL RIGHTS RESERVED
*
* Permission is granted to use, copy, create derivative works
* and redistribute this software and such derivative works
* for any purpose, so long as the name of The University of
* Michigan is not used in any advertising or publicity
* pertaining to the use of distribution of this software
* without specific, written prior authorization. If the
* above copyright notice or any other identification of the
* University of Michigan is included in any copy of any
* portion of this software, then the disclaimer below must
* also be included.
*
* THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION
* FROM THE UNIVERSITY OF MICHIGAN AS TO ITS FITNESS FOR ANY
* PURPOSE, AND WITHOUT WARRANTY BY THE UNIVERSITY OF
* MICHIGAN OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
* REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE
* FOR ANY DAMAGES, INCLUDING SPECIAL, INDIRECT, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY CLAIM ARISING
* OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN
* IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*/
#include "pkinit_crypto_openssl.h"
#include "k5-buf.h"
#include <dlfcn.h>
#include <unistd.h>
#include <dirent.h>
#include <arpa/inet.h>
static krb5_error_code pkinit_init_pkinit_oids(pkinit_plg_crypto_context );
static void pkinit_fini_pkinit_oids(pkinit_plg_crypto_context );
static krb5_error_code pkinit_init_dh_params(pkinit_plg_crypto_context );
static void pkinit_fini_dh_params(pkinit_plg_crypto_context );
static krb5_error_code pkinit_init_certs(pkinit_identity_crypto_context ctx);
static void pkinit_fini_certs(pkinit_identity_crypto_context ctx);
static krb5_error_code pkinit_init_pkcs11(pkinit_identity_crypto_context ctx);
static void pkinit_fini_pkcs11(pkinit_identity_crypto_context ctx);
static krb5_error_code pkinit_encode_dh_params
(const BIGNUM *, const BIGNUM *, const BIGNUM *, uint8_t **, unsigned int *);
static DH *decode_dh_params(const uint8_t *, unsigned int );
static int pkinit_check_dh_params(DH *dh1, DH *dh2);
static krb5_error_code pkinit_sign_data
(krb5_context context, pkinit_identity_crypto_context cryptoctx,
unsigned char *data, unsigned int data_len,
unsigned char **sig, unsigned int *sig_len);
static krb5_error_code create_signature
(unsigned char **, unsigned int *, unsigned char *, unsigned int,
EVP_PKEY *pkey);
static krb5_error_code pkinit_decode_data
(krb5_context context, pkinit_identity_crypto_context cryptoctx,
const uint8_t *data, unsigned int data_len, uint8_t **decoded,
unsigned int *decoded_len);
#ifdef DEBUG_DH
static void print_dh(DH *, char *);
static void print_pubkey(BIGNUM *, char *);
#endif
static int prepare_enc_data
(const uint8_t *indata, int indata_len, uint8_t **outdata, int *outdata_len);
static int openssl_callback (int, X509_STORE_CTX *);
static int openssl_callback_ignore_crls (int, X509_STORE_CTX *);
static int pkcs7_decrypt
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
PKCS7 *p7, BIO *bio);
static BIO * pkcs7_dataDecode
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
PKCS7 *p7);
static ASN1_OBJECT * pkinit_pkcs7type2oid
(pkinit_plg_crypto_context plg_cryptoctx, int pkcs7_type);
static krb5_error_code pkinit_create_sequence_of_principal_identifiers
(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int type, krb5_pa_data ***e_data_out);
#ifndef WITHOUT_PKCS11
static krb5_error_code pkinit_find_private_key
(pkinit_identity_crypto_context, CK_ATTRIBUTE_TYPE usage,
CK_OBJECT_HANDLE *objp);
static krb5_error_code pkinit_login
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
CK_TOKEN_INFO *tip, const char *password);
static krb5_error_code pkinit_open_session
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx);
static void * pkinit_C_LoadModule(const char *modname, CK_FUNCTION_LIST_PTR_PTR p11p);
static CK_RV pkinit_C_UnloadModule(void *handle);
#ifdef SILLYDECRYPT
CK_RV pkinit_C_Decrypt
(pkinit_identity_crypto_context id_cryptoctx,
CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen,
CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen);
#endif
static krb5_error_code pkinit_sign_data_pkcs11
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data, unsigned int data_len,
unsigned char **sig, unsigned int *sig_len);
static krb5_error_code pkinit_decode_data_pkcs11
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
const uint8_t *data, unsigned int data_len, uint8_t **decoded_data,
unsigned int *decoded_data_len);
#endif /* WITHOUT_PKCS11 */
static krb5_error_code pkinit_sign_data_fs
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data, unsigned int data_len,
unsigned char **sig, unsigned int *sig_len);
static krb5_error_code pkinit_decode_data_fs
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
const uint8_t *data, unsigned int data_len, uint8_t **decoded_data,
unsigned int *decoded_data_len);
static krb5_error_code
create_krb5_invalidCertificates(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_external_principal_identifier *** ids);
static krb5_error_code
create_identifiers_from_stack(STACK_OF(X509) *sk,
krb5_external_principal_identifier *** ids);
static int
wrap_signeddata(unsigned char *data, unsigned int data_len,
unsigned char **out, unsigned int *out_len);
static char *
pkinit_pkcs11_code_to_text(int err);
#ifdef HAVE_OPENSSL_CMS
/* Use CMS support present in OpenSSL. */
#include <openssl/cms.h>
#define pkinit_CMS_get0_content_signed(_cms) CMS_get0_content(_cms)
#define pkinit_CMS_get0_content_data(_cms) CMS_get0_content(_cms)
#define pkinit_CMS_free1_crls(_sk_x509crl) \
sk_X509_CRL_pop_free((_sk_x509crl), X509_CRL_free)
#define pkinit_CMS_free1_certs(_sk_x509) \
sk_X509_pop_free((_sk_x509), X509_free)
#define pkinit_CMS_SignerInfo_get_cert(_cms,_si,_x509_pp) \
CMS_SignerInfo_get0_algs(_si,NULL,_x509_pp,NULL,NULL)
#else
/* Fake up CMS support using PKCS7. */
#define pkinit_CMS_free1_crls(_stack_of_x509crls) /* Don't free these */
#define pkinit_CMS_free1_certs(_stack_of_x509certs) /* Don't free these */
#define CMS_NO_SIGNER_CERT_VERIFY PKCS7_NOVERIFY
#define CMS_NOATTR PKCS7_NOATTR
#define CMS_ContentInfo PKCS7
#define CMS_SignerInfo PKCS7_SIGNER_INFO
#define d2i_CMS_ContentInfo d2i_PKCS7
#define CMS_get0_type(_p7) ((_p7)->type)
#define pkinit_CMS_get0_content_signed(_p7) (&((_p7)->d.sign->contents->d.other->value.octet_string))
#define pkinit_CMS_get0_content_data(_p7) (&((_p7)->d.other->value.octet_string))
#define CMS_set1_signers_certs(_p7,_stack_of_x509,_uint)
#define CMS_get0_SignerInfos PKCS7_get_signer_info
#define stack_st_CMS_SignerInfo stack_st_PKCS7_SIGNER_INFO
#undef sk_CMS_SignerInfo_value
#define sk_CMS_SignerInfo_value sk_PKCS7_SIGNER_INFO_value
#define CMS_get0_eContentType(_p7) (_p7->d.sign->contents->type)
#define CMS_verify PKCS7_verify
#define CMS_get1_crls(_p7) (_p7->d.sign->crl)
#define CMS_get1_certs(_p7) (_p7->d.sign->cert)
#define CMS_ContentInfo_free(_p7) PKCS7_free(_p7)
#define pkinit_CMS_SignerInfo_get_cert(_p7,_si,_x509_pp) \
(*_x509_pp) = PKCS7_cert_from_signer_info(_p7,_si)
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000L
/* 1.1 standardizes constructor and destructor names, renaming
* EVP_MD_CTX_{create,destroy} and deprecating ASN1_STRING_data. */
#define EVP_MD_CTX_new EVP_MD_CTX_create
#define EVP_MD_CTX_free EVP_MD_CTX_destroy
#define ASN1_STRING_get0_data ASN1_STRING_data
/* 1.1 makes many handle types opaque and adds accessors. Add compatibility
* versions of the new accessors we use for pre-1.1. */
#define OBJ_get0_data(o) ((o)->data)
#define OBJ_length(o) ((o)->length)
#define DH_set0_pqg compat_dh_set0_pqg
static int compat_dh_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g)
{
/* The real function frees the old values and does argument checking, but
* our code doesn't need that. */
dh->p = p;
dh->q = q;
dh->g = g;
return 1;
}
#define DH_get0_pqg compat_dh_get0_pqg
static void compat_dh_get0_pqg(const DH *dh, const BIGNUM **p,
const BIGNUM **q, const BIGNUM **g)
{
if (p != NULL)
*p = dh->p;
if (q != NULL)
*q = dh->q;
if (g != NULL)
*g = dh->g;
}
#define DH_get0_key compat_dh_get0_key
static void compat_dh_get0_key(const DH *dh, const BIGNUM **pub,
const BIGNUM **priv)
{
if (pub != NULL)
*pub = dh->pub_key;
if (priv != NULL)
*priv = dh->priv_key;
}
/* Return true if the cert c includes a key usage which doesn't include u.
* Define using direct member access for pre-1.1. */
#define ku_reject(c, u) \
(((c)->ex_flags & EXFLAG_KUSAGE) && !((c)->ex_kusage & (u)))
#else /* OPENSSL_VERSION_NUMBER >= 0x10100000L */
/* Return true if the cert x includes a key usage which doesn't include u. */
#define ku_reject(c, u) (!(X509_get_key_usage(c) & (u)))
#endif
static struct pkcs11_errstrings {
short code;
char *text;
} pkcs11_errstrings[] = {
{ 0x0, "ok" },
{ 0x1, "cancel" },
{ 0x2, "host memory" },
{ 0x3, "slot id invalid" },
{ 0x5, "general error" },
{ 0x6, "function failed" },
{ 0x7, "arguments bad" },
{ 0x8, "no event" },
{ 0x9, "need to create threads" },
{ 0xa, "cant lock" },
{ 0x10, "attribute read only" },
{ 0x11, "attribute sensitive" },
{ 0x12, "attribute type invalid" },
{ 0x13, "attribute value invalid" },
{ 0x20, "data invalid" },
{ 0x21, "data len range" },
{ 0x30, "device error" },
{ 0x31, "device memory" },
{ 0x32, "device removed" },
{ 0x40, "encrypted data invalid" },
{ 0x41, "encrypted data len range" },
{ 0x50, "function canceled" },
{ 0x51, "function not parallel" },
{ 0x54, "function not supported" },
{ 0x60, "key handle invalid" },
{ 0x62, "key size range" },
{ 0x63, "key type inconsistent" },
{ 0x64, "key not needed" },
{ 0x65, "key changed" },
{ 0x66, "key needed" },
{ 0x67, "key indigestible" },
{ 0x68, "key function not permitted" },
{ 0x69, "key not wrappable" },
{ 0x6a, "key unextractable" },
{ 0x70, "mechanism invalid" },
{ 0x71, "mechanism param invalid" },
{ 0x82, "object handle invalid" },
{ 0x90, "operation active" },
{ 0x91, "operation not initialized" },
{ 0xa0, "pin incorrect" },
{ 0xa1, "pin invalid" },
{ 0xa2, "pin len range" },
{ 0xa3, "pin expired" },
{ 0xa4, "pin locked" },
{ 0xb0, "session closed" },
{ 0xb1, "session count" },
{ 0xb3, "session handle invalid" },
{ 0xb4, "session parallel not supported" },
{ 0xb5, "session read only" },
{ 0xb6, "session exists" },
{ 0xb7, "session read only exists" },
{ 0xb8, "session read write so exists" },
{ 0xc0, "signature invalid" },
{ 0xc1, "signature len range" },
{ 0xd0, "template incomplete" },
{ 0xd1, "template inconsistent" },
{ 0xe0, "token not present" },
{ 0xe1, "token not recognized" },
{ 0xe2, "token write protected" },
{ 0xf0, "unwrapping key handle invalid" },
{ 0xf1, "unwrapping key size range" },
{ 0xf2, "unwrapping key type inconsistent" },
{ 0x100, "user already logged in" },
{ 0x101, "user not logged in" },
{ 0x102, "user pin not initialized" },
{ 0x103, "user type invalid" },
{ 0x104, "user another already logged in" },
{ 0x105, "user too many types" },
{ 0x110, "wrapped key invalid" },
{ 0x112, "wrapped key len range" },
{ 0x113, "wrapping key handle invalid" },
{ 0x114, "wrapping key size range" },
{ 0x115, "wrapping key type inconsistent" },
{ 0x120, "random seed not supported" },
{ 0x121, "random no rng" },
{ 0x130, "domain params invalid" },
{ 0x150, "buffer too small" },
{ 0x160, "saved state invalid" },
{ 0x170, "information sensitive" },
{ 0x180, "state unsaveable" },
{ 0x190, "cryptoki not initialized" },
{ 0x191, "cryptoki already initialized" },
{ 0x1a0, "mutex bad" },
{ 0x1a1, "mutex not locked" },
{ 0x200, "function rejected" },
{ -1, NULL }
};
/* DH parameters */
static uint8_t oakley_1024[128] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,
0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22,
0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B,
0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,
0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B,
0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5,
0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE6, 0x53, 0x81,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t oakley_2048[2048/8] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,
0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22,
0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B,
0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,
0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B,
0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5,
0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D,
0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,
0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A,
0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,
0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96,
0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,
0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D,
0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,
0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C,
0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,
0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03,
0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,
0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9,
0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,
0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5,
0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,
0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t oakley_4096[4096/8] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,
0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22,
0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B,
0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,
0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B,
0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5,
0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D,
0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,
0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A,
0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,
0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96,
0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,
0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D,
0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,
0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C,
0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,
0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03,
0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,
0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9,
0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,
0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5,
0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,
0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D,
0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33,
0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64,
0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A,
0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D,
0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7,
0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7,
0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D,
0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B,
0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64,
0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64,
0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C,
0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C,
0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2,
0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31,
0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E,
0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x21, 0x08, 0x01,
0x1A, 0x72, 0x3C, 0x12, 0xA7, 0x87, 0xE6, 0xD7,
0x88, 0x71, 0x9A, 0x10, 0xBD, 0xBA, 0x5B, 0x26,
0x99, 0xC3, 0x27, 0x18, 0x6A, 0xF4, 0xE2, 0x3C,
0x1A, 0x94, 0x68, 0x34, 0xB6, 0x15, 0x0B, 0xDA,
0x25, 0x83, 0xE9, 0xCA, 0x2A, 0xD4, 0x4C, 0xE8,
0xDB, 0xBB, 0xC2, 0xDB, 0x04, 0xDE, 0x8E, 0xF9,
0x2E, 0x8E, 0xFC, 0x14, 0x1F, 0xBE, 0xCA, 0xA6,
0x28, 0x7C, 0x59, 0x47, 0x4E, 0x6B, 0xC0, 0x5D,
0x99, 0xB2, 0x96, 0x4F, 0xA0, 0x90, 0xC3, 0xA2,
0x23, 0x3B, 0xA1, 0x86, 0x51, 0x5B, 0xE7, 0xED,
0x1F, 0x61, 0x29, 0x70, 0xCE, 0xE2, 0xD7, 0xAF,
0xB8, 0x1B, 0xDD, 0x76, 0x21, 0x70, 0x48, 0x1C,
0xD0, 0x06, 0x91, 0x27, 0xD5, 0xB0, 0x5A, 0xA9,
0x93, 0xB4, 0xEA, 0x98, 0x8D, 0x8F, 0xDD, 0xC1,
0x86, 0xFF, 0xB7, 0xDC, 0x90, 0xA6, 0xC0, 0x8F,
0x4D, 0xF4, 0x35, 0xC9, 0x34, 0x06, 0x31, 0x99,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
MAKE_INIT_FUNCTION(pkinit_openssl_init);
static krb5_error_code oerr(krb5_context context, krb5_error_code code,
const char *fmt, ...)
#if !defined(__cplusplus) && (__GNUC__ > 2)
__attribute__((__format__(__printf__, 3, 4)))
#endif
;
/*
* Set an error string containing the formatted arguments and the first pending
* OpenSSL error. Write the formatted arguments and all pending OpenSSL error
* messages to the trace log. Return code, or KRB5KDC_ERR_PREAUTH_FAILED if
* code is 0.
*/
static krb5_error_code
oerr(krb5_context context, krb5_error_code code, const char *fmt, ...)
{
unsigned long err;
va_list ap;
char *str, buf[128];
int r;
if (!code)
code = KRB5KDC_ERR_PREAUTH_FAILED;
va_start(ap, fmt);
r = vasprintf(&str, fmt, ap);
va_end(ap);
if (r < 0)
return code;
err = ERR_peek_error();
if (err) {
krb5_set_error_message(context, code, _("%s: %s"), str,
ERR_reason_error_string(err));
} else {
krb5_set_error_message(context, code, "%s", str);
}
TRACE_PKINIT_OPENSSL_ERROR(context, str);
while ((err = ERR_get_error()) != 0) {
ERR_error_string_n(err, buf, sizeof(buf));
TRACE_PKINIT_OPENSSL_ERROR(context, buf);
}
free(str);
return code;
}
/*
* Set an appropriate error string containing msg for a certificate
* verification failure from certctx. Write the message and all pending
* OpenSSL error messages to the trace log. Return code, or
* KRB5KDC_ERR_PREAUTH_FAILED if code is 0.
*/
static krb5_error_code
oerr_cert(krb5_context context, krb5_error_code code, X509_STORE_CTX *certctx,
const char *msg)
{
int depth = X509_STORE_CTX_get_error_depth(certctx);
int err = X509_STORE_CTX_get_error(certctx);
const char *errstr = X509_verify_cert_error_string(err);
return oerr(context, code, _("%s (depth %d): %s"), msg, depth, errstr);
}
krb5_error_code
pkinit_init_plg_crypto(pkinit_plg_crypto_context *cryptoctx)
{
krb5_error_code retval = ENOMEM;
pkinit_plg_crypto_context ctx = NULL;
(void)CALL_INIT_FUNCTION(pkinit_openssl_init);
ctx = malloc(sizeof(*ctx));
if (ctx == NULL)
goto out;
memset(ctx, 0, sizeof(*ctx));
pkiDebug("%s: initializing openssl crypto context at %p\n",
__FUNCTION__, ctx);
retval = pkinit_init_pkinit_oids(ctx);
if (retval)
goto out;
retval = pkinit_init_dh_params(ctx);
if (retval)
goto out;
*cryptoctx = ctx;
out:
if (retval && ctx != NULL)
pkinit_fini_plg_crypto(ctx);
return retval;
}
void
pkinit_fini_plg_crypto(pkinit_plg_crypto_context cryptoctx)
{
pkiDebug("%s: freeing context at %p\n", __FUNCTION__, cryptoctx);
if (cryptoctx == NULL)
return;
pkinit_fini_pkinit_oids(cryptoctx);
pkinit_fini_dh_params(cryptoctx);
free(cryptoctx);
}
krb5_error_code
pkinit_init_identity_crypto(pkinit_identity_crypto_context *idctx)
{
krb5_error_code retval = ENOMEM;
pkinit_identity_crypto_context ctx = NULL;
ctx = malloc(sizeof(*ctx));
if (ctx == NULL)
goto out;
memset(ctx, 0, sizeof(*ctx));
ctx->identity = NULL;
retval = pkinit_init_certs(ctx);
if (retval)
goto out;
retval = pkinit_init_pkcs11(ctx);
if (retval)
goto out;
pkiDebug("%s: returning ctx at %p\n", __FUNCTION__, ctx);
*idctx = ctx;
out:
if (retval) {
if (ctx)
pkinit_fini_identity_crypto(ctx);
}
return retval;
}
void
pkinit_fini_identity_crypto(pkinit_identity_crypto_context idctx)
{
if (idctx == NULL)
return;
pkiDebug("%s: freeing ctx at %p\n", __FUNCTION__, idctx);
if (idctx->deferred_ids != NULL)
pkinit_free_deferred_ids(idctx->deferred_ids);
free(idctx->identity);
pkinit_fini_certs(idctx);
pkinit_fini_pkcs11(idctx);
free(idctx);
}
krb5_error_code
pkinit_init_req_crypto(pkinit_req_crypto_context *cryptoctx)
{
krb5_error_code retval = ENOMEM;
pkinit_req_crypto_context ctx = NULL;
ctx = malloc(sizeof(*ctx));
if (ctx == NULL)
goto out;
memset(ctx, 0, sizeof(*ctx));
ctx->dh = NULL;
ctx->received_cert = NULL;
*cryptoctx = ctx;
pkiDebug("%s: returning ctx at %p\n", __FUNCTION__, ctx);
retval = 0;
out:
if (retval)
free(ctx);
return retval;
}
void
pkinit_fini_req_crypto(pkinit_req_crypto_context req_cryptoctx)
{
if (req_cryptoctx == NULL)
return;
pkiDebug("%s: freeing ctx at %p\n", __FUNCTION__, req_cryptoctx);
if (req_cryptoctx->dh != NULL)
DH_free(req_cryptoctx->dh);
if (req_cryptoctx->received_cert != NULL)
X509_free(req_cryptoctx->received_cert);
free(req_cryptoctx);
}
static krb5_error_code
pkinit_init_pkinit_oids(pkinit_plg_crypto_context ctx)
{
ctx->id_pkinit_san = OBJ_txt2obj("1.3.6.1.5.2.2", 1);
if (ctx->id_pkinit_san == NULL)
return ENOMEM;
ctx->id_pkinit_authData = OBJ_txt2obj("1.3.6.1.5.2.3.1", 1);
if (ctx->id_pkinit_authData == NULL)
return ENOMEM;
ctx->id_pkinit_DHKeyData = OBJ_txt2obj("1.3.6.1.5.2.3.2", 1);
if (ctx->id_pkinit_DHKeyData == NULL)
return ENOMEM;
ctx->id_pkinit_rkeyData = OBJ_txt2obj("1.3.6.1.5.2.3.3", 1);
if (ctx->id_pkinit_rkeyData == NULL)
return ENOMEM;
ctx->id_pkinit_KPClientAuth = OBJ_txt2obj("1.3.6.1.5.2.3.4", 1);
if (ctx->id_pkinit_KPClientAuth == NULL)
return ENOMEM;
ctx->id_pkinit_KPKdc = OBJ_txt2obj("1.3.6.1.5.2.3.5", 1);
if (ctx->id_pkinit_KPKdc == NULL)
return ENOMEM;
ctx->id_ms_kp_sc_logon = OBJ_txt2obj("1.3.6.1.4.1.311.20.2.2", 1);
if (ctx->id_ms_kp_sc_logon == NULL)
return ENOMEM;
ctx->id_ms_san_upn = OBJ_txt2obj("1.3.6.1.4.1.311.20.2.3", 1);
if (ctx->id_ms_san_upn == NULL)
return ENOMEM;
ctx->id_kp_serverAuth = OBJ_txt2obj("1.3.6.1.5.5.7.3.1", 1);
if (ctx->id_kp_serverAuth == NULL)
return ENOMEM;
return 0;
}
static krb5_error_code
get_cert(char *filename, X509 **retcert)
{
X509 *cert = NULL;
BIO *tmp = NULL;
int code;
krb5_error_code retval;
if (filename == NULL || retcert == NULL)
return EINVAL;
*retcert = NULL;
tmp = BIO_new(BIO_s_file());
if (tmp == NULL)
return ENOMEM;
code = BIO_read_filename(tmp, filename);
if (code == 0) {
retval = errno;
goto cleanup;
}
cert = (X509 *) PEM_read_bio_X509(tmp, NULL, NULL, NULL);
if (cert == NULL) {
retval = EIO;
pkiDebug("failed to read certificate from %s\n", filename);
goto cleanup;
}
*retcert = cert;
retval = 0;
cleanup:
if (tmp != NULL)
BIO_free(tmp);
return retval;
}
struct get_key_cb_data {
krb5_context context;
pkinit_identity_crypto_context id_cryptoctx;
const char *fsname;
char *filename;
const char *password;
};
static int
get_key_cb(char *buf, int size, int rwflag, void *userdata)
{
struct get_key_cb_data *data = userdata;
pkinit_identity_crypto_context id_cryptoctx;
krb5_data rdat;
krb5_prompt kprompt;
krb5_prompt_type prompt_type;
krb5_error_code retval;
char *prompt;
if (data->id_cryptoctx->defer_id_prompt) {
/* Supply the identity name to be passed to a responder callback. */
pkinit_set_deferred_id(&data->id_cryptoctx->deferred_ids,
data->fsname, 0, NULL);
return -1;
}
if (data->password == NULL) {
/* We don't already have a password to use, so prompt for one. */
if (data->id_cryptoctx->prompter == NULL)
return -1;
if (asprintf(&prompt, "%s %s", _("Pass phrase for"),
data->filename) < 0)
return -1;
rdat.data = buf;
rdat.length = size;
kprompt.prompt = prompt;
kprompt.hidden = 1;
kprompt.reply = &rdat;
prompt_type = KRB5_PROMPT_TYPE_PREAUTH;
/* PROMPTER_INVOCATION */
k5int_set_prompt_types(data->context, &prompt_type);
id_cryptoctx = data->id_cryptoctx;
retval = (data->id_cryptoctx->prompter)(data->context,
id_cryptoctx->prompter_data,
NULL, NULL, 1, &kprompt);
k5int_set_prompt_types(data->context, 0);
free(prompt);
if (retval != 0)
return -1;
} else {
/* Just use the already-supplied password. */
rdat.length = strlen(data->password);
if ((int)rdat.length >= size)
return -1;
snprintf(buf, size, "%s", data->password);
}
return (int)rdat.length;
}
static krb5_error_code
get_key(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
char *filename, const char *fsname, EVP_PKEY **retkey,
const char *password)
{
EVP_PKEY *pkey = NULL;
BIO *tmp = NULL;
struct get_key_cb_data cb_data;
int code;
krb5_error_code retval;
if (filename == NULL || retkey == NULL)
return EINVAL;
tmp = BIO_new(BIO_s_file());
if (tmp == NULL)
return ENOMEM;
code = BIO_read_filename(tmp, filename);
if (code == 0) {
retval = errno;
goto cleanup;
}
cb_data.context = context;
cb_data.id_cryptoctx = id_cryptoctx;
cb_data.filename = filename;
cb_data.fsname = fsname;
cb_data.password = password;
pkey = PEM_read_bio_PrivateKey(tmp, NULL, get_key_cb, &cb_data);
if (pkey == NULL && !id_cryptoctx->defer_id_prompt) {
retval = EIO;
pkiDebug("failed to read private key from %s\n", filename);
goto cleanup;
}
*retkey = pkey;
retval = 0;
cleanup:
if (tmp != NULL)
BIO_free(tmp);
return retval;
}
static void
pkinit_fini_pkinit_oids(pkinit_plg_crypto_context ctx)
{
if (ctx == NULL)
return;
ASN1_OBJECT_free(ctx->id_pkinit_san);
ASN1_OBJECT_free(ctx->id_pkinit_authData);
ASN1_OBJECT_free(ctx->id_pkinit_DHKeyData);
ASN1_OBJECT_free(ctx->id_pkinit_rkeyData);
ASN1_OBJECT_free(ctx->id_pkinit_KPClientAuth);
ASN1_OBJECT_free(ctx->id_pkinit_KPKdc);
ASN1_OBJECT_free(ctx->id_ms_kp_sc_logon);
ASN1_OBJECT_free(ctx->id_ms_san_upn);
ASN1_OBJECT_free(ctx->id_kp_serverAuth);
}
/* Construct an OpenSSL DH object for an Oakley group. */
static DH *
make_oakley_dh(uint8_t *prime, size_t len)
{
DH *dh = NULL;
BIGNUM *p = NULL, *q = NULL, *g = NULL;
p = BN_bin2bn(prime, len, NULL);
if (p == NULL)
goto cleanup;
q = BN_new();
if (q == NULL)
goto cleanup;
if (!BN_rshift1(q, p))
goto cleanup;
g = BN_new();
if (g == NULL)
goto cleanup;
if (!BN_set_word(g, DH_GENERATOR_2))
goto cleanup;
dh = DH_new();
if (dh == NULL)
goto cleanup;
DH_set0_pqg(dh, p, q, g);
p = g = q = NULL;
cleanup:
BN_free(p);
BN_free(q);
BN_free(g);
return dh;
}
static krb5_error_code
pkinit_init_dh_params(pkinit_plg_crypto_context plgctx)
{
krb5_error_code retval = ENOMEM;
plgctx->dh_1024 = make_oakley_dh(oakley_1024, sizeof(oakley_1024));
if (plgctx->dh_1024 == NULL)
goto cleanup;
plgctx->dh_2048 = make_oakley_dh(oakley_2048, sizeof(oakley_2048));
if (plgctx->dh_2048 == NULL)
goto cleanup;
plgctx->dh_4096 = make_oakley_dh(oakley_4096, sizeof(oakley_4096));
if (plgctx->dh_4096 == NULL)
goto cleanup;
retval = 0;
cleanup:
if (retval)
pkinit_fini_dh_params(plgctx);
return retval;
}
static void
pkinit_fini_dh_params(pkinit_plg_crypto_context plgctx)
{
if (plgctx->dh_1024 != NULL)
DH_free(plgctx->dh_1024);
if (plgctx->dh_2048 != NULL)
DH_free(plgctx->dh_2048);
if (plgctx->dh_4096 != NULL)
DH_free(plgctx->dh_4096);
plgctx->dh_1024 = plgctx->dh_2048 = plgctx->dh_4096 = NULL;
}
static krb5_error_code
pkinit_init_certs(pkinit_identity_crypto_context ctx)
{
krb5_error_code retval = ENOMEM;
int i;
for (i = 0; i < MAX_CREDS_ALLOWED; i++)
ctx->creds[i] = NULL;
ctx->my_certs = NULL;
ctx->cert_index = 0;
ctx->my_key = NULL;
ctx->trustedCAs = NULL;
ctx->intermediateCAs = NULL;
ctx->revoked = NULL;
retval = 0;
return retval;
}
static void
pkinit_fini_certs(pkinit_identity_crypto_context ctx)
{
if (ctx == NULL)
return;
if (ctx->my_certs != NULL)
sk_X509_pop_free(ctx->my_certs, X509_free);
if (ctx->my_key != NULL)
EVP_PKEY_free(ctx->my_key);
if (ctx->trustedCAs != NULL)
sk_X509_pop_free(ctx->trustedCAs, X509_free);
if (ctx->intermediateCAs != NULL)
sk_X509_pop_free(ctx->intermediateCAs, X509_free);
if (ctx->revoked != NULL)
sk_X509_CRL_pop_free(ctx->revoked, X509_CRL_free);
}
static krb5_error_code
pkinit_init_pkcs11(pkinit_identity_crypto_context ctx)
{
krb5_error_code retval = ENOMEM;
#ifndef WITHOUT_PKCS11
ctx->p11_module_name = strdup(PKCS11_MODNAME);
if (ctx->p11_module_name == NULL)
return retval;
ctx->p11_module = NULL;
ctx->slotid = PK_NOSLOT;
ctx->token_label = NULL;
ctx->cert_label = NULL;
ctx->session = CK_INVALID_HANDLE;
ctx->p11 = NULL;
#endif
ctx->pkcs11_method = 0;
retval = 0;
return retval;
}
static void
pkinit_fini_pkcs11(pkinit_identity_crypto_context ctx)
{
#ifndef WITHOUT_PKCS11
if (ctx == NULL)
return;
if (ctx->p11 != NULL) {
if (ctx->session != CK_INVALID_HANDLE) {
ctx->p11->C_CloseSession(ctx->session);
ctx->session = CK_INVALID_HANDLE;
}
ctx->p11->C_Finalize(NULL_PTR);
ctx->p11 = NULL;
}
if (ctx->p11_module != NULL) {
pkinit_C_UnloadModule(ctx->p11_module);
ctx->p11_module = NULL;
}
free(ctx->p11_module_name);
free(ctx->token_label);
free(ctx->cert_id);
free(ctx->cert_label);
#endif
}
krb5_error_code
pkinit_identity_set_prompter(pkinit_identity_crypto_context id_cryptoctx,
krb5_prompter_fct prompter,
void *prompter_data)
{
id_cryptoctx->prompter = prompter;
id_cryptoctx->prompter_data = prompter_data;
return 0;
}
/* Create a CMS ContentInfo of type oid containing the octet string in data. */
static krb5_error_code
create_contentinfo(krb5_context context, ASN1_OBJECT *oid,
unsigned char *data, size_t data_len, PKCS7 **p7_out)
{
PKCS7 *p7 = NULL;
ASN1_OCTET_STRING *ostr = NULL;
*p7_out = NULL;
ostr = ASN1_OCTET_STRING_new();
if (ostr == NULL)
goto oom;
if (!ASN1_OCTET_STRING_set(ostr, (unsigned char *)data, data_len))
goto oom;
p7 = PKCS7_new();
if (p7 == NULL)
goto oom;
p7->type = OBJ_dup(oid);
if (p7->type == NULL)
goto oom;
if (OBJ_obj2nid(oid) == NID_pkcs7_data) {
/* Draft 9 uses id-pkcs7-data for signed data. For this type OpenSSL
* expects an octet string in d.data. */
p7->d.data = ostr;
} else {
p7->d.other = ASN1_TYPE_new();
if (p7->d.other == NULL)
goto oom;
p7->d.other->type = V_ASN1_OCTET_STRING;
p7->d.other->value.octet_string = ostr;
}
*p7_out = p7;
return 0;
oom:
if (ostr != NULL)
ASN1_OCTET_STRING_free(ostr);
if (p7 != NULL)
PKCS7_free(p7);
return ENOMEM;
}
krb5_error_code
cms_contentinfo_create(krb5_context context, /* IN */
pkinit_plg_crypto_context plg_cryptoctx, /* IN */
pkinit_req_crypto_context req_cryptoctx, /* IN */
pkinit_identity_crypto_context id_cryptoctx, /* IN */
int cms_msg_type,
unsigned char *data, unsigned int data_len,
unsigned char **out_data, unsigned int *out_data_len)
{
krb5_error_code retval = ENOMEM;
ASN1_OBJECT *oid;
PKCS7 *p7 = NULL;
unsigned char *p;
/* Pick the correct oid for the eContentInfo. */
oid = pkinit_pkcs7type2oid(plg_cryptoctx, cms_msg_type);
if (oid == NULL)
goto cleanup;
retval = create_contentinfo(context, oid, data, data_len, &p7);
if (retval != 0)
goto cleanup;
*out_data_len = i2d_PKCS7(p7, NULL);
if (!(*out_data_len)) {
retval = oerr(context, 0, _("Failed to DER encode PKCS7"));
goto cleanup;
}
retval = ENOMEM;
if ((p = *out_data = malloc(*out_data_len)) == NULL)
goto cleanup;
/* DER encode PKCS7 data */
retval = i2d_PKCS7(p7, &p);
if (!retval) {
retval = oerr(context, 0, _("Failed to DER encode PKCS7"));
goto cleanup;
}
retval = 0;
cleanup:
if (p7)
PKCS7_free(p7);
return retval;
}
krb5_error_code
cms_signeddata_create(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int cms_msg_type,
int include_certchain,
unsigned char *data,
unsigned int data_len,
unsigned char **signed_data,
unsigned int *signed_data_len)
{
krb5_error_code retval = ENOMEM;
PKCS7 *p7 = NULL, *inner_p7 = NULL;
PKCS7_SIGNED *p7s = NULL;
PKCS7_SIGNER_INFO *p7si = NULL;
unsigned char *p;
STACK_OF(X509) * cert_stack = NULL;
ASN1_OCTET_STRING *digest_attr = NULL;
EVP_MD_CTX *ctx;
const EVP_MD *md_tmp = NULL;
unsigned char md_data[EVP_MAX_MD_SIZE], md_data2[EVP_MAX_MD_SIZE];
unsigned char *digestInfo_buf = NULL, *abuf = NULL;
unsigned int md_len, md_len2, alen, digestInfo_len;
STACK_OF(X509_ATTRIBUTE) * sk;
unsigned char *sig = NULL;
unsigned int sig_len = 0;
X509_ALGOR *alg = NULL;
ASN1_OCTET_STRING *digest = NULL;
unsigned int alg_len = 0, digest_len = 0;
unsigned char *y = NULL;
X509 *cert = NULL;
ASN1_OBJECT *oid = NULL, *oid_copy;
/* Start creating PKCS7 data. */
if ((p7 = PKCS7_new()) == NULL)
goto cleanup;
p7->type = OBJ_nid2obj(NID_pkcs7_signed);
if ((p7s = PKCS7_SIGNED_new()) == NULL)
goto cleanup;
p7->d.sign = p7s;
if (!ASN1_INTEGER_set(p7s->version, 3))
goto cleanup;
/* pick the correct oid for the eContentInfo */
oid = pkinit_pkcs7type2oid(plg_cryptoctx, cms_msg_type);
if (oid == NULL)
goto cleanup;
if (id_cryptoctx->my_certs != NULL) {
/* create a cert chain that has at least the signer's certificate */
if ((cert_stack = sk_X509_new_null()) == NULL)
goto cleanup;
cert = sk_X509_value(id_cryptoctx->my_certs, id_cryptoctx->cert_index);
if (!include_certchain) {
pkiDebug("only including signer's certificate\n");
sk_X509_push(cert_stack, X509_dup(cert));
} else {
/* create a cert chain */
X509_STORE *certstore = NULL;
X509_STORE_CTX *certctx;
STACK_OF(X509) *certstack = NULL;
char buf[DN_BUF_LEN];
unsigned int i = 0, size = 0;
if ((certstore = X509_STORE_new()) == NULL)
goto cleanup;
pkiDebug("building certificate chain\n");
X509_STORE_set_verify_cb(certstore, openssl_callback);
certctx = X509_STORE_CTX_new();
if (certctx == NULL)
goto cleanup;
X509_STORE_CTX_init(certctx, certstore, cert,
id_cryptoctx->intermediateCAs);
X509_STORE_CTX_trusted_stack(certctx, id_cryptoctx->trustedCAs);
if (!X509_verify_cert(certctx)) {
retval = oerr_cert(context, 0, certctx,
_("Failed to verify own certificate"));
goto cleanup;
}
certstack = X509_STORE_CTX_get1_chain(certctx);
size = sk_X509_num(certstack);
pkiDebug("size of certificate chain = %d\n", size);
for(i = 0; i < size - 1; i++) {
X509 *x = sk_X509_value(certstack, i);
X509_NAME_oneline(X509_get_subject_name(x), buf, sizeof(buf));
pkiDebug("cert #%d: %s\n", i, buf);
sk_X509_push(cert_stack, X509_dup(x));
}
X509_STORE_CTX_free(certctx);
X509_STORE_free(certstore);
sk_X509_pop_free(certstack, X509_free);
}
p7s->cert = cert_stack;
/* fill-in PKCS7_SIGNER_INFO */
if ((p7si = PKCS7_SIGNER_INFO_new()) == NULL)
goto cleanup;
if (!ASN1_INTEGER_set(p7si->version, 1))
goto cleanup;
if (!X509_NAME_set(&p7si->issuer_and_serial->issuer,
X509_get_issuer_name(cert)))
goto cleanup;
/* because ASN1_INTEGER_set is used to set a 'long' we will do
* things the ugly way. */
ASN1_INTEGER_free(p7si->issuer_and_serial->serial);
if (!(p7si->issuer_and_serial->serial =
ASN1_INTEGER_dup(X509_get_serialNumber(cert))))
goto cleanup;
/* will not fill-out EVP_PKEY because it's on the smartcard */
/* Set digest algs */
p7si->digest_alg->algorithm = OBJ_nid2obj(NID_sha1);
if (p7si->digest_alg->parameter != NULL)
ASN1_TYPE_free(p7si->digest_alg->parameter);
if ((p7si->digest_alg->parameter = ASN1_TYPE_new()) == NULL)
goto cleanup;
p7si->digest_alg->parameter->type = V_ASN1_NULL;
/* Set sig algs */
if (p7si->digest_enc_alg->parameter != NULL)
ASN1_TYPE_free(p7si->digest_enc_alg->parameter);
p7si->digest_enc_alg->algorithm = OBJ_nid2obj(NID_sha1WithRSAEncryption);
if (!(p7si->digest_enc_alg->parameter = ASN1_TYPE_new()))
goto cleanup;
p7si->digest_enc_alg->parameter->type = V_ASN1_NULL;
if (cms_msg_type == CMS_SIGN_DRAFT9){
/* don't include signed attributes for pa-type 15 request */
abuf = data;
alen = data_len;
} else {
/* add signed attributes */
/* compute sha1 digest over the EncapsulatedContentInfo */
ctx = EVP_MD_CTX_new();
if (ctx == NULL)
goto cleanup;
EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
EVP_DigestUpdate(ctx, data, data_len);
md_tmp = EVP_MD_CTX_md(ctx);
EVP_DigestFinal_ex(ctx, md_data, &md_len);
EVP_MD_CTX_free(ctx);
/* create a message digest attr */
digest_attr = ASN1_OCTET_STRING_new();
ASN1_OCTET_STRING_set(digest_attr, md_data, (int)md_len);
PKCS7_add_signed_attribute(p7si, NID_pkcs9_messageDigest,
V_ASN1_OCTET_STRING, (char *) digest_attr);
/* create a content-type attr */
oid_copy = OBJ_dup(oid);
if (oid_copy == NULL)
goto cleanup2;
PKCS7_add_signed_attribute(p7si, NID_pkcs9_contentType,
V_ASN1_OBJECT, oid_copy);
/* create the signature over signed attributes. get DER encoded value */
/* This is the place where smartcard signature needs to be calculated */
sk = p7si->auth_attr;
alen = ASN1_item_i2d((ASN1_VALUE *) sk, &abuf,
ASN1_ITEM_rptr(PKCS7_ATTR_SIGN));
if (abuf == NULL)
goto cleanup2;
} /* signed attributes */
#ifndef WITHOUT_PKCS11
/* Some tokens can only do RSAEncryption without sha1 hash */
/* to compute sha1WithRSAEncryption, encode the algorithm ID for the hash
* function and the hash value into an ASN.1 value of type DigestInfo
* DigestInfo::=SEQUENCE {
* digestAlgorithm AlgorithmIdentifier,
* digest OCTET STRING }
*/
if (id_cryptoctx->pkcs11_method == 1 &&
id_cryptoctx->mech == CKM_RSA_PKCS) {
pkiDebug("mech = CKM_RSA_PKCS\n");
ctx = EVP_MD_CTX_new();
if (ctx == NULL)
goto cleanup;
/* if this is not draft9 request, include digest signed attribute */
if (cms_msg_type != CMS_SIGN_DRAFT9)
EVP_DigestInit_ex(ctx, md_tmp, NULL);
else
EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
EVP_DigestUpdate(ctx, abuf, alen);
EVP_DigestFinal_ex(ctx, md_data2, &md_len2);
EVP_MD_CTX_free(ctx);
alg = X509_ALGOR_new();
if (alg == NULL)
goto cleanup2;
X509_ALGOR_set0(alg, OBJ_nid2obj(NID_sha1), V_ASN1_NULL, NULL);
alg_len = i2d_X509_ALGOR(alg, NULL);
digest = ASN1_OCTET_STRING_new();
if (digest == NULL)
goto cleanup2;
ASN1_OCTET_STRING_set(digest, md_data2, (int)md_len2);
digest_len = i2d_ASN1_OCTET_STRING(digest, NULL);
digestInfo_len = ASN1_object_size(1, (int)(alg_len + digest_len),
V_ASN1_SEQUENCE);
y = digestInfo_buf = malloc(digestInfo_len);
if (digestInfo_buf == NULL)
goto cleanup2;
ASN1_put_object(&y, 1, (int)(alg_len + digest_len), V_ASN1_SEQUENCE,
V_ASN1_UNIVERSAL);
i2d_X509_ALGOR(alg, &y);
i2d_ASN1_OCTET_STRING(digest, &y);
#ifdef DEBUG_SIG
pkiDebug("signing buffer\n");
print_buffer(digestInfo_buf, digestInfo_len);
print_buffer_bin(digestInfo_buf, digestInfo_len, "/tmp/pkcs7_tosign");
#endif
retval = pkinit_sign_data(context, id_cryptoctx, digestInfo_buf,
digestInfo_len, &sig, &sig_len);
} else
#endif
{
pkiDebug("mech = %s\n",
id_cryptoctx->pkcs11_method == 1 ? "CKM_SHA1_RSA_PKCS" : "FS");
retval = pkinit_sign_data(context, id_cryptoctx, abuf, alen,
&sig, &sig_len);
}
#ifdef DEBUG_SIG
print_buffer(sig, sig_len);
#endif
if (cms_msg_type != CMS_SIGN_DRAFT9 )
free(abuf);
if (retval)
goto cleanup2;
/* Add signature */
if (!ASN1_STRING_set(p7si->enc_digest, (unsigned char *) sig,
(int)sig_len)) {
retval = oerr(context, 0, _("Failed to add digest attribute"));
goto cleanup2;
}
/* adder signer_info to pkcs7 signed */
if (!PKCS7_add_signer(p7, p7si))
goto cleanup2;
} /* we have a certificate */
/* start on adding data to the pkcs7 signed */
retval = create_contentinfo(context, oid, data, data_len, &inner_p7);
if (p7s->contents != NULL)
PKCS7_free(p7s->contents);
p7s->contents = inner_p7;
*signed_data_len = i2d_PKCS7(p7, NULL);
if (!(*signed_data_len)) {
retval = oerr(context, 0, _("Failed to DER encode PKCS7"));
goto cleanup2;
}
retval = ENOMEM;
if ((p = *signed_data = malloc(*signed_data_len)) == NULL)
goto cleanup2;
/* DER encode PKCS7 data */
retval = i2d_PKCS7(p7, &p);
if (!retval) {
retval = oerr(context, 0, _("Failed to DER encode PKCS7"));
goto cleanup2;
}
retval = 0;
#ifdef DEBUG_ASN1
if (cms_msg_type == CMS_SIGN_CLIENT) {
print_buffer_bin(*signed_data, *signed_data_len,
"/tmp/client_pkcs7_signeddata");
} else {
if (cms_msg_type == CMS_SIGN_SERVER) {
print_buffer_bin(*signed_data, *signed_data_len,
"/tmp/kdc_pkcs7_signeddata");
} else {
print_buffer_bin(*signed_data, *signed_data_len,
"/tmp/draft9_pkcs7_signeddata");
}
}
#endif
cleanup2:
if (p7si) {
if (cms_msg_type != CMS_SIGN_DRAFT9)
#ifndef WITHOUT_PKCS11
if (id_cryptoctx->pkcs11_method == 1 &&
id_cryptoctx->mech == CKM_RSA_PKCS) {
free(digestInfo_buf);
if (digest != NULL)
ASN1_OCTET_STRING_free(digest);
}
#endif
if (alg != NULL)
X509_ALGOR_free(alg);
}
cleanup:
if (p7 != NULL)
PKCS7_free(p7);
free(sig);
return retval;
}
krb5_error_code
cms_signeddata_verify(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
pkinit_identity_crypto_context idctx,
int cms_msg_type,
int require_crl_checking,
unsigned char *signed_data,
unsigned int signed_data_len,
unsigned char **data,
unsigned int *data_len,
unsigned char **authz_data,
unsigned int *authz_data_len,
int *is_signed)
{
/*
* Warning: Since most openssl functions do not set retval, large chunks of
* this function assume that retval is always a failure and may go to
* cleanup without setting retval explicitly. Make sure retval is not set
* to 0 or errors such as signature verification failure may be converted
* to success with significant security consequences.
*/
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
CMS_ContentInfo *cms = NULL;
BIO *out = NULL;
int flags = CMS_NO_SIGNER_CERT_VERIFY;
int valid_oid = 0;
unsigned int i = 0;
unsigned int vflags = 0, size = 0;
const unsigned char *p = signed_data;
STACK_OF(CMS_SignerInfo) *si_sk = NULL;
CMS_SignerInfo *si = NULL;
X509 *x = NULL;
X509_STORE *store = NULL;
X509_STORE_CTX *cert_ctx;
STACK_OF(X509) *signerCerts = NULL;
STACK_OF(X509) *intermediateCAs = NULL;
STACK_OF(X509_CRL) *signerRevoked = NULL;
STACK_OF(X509_CRL) *revoked = NULL;
STACK_OF(X509) *verified_chain = NULL;
ASN1_OBJECT *oid = NULL;
const ASN1_OBJECT *type = NULL, *etype = NULL;
ASN1_OCTET_STRING **octets;
krb5_external_principal_identifier **krb5_verified_chain = NULL;
krb5_data *authz = NULL;
char buf[DN_BUF_LEN];
#ifdef DEBUG_ASN1
print_buffer_bin(signed_data, signed_data_len,
"/tmp/client_received_pkcs7_signeddata");
#endif
if (is_signed)
*is_signed = 1;
oid = pkinit_pkcs7type2oid(plgctx, cms_msg_type);
if (oid == NULL)
goto cleanup;
/* decode received CMS message */
if ((cms = d2i_CMS_ContentInfo(NULL, &p, (int)signed_data_len)) == NULL) {
retval = oerr(context, 0, _("Failed to decode CMS message"));
goto cleanup;
}
etype = CMS_get0_eContentType(cms);
/*
* Prior to 1.10 the MIT client incorrectly emitted the pkinit structure
* directly in a CMS ContentInfo rather than using SignedData with no
* signers. Handle that case.
*/
type = CMS_get0_type(cms);
if (is_signed && !OBJ_cmp(type, oid)) {
unsigned char *d;
*is_signed = 0;
octets = pkinit_CMS_get0_content_data(cms);
if (!octets || ((*octets)->type != V_ASN1_OCTET_STRING)) {
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval,
_("Invalid pkinit packet: octet string "
"expected"));
goto cleanup;
}
*data_len = ASN1_STRING_length(*octets);
d = malloc(*data_len);
if (d == NULL) {
retval = ENOMEM;
goto cleanup;
}
memcpy(d, ASN1_STRING_get0_data(*octets), *data_len);
*data = d;
goto out;
} else {
/* Verify that the received message is CMS SignedData message. */
if (OBJ_obj2nid(type) != NID_pkcs7_signed) {
pkiDebug("Expected id-signedData CMS msg (received type = %d)\n",
OBJ_obj2nid(type));
krb5_set_error_message(context, retval, _("wrong oid\n"));
goto cleanup;
}
}
/* setup to verify X509 certificate used to sign CMS message */
if (!(store = X509_STORE_new()))
goto cleanup;
/* check if we are inforcing CRL checking */
vflags = X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;
if (require_crl_checking)
X509_STORE_set_verify_cb(store, openssl_callback);
else
X509_STORE_set_verify_cb(store, openssl_callback_ignore_crls);
X509_STORE_set_flags(store, vflags);
/*
* Get the signer's information from the CMS message. Match signer ID
* against anchors and intermediate CAs in case no certs are present in the
* SignedData. If we start sending kdcPkId values in requests, we'll need
* to match against the source of that information too.
*/
CMS_set1_signers_certs(cms, NULL, 0);
CMS_set1_signers_certs(cms, idctx->trustedCAs, CMS_NOINTERN);
CMS_set1_signers_certs(cms, idctx->intermediateCAs, CMS_NOINTERN);
if (((si_sk = CMS_get0_SignerInfos(cms)) == NULL) ||
((si = sk_CMS_SignerInfo_value(si_sk, 0)) == NULL)) {
/* Not actually signed; anonymous case */
if (!is_signed)
goto cleanup;
*is_signed = 0;
/* We cannot use CMS_dataInit because there may be no digest */
octets = pkinit_CMS_get0_content_signed(cms);
if (octets)
out = BIO_new_mem_buf((*octets)->data, (*octets)->length);
if (out == NULL)
goto cleanup;
} else {
pkinit_CMS_SignerInfo_get_cert(cms, si, &x);
if (x == NULL)
goto cleanup;
/* create available CRL information (get local CRLs and include CRLs
* received in the CMS message
*/
signerRevoked = CMS_get1_crls(cms);
if (idctx->revoked == NULL)
revoked = signerRevoked;
else if (signerRevoked == NULL)
revoked = idctx->revoked;
else {
size = sk_X509_CRL_num(idctx->revoked);
revoked = sk_X509_CRL_new_null();
for (i = 0; i < size; i++)
sk_X509_CRL_push(revoked, sk_X509_CRL_value(idctx->revoked, i));
size = sk_X509_CRL_num(signerRevoked);
for (i = 0; i < size; i++)
sk_X509_CRL_push(revoked, sk_X509_CRL_value(signerRevoked, i));
}
/* create available intermediate CAs chains (get local intermediateCAs and
* include the CA chain received in the CMS message
*/
signerCerts = CMS_get1_certs(cms);
if (idctx->intermediateCAs == NULL)
intermediateCAs = signerCerts;
else if (signerCerts == NULL)
intermediateCAs = idctx->intermediateCAs;
else {
size = sk_X509_num(idctx->intermediateCAs);
intermediateCAs = sk_X509_new_null();
for (i = 0; i < size; i++) {
sk_X509_push(intermediateCAs,
sk_X509_value(idctx->intermediateCAs, i));
}
size = sk_X509_num(signerCerts);
for (i = 0; i < size; i++) {
sk_X509_push(intermediateCAs, sk_X509_value(signerCerts, i));
}
}
/* initialize x509 context with the received certificate and
* trusted and intermediate CA chains and CRLs
*/
cert_ctx = X509_STORE_CTX_new();
if (cert_ctx == NULL)
goto cleanup;
if (!X509_STORE_CTX_init(cert_ctx, store, x, intermediateCAs))
goto cleanup;
X509_STORE_CTX_set0_crls(cert_ctx, revoked);
/* add trusted CAs certificates for cert verification */
if (idctx->trustedCAs != NULL)
X509_STORE_CTX_trusted_stack(cert_ctx, idctx->trustedCAs);
else {
pkiDebug("unable to find any trusted CAs\n");
goto cleanup;
}
#ifdef DEBUG_CERTCHAIN
if (intermediateCAs != NULL) {
size = sk_X509_num(intermediateCAs);
pkiDebug("untrusted cert chain of size %d\n", size);
for (i = 0; i < size; i++) {
X509_NAME_oneline(X509_get_subject_name(
sk_X509_value(intermediateCAs, i)), buf, sizeof(buf));
pkiDebug("cert #%d: %s\n", i, buf);
}
}
if (idctx->trustedCAs != NULL) {
size = sk_X509_num(idctx->trustedCAs);
pkiDebug("trusted cert chain of size %d\n", size);
for (i = 0; i < size; i++) {
X509_NAME_oneline(X509_get_subject_name(
sk_X509_value(idctx->trustedCAs, i)), buf, sizeof(buf));
pkiDebug("cert #%d: %s\n", i, buf);
}
}
if (revoked != NULL) {
size = sk_X509_CRL_num(revoked);
pkiDebug("CRL chain of size %d\n", size);
for (i = 0; i < size; i++) {
X509_CRL *crl = sk_X509_CRL_value(revoked, i);
X509_NAME_oneline(X509_CRL_get_issuer(crl), buf, sizeof(buf));
pkiDebug("crls by CA #%d: %s\n", i , buf);
}
}
#endif
i = X509_verify_cert(cert_ctx);
if (i <= 0) {
int j = X509_STORE_CTX_get_error(cert_ctx);
X509 *cert;
cert = X509_STORE_CTX_get_current_cert(cert_ctx);
reqctx->received_cert = X509_dup(cert);
switch(j) {
case X509_V_ERR_CERT_REVOKED:
retval = KRB5KDC_ERR_REVOKED_CERTIFICATE;
break;
case X509_V_ERR_UNABLE_TO_GET_CRL:
retval = KRB5KDC_ERR_REVOCATION_STATUS_UNKNOWN;
break;
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
retval = KRB5KDC_ERR_CANT_VERIFY_CERTIFICATE;
break;
default:
retval = KRB5KDC_ERR_INVALID_CERTIFICATE;
}
(void)oerr_cert(context, retval, cert_ctx,
_("Failed to verify received certificate"));
if (reqctx->received_cert == NULL)
strlcpy(buf, "(none)", sizeof(buf));
else
X509_NAME_oneline(X509_get_subject_name(reqctx->received_cert),
buf, sizeof(buf));
pkiDebug("problem with cert DN = %s (error=%d) %s\n", buf, j,
X509_verify_cert_error_string(j));
#ifdef DEBUG_CERTCHAIN
size = sk_X509_num(signerCerts);
pkiDebug("received cert chain of size %d\n", size);
for (j = 0; j < size; j++) {
X509 *tmp_cert = sk_X509_value(signerCerts, j);
X509_NAME_oneline(X509_get_subject_name(tmp_cert), buf, sizeof(buf));
pkiDebug("cert #%d: %s\n", j, buf);
}
#endif
} else {
/* retrieve verified certificate chain */
if (cms_msg_type == CMS_SIGN_CLIENT || cms_msg_type == CMS_SIGN_DRAFT9)
verified_chain = X509_STORE_CTX_get1_chain(cert_ctx);
}
X509_STORE_CTX_free(cert_ctx);
if (i <= 0)
goto cleanup;
out = BIO_new(BIO_s_mem());
if (cms_msg_type == CMS_SIGN_DRAFT9)
flags |= CMS_NOATTR;
if (CMS_verify(cms, NULL, store, NULL, out, flags) == 0) {
unsigned long err = ERR_peek_error();
switch(ERR_GET_REASON(err)) {
case PKCS7_R_DIGEST_FAILURE:
retval = KRB5KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED;
break;
case PKCS7_R_SIGNATURE_FAILURE:
default:
retval = KRB5KDC_ERR_INVALID_SIG;
}
(void)oerr(context, retval, _("Failed to verify CMS message"));
goto cleanup;
}
} /* message was signed */
if (!OBJ_cmp(etype, oid))
valid_oid = 1;
else if (cms_msg_type == CMS_SIGN_DRAFT9) {
/*
* Various implementations of the pa-type 15 request use
* different OIDS. We check that the returned object
* has any of the acceptable OIDs
*/
ASN1_OBJECT *client_oid = NULL, *server_oid = NULL, *rsa_oid = NULL;
client_oid = pkinit_pkcs7type2oid(plgctx, CMS_SIGN_CLIENT);
server_oid = pkinit_pkcs7type2oid(plgctx, CMS_SIGN_SERVER);
rsa_oid = pkinit_pkcs7type2oid(plgctx, CMS_ENVEL_SERVER);
if (!OBJ_cmp(etype, client_oid) ||
!OBJ_cmp(etype, server_oid) ||
!OBJ_cmp(etype, rsa_oid))
valid_oid = 1;
}
if (valid_oid)
pkiDebug("CMS Verification successful\n");
else {
pkiDebug("wrong oid in eContentType\n");
print_buffer(OBJ_get0_data(etype), OBJ_length(etype));
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval, "wrong oid\n");
goto cleanup;
}
/* transfer the data from CMS message into return buffer */
for (size = 0;;) {
int remain;
retval = ENOMEM;
if ((*data = realloc(*data, size + 1024 * 10)) == NULL)
goto cleanup;
remain = BIO_read(out, &((*data)[size]), 1024 * 10);
if (remain <= 0)
break;
else
size += remain;
}
*data_len = size;
if (x) {
reqctx->received_cert = X509_dup(x);
/* generate authorization data */
if (cms_msg_type == CMS_SIGN_CLIENT || cms_msg_type == CMS_SIGN_DRAFT9) {
if (authz_data == NULL || authz_data_len == NULL)
goto out;
*authz_data = NULL;
retval = create_identifiers_from_stack(verified_chain,
&krb5_verified_chain);
if (retval) {
pkiDebug("create_identifiers_from_stack failed\n");
goto cleanup;
}
retval = k5int_encode_krb5_td_trusted_certifiers((krb5_external_principal_identifier *const *)krb5_verified_chain, &authz);
if (retval) {
pkiDebug("encode_krb5_td_trusted_certifiers failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)authz->data, authz->length,
"/tmp/kdc_ad_initial_verified_cas");
#endif
*authz_data = malloc(authz->length);
if (*authz_data == NULL) {
retval = ENOMEM;
goto cleanup;
}
memcpy(*authz_data, authz->data, authz->length);
*authz_data_len = authz->length;
}
}
out:
retval = 0;
cleanup:
if (out != NULL)
BIO_free(out);
if (store != NULL)
X509_STORE_free(store);
if (cms != NULL) {
if (signerCerts != NULL)
pkinit_CMS_free1_certs(signerCerts);
if (idctx->intermediateCAs != NULL && signerCerts)
sk_X509_free(intermediateCAs);
if (signerRevoked != NULL)
pkinit_CMS_free1_crls(signerRevoked);
if (idctx->revoked != NULL && signerRevoked)
sk_X509_CRL_free(revoked);
CMS_ContentInfo_free(cms);
}
if (verified_chain != NULL)
sk_X509_pop_free(verified_chain, X509_free);
if (krb5_verified_chain != NULL)
free_krb5_external_principal_identifier(&krb5_verified_chain);
if (authz != NULL)
krb5_free_data(context, authz);
return retval;
}
krb5_error_code
cms_envelopeddata_create(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
pkinit_identity_crypto_context idctx,
krb5_preauthtype pa_type,
int include_certchain,
unsigned char *key_pack,
unsigned int key_pack_len,
unsigned char **out,
unsigned int *out_len)
{
krb5_error_code retval = ENOMEM;
PKCS7 *p7 = NULL;
BIO *in = NULL;
unsigned char *p = NULL, *signed_data = NULL, *enc_data = NULL;
int signed_data_len = 0, enc_data_len = 0, flags = PKCS7_BINARY;
STACK_OF(X509) *encerts = NULL;
const EVP_CIPHER *cipher = NULL;
int cms_msg_type;
/* create the PKCS7 SignedData portion of the PKCS7 EnvelopedData */
switch ((int)pa_type) {
case KRB5_PADATA_PK_AS_REQ_OLD:
case KRB5_PADATA_PK_AS_REP_OLD:
cms_msg_type = CMS_SIGN_DRAFT9;
break;
case KRB5_PADATA_PK_AS_REQ:
cms_msg_type = CMS_ENVEL_SERVER;
break;
default:
goto cleanup;
}
retval = cms_signeddata_create(context, plgctx, reqctx, idctx,
cms_msg_type, include_certchain, key_pack, key_pack_len,
&signed_data, (unsigned int *)&signed_data_len);
if (retval) {
pkiDebug("failed to create pkcs7 signed data\n");
goto cleanup;
}
/* check we have client's certificate */
if (reqctx->received_cert == NULL) {
retval = KRB5KDC_ERR_PREAUTH_FAILED;
goto cleanup;
}
encerts = sk_X509_new_null();
sk_X509_push(encerts, reqctx->received_cert);
cipher = EVP_des_ede3_cbc();
in = BIO_new(BIO_s_mem());
switch (pa_type) {
case KRB5_PADATA_PK_AS_REQ:
prepare_enc_data(signed_data, signed_data_len, &enc_data,
&enc_data_len);
retval = BIO_write(in, enc_data, enc_data_len);
if (retval != enc_data_len) {
pkiDebug("BIO_write only wrote %d\n", retval);
goto cleanup;
}
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = BIO_write(in, signed_data, signed_data_len);
if (retval != signed_data_len) {
pkiDebug("BIO_write only wrote %d\n", retval);
goto cleanup;
}
break;
default:
retval = -1;
goto cleanup;
}
p7 = PKCS7_encrypt(encerts, in, cipher, flags);
if (p7 == NULL) {
retval = oerr(context, 0, _("Failed to encrypt PKCS7 object"));
goto cleanup;
}
switch (pa_type) {
case KRB5_PADATA_PK_AS_REQ:
p7->d.enveloped->enc_data->content_type =
OBJ_nid2obj(NID_pkcs7_signed);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
p7->d.enveloped->enc_data->content_type =
OBJ_nid2obj(NID_pkcs7_data);
break;
break;
break;
break;
}
*out_len = i2d_PKCS7(p7, NULL);
if (!*out_len || (p = *out = malloc(*out_len)) == NULL) {
retval = ENOMEM;
goto cleanup;
}
retval = i2d_PKCS7(p7, &p);
if (!retval) {
retval = oerr(context, 0, _("Failed to DER encode PKCS7"));
goto cleanup;
}
retval = 0;
#ifdef DEBUG_ASN1
print_buffer_bin(*out, *out_len, "/tmp/kdc_enveloped_data");
#endif
cleanup:
if (p7 != NULL)
PKCS7_free(p7);
if (in != NULL)
BIO_free(in);
free(signed_data);
free(enc_data);
if (encerts != NULL)
sk_X509_free(encerts);
return retval;
}
krb5_error_code
cms_envelopeddata_verify(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_preauthtype pa_type,
int require_crl_checking,
unsigned char *enveloped_data,
unsigned int enveloped_data_len,
unsigned char **data,
unsigned int *data_len)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
PKCS7 *p7 = NULL;
BIO *out = NULL;
int i = 0;
unsigned int size = 0;
const unsigned char *p = enveloped_data;
unsigned int tmp_buf_len = 0, tmp_buf2_len = 0, vfy_buf_len = 0;
unsigned char *tmp_buf = NULL, *tmp_buf2 = NULL, *vfy_buf = NULL;
int msg_type = 0;
#ifdef DEBUG_ASN1
print_buffer_bin(enveloped_data, enveloped_data_len,
"/tmp/client_envelopeddata");
#endif
/* decode received PKCS7 message */
if ((p7 = d2i_PKCS7(NULL, &p, (int)enveloped_data_len)) == NULL) {
retval = oerr(context, 0, _("Failed to decode PKCS7"));
goto cleanup;
}
/* verify that the received message is PKCS7 EnvelopedData message */
if (OBJ_obj2nid(p7->type) != NID_pkcs7_enveloped) {
pkiDebug("Expected id-enveloped PKCS7 msg (received type = %d)\n",
OBJ_obj2nid(p7->type));
krb5_set_error_message(context, retval, "wrong oid\n");
goto cleanup;
}
/* decrypt received PKCS7 message */
out = BIO_new(BIO_s_mem());
if (pkcs7_decrypt(context, id_cryptoctx, p7, out)) {
pkiDebug("PKCS7 decryption successful\n");
} else {
retval = oerr(context, 0, _("Failed to decrypt PKCS7 message"));
goto cleanup;
}
/* transfer the decoded PKCS7 SignedData message into a separate buffer */
for (;;) {
if ((tmp_buf = realloc(tmp_buf, size + 1024 * 10)) == NULL)
goto cleanup;
i = BIO_read(out, &(tmp_buf[size]), 1024 * 10);
if (i <= 0)
break;
else
size += i;
}
tmp_buf_len = size;
#ifdef DEBUG_ASN1
print_buffer_bin(tmp_buf, tmp_buf_len, "/tmp/client_enc_keypack");
#endif
/* verify PKCS7 SignedData message */
switch (pa_type) {
case KRB5_PADATA_PK_AS_REP:
msg_type = CMS_ENVEL_SERVER;
break;
case KRB5_PADATA_PK_AS_REP_OLD:
msg_type = CMS_SIGN_DRAFT9;
break;
default:
pkiDebug("%s: unrecognized pa_type = %d\n", __FUNCTION__, pa_type);
retval = KRB5KDC_ERR_PREAUTH_FAILED;
goto cleanup;
}
/*
* If this is the RFC style, wrap the signed data to make
* decoding easier in the verify routine.
* For draft9-compatible, we don't do anything because it
* is already wrapped.
*/
if (msg_type == CMS_ENVEL_SERVER) {
retval = wrap_signeddata(tmp_buf, tmp_buf_len,
&tmp_buf2, &tmp_buf2_len);
if (retval) {
pkiDebug("failed to encode signeddata\n");
goto cleanup;
}
vfy_buf = tmp_buf2;
vfy_buf_len = tmp_buf2_len;
} else {
vfy_buf = tmp_buf;
vfy_buf_len = tmp_buf_len;
}
#ifdef DEBUG_ASN1
print_buffer_bin(vfy_buf, vfy_buf_len, "/tmp/client_enc_keypack2");
#endif
retval = cms_signeddata_verify(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx, msg_type,
require_crl_checking,
vfy_buf, vfy_buf_len,
data, data_len, NULL, NULL, NULL);
if (!retval)
pkiDebug("PKCS7 Verification Success\n");
else {
pkiDebug("PKCS7 Verification Failure\n");
goto cleanup;
}
retval = 0;
cleanup:
if (p7 != NULL)
PKCS7_free(p7);
if (out != NULL)
BIO_free(out);
free(tmp_buf);
free(tmp_buf2);
return retval;
}
static krb5_error_code
crypto_retrieve_X509_sans(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
X509 *cert,
krb5_principal **princs_ret,
krb5_principal **upn_ret,
unsigned char ***dns_ret)
{
krb5_error_code retval = EINVAL;
char buf[DN_BUF_LEN];
int p = 0, u = 0, d = 0, ret = 0, l;
krb5_principal *princs = NULL;
krb5_principal *upns = NULL;
unsigned char **dnss = NULL;
unsigned int i, num_found = 0, num_sans = 0;
X509_EXTENSION *ext = NULL;
GENERAL_NAMES *ialt = NULL;
GENERAL_NAME *gen = NULL;
if (princs_ret != NULL)
*princs_ret = NULL;
if (upn_ret != NULL)
*upn_ret = NULL;
if (dns_ret != NULL)
*dns_ret = NULL;
if (princs_ret == NULL && upn_ret == NULL && dns_ret == NULL) {
pkiDebug("%s: nowhere to return any values!\n", __FUNCTION__);
return retval;
}
if (cert == NULL) {
pkiDebug("%s: no certificate!\n", __FUNCTION__);
return retval;
}
X509_NAME_oneline(X509_get_subject_name(cert),
buf, sizeof(buf));
pkiDebug("%s: looking for SANs in cert = %s\n", __FUNCTION__, buf);
l = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
if (l < 0)
return 0;
if (!(ext = X509_get_ext(cert, l)) || !(ialt = X509V3_EXT_d2i(ext))) {
pkiDebug("%s: found no subject alt name extensions\n", __FUNCTION__);
goto cleanup;
}
num_sans = sk_GENERAL_NAME_num(ialt);
pkiDebug("%s: found %d subject alt name extension(s)\n", __FUNCTION__,
num_sans);
/* OK, we're likely returning something. Allocate return values */
if (princs_ret != NULL) {
princs = calloc(num_sans + 1, sizeof(krb5_principal));
if (princs == NULL) {
retval = ENOMEM;
goto cleanup;
}
}
if (upn_ret != NULL) {
upns = calloc(num_sans + 1, sizeof(krb5_principal));
if (upns == NULL) {
retval = ENOMEM;
goto cleanup;
}
}
if (dns_ret != NULL) {
dnss = calloc(num_sans + 1, sizeof(*dnss));
if (dnss == NULL) {
retval = ENOMEM;
goto cleanup;
}
}
for (i = 0; i < num_sans; i++) {
krb5_data name = { 0, 0, NULL };
gen = sk_GENERAL_NAME_value(ialt, i);
switch (gen->type) {
case GEN_OTHERNAME:
name.length = gen->d.otherName->value->value.sequence->length;
name.data = (char *)gen->d.otherName->value->value.sequence->data;
if (princs != NULL &&
OBJ_cmp(plgctx->id_pkinit_san,
gen->d.otherName->type_id) == 0) {
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)name.data, name.length,
"/tmp/pkinit_san");
#endif
ret = k5int_decode_krb5_principal_name(&name, &princs[p]);
if (ret) {
pkiDebug("%s: failed decoding pkinit san value\n",
__FUNCTION__);
} else {
p++;
num_found++;
}
} else if (upns != NULL &&
OBJ_cmp(plgctx->id_ms_san_upn,
gen->d.otherName->type_id) == 0) {
/* Prevent abuse of embedded null characters. */
if (memchr(name.data, '\0', name.length))
break;
ret = krb5_parse_name_flags(context, name.data,
KRB5_PRINCIPAL_PARSE_ENTERPRISE,
&upns[u]);
if (ret) {
pkiDebug("%s: failed parsing ms-upn san value\n",
__FUNCTION__);
} else {
u++;
num_found++;
}
} else {
pkiDebug("%s: unrecognized othername oid in SAN\n",
__FUNCTION__);
continue;
}
break;
case GEN_DNS:
if (dnss != NULL) {
/* Prevent abuse of embedded null characters. */
if (memchr(gen->d.dNSName->data, '\0', gen->d.dNSName->length))
break;
pkiDebug("%s: found dns name = %s\n", __FUNCTION__,
gen->d.dNSName->data);
dnss[d] = (unsigned char *)
strdup((char *)gen->d.dNSName->data);
if (dnss[d] == NULL) {
pkiDebug("%s: failed to duplicate dns name\n",
__FUNCTION__);
} else {
d++;
num_found++;
}
}
break;
default:
pkiDebug("%s: SAN type = %d expecting %d\n", __FUNCTION__,
gen->type, GEN_OTHERNAME);
}
}
sk_GENERAL_NAME_pop_free(ialt, GENERAL_NAME_free);
retval = 0;
if (princs != NULL && *princs != NULL) {
*princs_ret = princs;
princs = NULL;
}
if (upns != NULL && *upns != NULL) {
*upn_ret = upns;
upns = NULL;
}
if (dnss != NULL && *dnss != NULL) {
*dns_ret = dnss;
dnss = NULL;
}
cleanup:
for (i = 0; princs != NULL && princs[i] != NULL; i++)
krb5_free_principal(context, princs[i]);
free(princs);
for (i = 0; upns != NULL && upns[i] != NULL; i++)
krb5_free_principal(context, upns[i]);
free(upns);
for (i = 0; dnss != NULL && dnss[i] != NULL; i++)
free(dnss[i]);
free(dnss);
return retval;
}
krb5_error_code
crypto_retrieve_signer_identity(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
const char **identity)
{
*identity = id_cryptoctx->identity;
if (*identity == NULL)
return ENOENT;
return 0;
}
krb5_error_code
crypto_retrieve_cert_sans(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
pkinit_identity_crypto_context idctx,
krb5_principal **princs_ret,
krb5_principal **upn_ret,
unsigned char ***dns_ret)
{
krb5_error_code retval = EINVAL;
if (reqctx->received_cert == NULL) {
pkiDebug("%s: No certificate!\n", __FUNCTION__);
return retval;
}
return crypto_retrieve_X509_sans(context, plgctx, reqctx,
reqctx->received_cert, princs_ret,
upn_ret, dns_ret);
}
krb5_error_code
crypto_check_cert_eku(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
pkinit_identity_crypto_context idctx,
int checking_kdc_cert,
int allow_secondary_usage,
int *valid_eku)
{
char buf[DN_BUF_LEN];
int found_eku = 0;
krb5_error_code retval = EINVAL;
int i;
*valid_eku = 0;
if (reqctx->received_cert == NULL)
goto cleanup;
X509_NAME_oneline(X509_get_subject_name(reqctx->received_cert),
buf, sizeof(buf));
if ((i = X509_get_ext_by_NID(reqctx->received_cert,
NID_ext_key_usage, -1)) >= 0) {
EXTENDED_KEY_USAGE *extusage;
extusage = X509_get_ext_d2i(reqctx->received_cert, NID_ext_key_usage,
NULL, NULL);
if (extusage) {
pkiDebug("%s: found eku info in the cert\n", __FUNCTION__);
for (i = 0; found_eku == 0 && i < sk_ASN1_OBJECT_num(extusage); i++) {
ASN1_OBJECT *tmp_oid;
tmp_oid = sk_ASN1_OBJECT_value(extusage, i);
pkiDebug("%s: checking eku %d of %d, allow_secondary = %d\n",
__FUNCTION__, i+1, sk_ASN1_OBJECT_num(extusage),
allow_secondary_usage);
if (checking_kdc_cert) {
if ((OBJ_cmp(tmp_oid, plgctx->id_pkinit_KPKdc) == 0)
|| (allow_secondary_usage
&& OBJ_cmp(tmp_oid, plgctx->id_kp_serverAuth) == 0))
found_eku = 1;
} else {
if ((OBJ_cmp(tmp_oid, plgctx->id_pkinit_KPClientAuth) == 0)
|| (allow_secondary_usage
&& OBJ_cmp(tmp_oid, plgctx->id_ms_kp_sc_logon) == 0))
found_eku = 1;
}
}
}
EXTENDED_KEY_USAGE_free(extusage);
if (found_eku) {
ASN1_BIT_STRING *usage = NULL;
/* check that digitalSignature KeyUsage is present */
X509_check_ca(reqctx->received_cert);
if ((usage = X509_get_ext_d2i(reqctx->received_cert,
NID_key_usage, NULL, NULL))) {
if (!ku_reject(reqctx->received_cert,
X509v3_KU_DIGITAL_SIGNATURE)) {
TRACE_PKINIT_EKU(context);
*valid_eku = 1;
} else
TRACE_PKINIT_EKU_NO_KU(context);
}
ASN1_BIT_STRING_free(usage);
}
}
retval = 0;
cleanup:
pkiDebug("%s: returning retval %d, valid_eku %d\n",
__FUNCTION__, retval, *valid_eku);
return retval;
}
krb5_error_code
pkinit_octetstring2key(krb5_context context,
krb5_enctype etype,
unsigned char *key,
unsigned int dh_key_len,
krb5_keyblock *key_block)
{
krb5_error_code retval;
unsigned char *buf = NULL;
unsigned char md[SHA_DIGEST_LENGTH];
unsigned char counter;
size_t keybytes, keylength, offset;
krb5_data random_data;
if ((buf = malloc(dh_key_len)) == NULL) {
retval = ENOMEM;
goto cleanup;
}
memset(buf, 0, dh_key_len);
counter = 0;
offset = 0;
do {
SHA_CTX c;
SHA1_Init(&c);
SHA1_Update(&c, &counter, 1);
SHA1_Update(&c, key, dh_key_len);
SHA1_Final(md, &c);
if (dh_key_len - offset < sizeof(md))
memcpy(buf + offset, md, dh_key_len - offset);
else
memcpy(buf + offset, md, sizeof(md));
offset += sizeof(md);
counter++;
} while (offset < dh_key_len);
key_block->magic = 0;
key_block->enctype = etype;
retval = krb5_c_keylengths(context, etype, &keybytes, &keylength);
if (retval)
goto cleanup;
key_block->length = keylength;
key_block->contents = malloc(keylength);
if (key_block->contents == NULL) {
retval = ENOMEM;
goto cleanup;
}
random_data.length = keybytes;
random_data.data = (char *)buf;
retval = krb5_c_random_to_key(context, etype, &random_data, key_block);
cleanup:
free(buf);
/* If this is an error return, free the allocated keyblock, if any */
if (retval) {
krb5_free_keyblock_contents(context, key_block);
}
return retval;
}
/**
* Given an algorithm_identifier, this function returns the hash length
* and EVP function associated with that algorithm.
*/
static krb5_error_code
pkinit_alg_values(krb5_context context,
const krb5_data *alg_id,
size_t *hash_bytes,
const EVP_MD *(**func)(void))
{
*hash_bytes = 0;
*func = NULL;
if ((alg_id->length == krb5_pkinit_sha1_oid_len) &&
(0 == memcmp(alg_id->data, &krb5_pkinit_sha1_oid,
krb5_pkinit_sha1_oid_len))) {
*hash_bytes = 20;
*func = &EVP_sha1;
return 0;
} else if ((alg_id->length == krb5_pkinit_sha256_oid_len) &&
(0 == memcmp(alg_id->data, krb5_pkinit_sha256_oid,
krb5_pkinit_sha256_oid_len))) {
*hash_bytes = 32;
*func = &EVP_sha256;
return 0;
} else if ((alg_id->length == krb5_pkinit_sha512_oid_len) &&
(0 == memcmp(alg_id->data, krb5_pkinit_sha512_oid,
krb5_pkinit_sha512_oid_len))) {
*hash_bytes = 64;
*func = &EVP_sha512;
return 0;
} else {
krb5_set_error_message(context, KRB5_ERR_BAD_S2K_PARAMS,
"Bad algorithm ID passed to PK-INIT KDF.");
return KRB5_ERR_BAD_S2K_PARAMS;
}
} /* pkinit_alg_values() */
/* pkinit_alg_agility_kdf() --
* This function generates a key using the KDF described in
* draft_ietf_krb_wg_pkinit_alg_agility-04.txt. The algorithm is
* described as follows:
*
* 1. reps = keydatalen (K) / hash length (H)
*
* 2. Initialize a 32-bit, big-endian bit string counter as 1.
*
* 3. For i = 1 to reps by 1, do the following:
*
* - Compute Hashi = H(counter || Z || OtherInfo).
*
* - Increment counter (modulo 2^32)
*
* 4. Set key = Hash1 || Hash2 || ... so that length of key is K bytes.
*/
krb5_error_code
pkinit_alg_agility_kdf(krb5_context context,
krb5_data *secret,
krb5_data *alg_oid,
krb5_const_principal party_u_info,
krb5_const_principal party_v_info,
krb5_enctype enctype,
krb5_data *as_req,
krb5_data *pk_as_rep,
krb5_keyblock *key_block)
{
krb5_error_code retval = 0;
unsigned int reps = 0;
uint32_t counter = 1; /* Does this type work on Windows? */
size_t offset = 0;
size_t hash_len = 0;
size_t rand_len = 0;
size_t key_len = 0;
krb5_data random_data;
krb5_sp80056a_other_info other_info_fields;
krb5_pkinit_supp_pub_info supp_pub_info_fields;
krb5_data *other_info = NULL;
krb5_data *supp_pub_info = NULL;
krb5_algorithm_identifier alg_id;
EVP_MD_CTX *ctx = NULL;
const EVP_MD *(*EVP_func)(void);
/* initialize random_data here to make clean-up safe */
random_data.length = 0;
random_data.data = NULL;
/* allocate and initialize the key block */
key_block->magic = 0;
key_block->enctype = enctype;
if (0 != (retval = krb5_c_keylengths(context, enctype, &rand_len,
&key_len)))
goto cleanup;
random_data.length = rand_len;
key_block->length = key_len;
if (NULL == (key_block->contents = malloc(key_block->length))) {
retval = ENOMEM;
goto cleanup;
}
memset (key_block->contents, 0, key_block->length);
/* If this is anonymous pkinit, use the anonymous principle for party_u_info */
if (party_u_info && krb5_principal_compare_any_realm(context, party_u_info,
krb5_anonymous_principal()))
party_u_info = (krb5_principal)krb5_anonymous_principal();
if (0 != (retval = pkinit_alg_values(context, alg_oid, &hash_len, &EVP_func)))
goto cleanup;
/* 1. reps = keydatalen (K) / hash length (H) */
reps = key_block->length/hash_len;
/* ... and round up, if necessary */
if (key_block->length > (reps * hash_len))
reps++;
/* Allocate enough space in the random data buffer to hash directly into
* it, even if the last hash will make it bigger than the key length. */
if (NULL == (random_data.data = malloc(reps * hash_len))) {
retval = ENOMEM;
goto cleanup;
}
/* Encode the ASN.1 octet string for "SuppPubInfo" */
supp_pub_info_fields.enctype = enctype;
supp_pub_info_fields.as_req = *as_req;
supp_pub_info_fields.pk_as_rep = *pk_as_rep;
if (0 != ((retval = encode_krb5_pkinit_supp_pub_info(&supp_pub_info_fields,
&supp_pub_info))))
goto cleanup;
/* Now encode the ASN.1 octet string for "OtherInfo" */
memset(&alg_id, 0, sizeof alg_id);
alg_id.algorithm = *alg_oid; /*alias*/
other_info_fields.algorithm_identifier = alg_id;
other_info_fields.party_u_info = (krb5_principal) party_u_info;
other_info_fields.party_v_info = (krb5_principal) party_v_info;
other_info_fields.supp_pub_info = *supp_pub_info;
if (0 != (retval = encode_krb5_sp80056a_other_info(&other_info_fields, &other_info)))
goto cleanup;
/* 2. Initialize a 32-bit, big-endian bit string counter as 1.
* 3. For i = 1 to reps by 1, do the following:
* - Compute Hashi = H(counter || Z || OtherInfo).
* - Increment counter (modulo 2^32)
*/
for (counter = 1; counter <= reps; counter++) {
uint s = 0;
uint32_t be_counter = htonl(counter);
ctx = EVP_MD_CTX_new();
if (ctx == NULL) {
retval = KRB5_CRYPTO_INTERNAL;
goto cleanup;
}
/* - Compute Hashi = H(counter || Z || OtherInfo). */
if (!EVP_DigestInit(ctx, EVP_func())) {
krb5_set_error_message(context, KRB5_CRYPTO_INTERNAL,
"Call to OpenSSL EVP_DigestInit() returned an error.");
retval = KRB5_CRYPTO_INTERNAL;
goto cleanup;
}
if (!EVP_DigestUpdate(ctx, &be_counter, 4) ||
!EVP_DigestUpdate(ctx, secret->data, secret->length) ||
!EVP_DigestUpdate(ctx, other_info->data, other_info->length)) {
krb5_set_error_message(context, KRB5_CRYPTO_INTERNAL,
"Call to OpenSSL EVP_DigestUpdate() returned an error.");
retval = KRB5_CRYPTO_INTERNAL;
goto cleanup;
}
/* 4. Set key = Hash1 || Hash2 || ... so that length of key is K bytes. */
if (!EVP_DigestFinal(ctx, (uint8_t *)random_data.data + offset, &s)) {
krb5_set_error_message(context, KRB5_CRYPTO_INTERNAL,
"Call to OpenSSL EVP_DigestUpdate() returned an error.");
retval = KRB5_CRYPTO_INTERNAL;
goto cleanup;
}
offset += s;
assert(s == hash_len);
EVP_MD_CTX_free(ctx);
ctx = NULL;
}
retval = krb5_c_random_to_key(context, enctype, &random_data,
key_block);
cleanup:
EVP_MD_CTX_free(ctx);
/* If this has been an error, free the allocated key_block, if any */
if (retval) {
krb5_free_keyblock_contents(context, key_block);
}
/* free other allocated resources, either way */
if (random_data.data)
free(random_data.data);
krb5_free_data(context, other_info);
krb5_free_data(context, supp_pub_info);
return retval;
} /*pkinit_alg_agility_kdf() */
/* Call DH_compute_key() and ensure that we left-pad short results instead of
* leaving junk bytes at the end of the buffer. */
static void
compute_dh(unsigned char *buf, int size, BIGNUM *server_pub_key, DH *dh)
{
int len, pad;
len = DH_compute_key(buf, server_pub_key, dh);
assert(len >= 0 && len <= size);
if (len < size) {
pad = size - len;
memmove(buf + pad, buf, len);
memset(buf, 0, pad);
}
}
krb5_error_code
client_create_dh(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int dh_size,
unsigned char **dh_params,
unsigned int *dh_params_len,
unsigned char **dh_pubkey,
unsigned int *dh_pubkey_len)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
unsigned char *buf = NULL;
int dh_err = 0;
ASN1_INTEGER *pub_key = NULL;
const BIGNUM *pubkey_bn, *p, *q, *g;
if (cryptoctx->dh == NULL) {
if (dh_size == 1024)
cryptoctx->dh = make_oakley_dh(oakley_1024, sizeof(oakley_1024));
else if (dh_size == 2048)
cryptoctx->dh = make_oakley_dh(oakley_2048, sizeof(oakley_2048));
else if (dh_size == 4096)
cryptoctx->dh = make_oakley_dh(oakley_4096, sizeof(oakley_4096));
if (cryptoctx->dh == NULL)
goto cleanup;
}
DH_generate_key(cryptoctx->dh);
DH_get0_key(cryptoctx->dh, &pubkey_bn, NULL);
DH_check(cryptoctx->dh, &dh_err);
if (dh_err != 0) {
pkiDebug("Warning: dh_check failed with %d\n", dh_err);
if (dh_err & DH_CHECK_P_NOT_PRIME)
pkiDebug("p value is not prime\n");
if (dh_err & DH_CHECK_P_NOT_SAFE_PRIME)
pkiDebug("p value is not a safe prime\n");
if (dh_err & DH_UNABLE_TO_CHECK_GENERATOR)
pkiDebug("unable to check the generator value\n");
if (dh_err & DH_NOT_SUITABLE_GENERATOR)
pkiDebug("the g value is not a generator\n");
}
#ifdef DEBUG_DH
print_dh(cryptoctx->dh, "client's DH params\n");
print_pubkey(cryptoctx->dh->pub_key, "client's pub_key=");
#endif
DH_check_pub_key(cryptoctx->dh, pubkey_bn, &dh_err);
if (dh_err != 0) {
pkiDebug("dh_check_pub_key failed with %d\n", dh_err);
goto cleanup;
}
/* pack DHparams */
/* aglo: usually we could just call i2d_DHparams to encode DH params
* however, PKINIT requires RFC3279 encoding and openssl does pkcs#3.
*/
DH_get0_pqg(cryptoctx->dh, &p, &q, &g);
retval = pkinit_encode_dh_params(p, g, q, dh_params, dh_params_len);
if (retval)
goto cleanup;
/* pack DH public key */
/* Diffie-Hellman public key must be ASN1 encoded as an INTEGER; this
* encoding shall be used as the contents (the value) of the
* subjectPublicKey component (a BIT STRING) of the SubjectPublicKeyInfo
* data element
*/
pub_key = BN_to_ASN1_INTEGER(pubkey_bn, NULL);
if (pub_key == NULL) {
retval = ENOMEM;
goto cleanup;
}
*dh_pubkey_len = i2d_ASN1_INTEGER(pub_key, NULL);
if ((buf = *dh_pubkey = malloc(*dh_pubkey_len)) == NULL) {
retval = ENOMEM;
goto cleanup;
}
i2d_ASN1_INTEGER(pub_key, &buf);
if (pub_key != NULL)
ASN1_INTEGER_free(pub_key);
retval = 0;
return retval;
cleanup:
if (cryptoctx->dh != NULL)
DH_free(cryptoctx->dh);
cryptoctx->dh = NULL;
free(*dh_params);
*dh_params = NULL;
free(*dh_pubkey);
*dh_pubkey = NULL;
if (pub_key != NULL)
ASN1_INTEGER_free(pub_key);
return retval;
}
krb5_error_code
client_process_dh(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *subjectPublicKey_data,
unsigned int subjectPublicKey_length,
unsigned char **client_key,
unsigned int *client_key_len)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
BIGNUM *server_pub_key = NULL;
ASN1_INTEGER *pub_key = NULL;
const unsigned char *p = NULL;
*client_key_len = DH_size(cryptoctx->dh);
if ((*client_key = malloc(*client_key_len)) == NULL) {
retval = ENOMEM;
goto cleanup;
}
p = subjectPublicKey_data;
pub_key = d2i_ASN1_INTEGER(NULL, &p, (long)subjectPublicKey_length);
if (pub_key == NULL)
goto cleanup;
if ((server_pub_key = ASN1_INTEGER_to_BN(pub_key, NULL)) == NULL)
goto cleanup;
compute_dh(*client_key, *client_key_len, server_pub_key, cryptoctx->dh);
#ifdef DEBUG_DH
print_pubkey(server_pub_key, "server's pub_key=");
pkiDebug("client computed key (%d)= ", *client_key_len);
print_buffer(*client_key, *client_key_len);
#endif
retval = 0;
if (server_pub_key != NULL)
BN_free(server_pub_key);
if (pub_key != NULL)
ASN1_INTEGER_free(pub_key);
return retval;
cleanup:
free(*client_key);
*client_key = NULL;
if (pub_key != NULL)
ASN1_INTEGER_free(pub_key);
return retval;
}
/* Return 1 if dh is a permitted well-known group, otherwise return 0. */
static int
check_dh_wellknown(pkinit_plg_crypto_context cryptoctx, DH *dh, int nbits)
{
switch (nbits) {
case 1024:
/* Oakley MODP group 2 */
if (pkinit_check_dh_params(cryptoctx->dh_1024, dh) == 0)
return 1;
break;
case 2048:
/* Oakley MODP group 14 */
if (pkinit_check_dh_params(cryptoctx->dh_2048, dh) == 0)
return 1;
break;
case 4096:
/* Oakley MODP group 16 */
if (pkinit_check_dh_params(cryptoctx->dh_4096, dh) == 0)
return 1;
break;
default:
break;
}
return 0;
}
krb5_error_code
server_check_dh(krb5_context context,
pkinit_plg_crypto_context cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_data *dh_params,
int minbits)
{
DH *dh = NULL;
const BIGNUM *p;
int dh_prime_bits;
krb5_error_code retval = KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
dh = decode_dh_params((uint8_t *)dh_params->data, dh_params->length);
if (dh == NULL) {
pkiDebug("failed to decode dhparams\n");
goto cleanup;
}
/* KDC SHOULD check to see if the key parameters satisfy its policy */
DH_get0_pqg(dh, &p, NULL, NULL);
dh_prime_bits = BN_num_bits(p);
if (minbits && dh_prime_bits < minbits) {
pkiDebug("client sent dh params with %d bits, we require %d\n",
dh_prime_bits, minbits);
goto cleanup;
}
if (check_dh_wellknown(cryptoctx, dh, dh_prime_bits))
retval = 0;
cleanup:
if (retval == 0)
req_cryptoctx->dh = dh;
else
DH_free(dh);
return retval;
}
/* Duplicate a DH handle (parameters only, not public or private key). */
static DH *
dup_dh_params(const DH *src)
{
const BIGNUM *oldp, *oldq, *oldg;
BIGNUM *p = NULL, *q = NULL, *g = NULL;
DH *dh;
DH_get0_pqg(src, &oldp, &oldq, &oldg);
p = BN_dup(oldp);
q = BN_dup(oldq);
g = BN_dup(oldg);
dh = DH_new();
if (p == NULL || q == NULL || g == NULL || dh == NULL) {
BN_free(p);
BN_free(q);
BN_free(g);
DH_free(dh);
return NULL;
}
DH_set0_pqg(dh, p, q, g);
return dh;
}
/* kdc's dh function */
krb5_error_code
server_process_dh(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data,
unsigned int data_len,
unsigned char **dh_pubkey,
unsigned int *dh_pubkey_len,
unsigned char **server_key,
unsigned int *server_key_len)
{
krb5_error_code retval = ENOMEM;
DH *dh = NULL, *dh_server = NULL;
unsigned char *p = NULL;
ASN1_INTEGER *pub_key = NULL;
BIGNUM *client_pubkey = NULL;
const BIGNUM *server_pubkey;
*dh_pubkey = *server_key = NULL;
*dh_pubkey_len = *server_key_len = 0;
/* get client's received DH parameters that we saved in server_check_dh */
dh = cryptoctx->dh;
dh_server = dup_dh_params(dh);
if (dh_server == NULL)
goto cleanup;
/* decode client's public key */
p = data;
pub_key = d2i_ASN1_INTEGER(NULL, (const unsigned char **)&p, (int)data_len);
if (pub_key == NULL)
goto cleanup;
client_pubkey = ASN1_INTEGER_to_BN(pub_key, NULL);
if (client_pubkey == NULL)
goto cleanup;
ASN1_INTEGER_free(pub_key);
if (!DH_generate_key(dh_server))
goto cleanup;
DH_get0_key(dh_server, &server_pubkey, NULL);
/* generate DH session key */
*server_key_len = DH_size(dh_server);
if ((*server_key = malloc(*server_key_len)) == NULL)
goto cleanup;
compute_dh(*server_key, *server_key_len, client_pubkey, dh_server);
#ifdef DEBUG_DH
print_dh(dh_server, "client&server's DH params\n");
print_pubkey(client_pubkey, "client's pub_key=");
print_pubkey(server_pubkey, "server's pub_key=");
pkiDebug("server computed key=");
print_buffer(*server_key, *server_key_len);
#endif
/* KDC reply */
/* pack DH public key */
/* Diffie-Hellman public key must be ASN1 encoded as an INTEGER; this
* encoding shall be used as the contents (the value) of the
* subjectPublicKey component (a BIT STRING) of the SubjectPublicKeyInfo
* data element
*/
pub_key = BN_to_ASN1_INTEGER(server_pubkey, NULL);
if (pub_key == NULL)
goto cleanup;
*dh_pubkey_len = i2d_ASN1_INTEGER(pub_key, NULL);
if ((p = *dh_pubkey = malloc(*dh_pubkey_len)) == NULL)
goto cleanup;
i2d_ASN1_INTEGER(pub_key, &p);
if (pub_key != NULL)
ASN1_INTEGER_free(pub_key);
retval = 0;
if (dh_server != NULL)
DH_free(dh_server);
return retval;
cleanup:
BN_free(client_pubkey);
DH_free(dh_server);
free(*dh_pubkey);
free(*server_key);
return retval;
}
int
pkinit_openssl_init()
{
/* Initialize OpenSSL. */
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
return 0;
}
static krb5_error_code
pkinit_encode_dh_params(const BIGNUM *p, const BIGNUM *g, const BIGNUM *q,
uint8_t **buf, unsigned int *buf_len)
{
krb5_error_code retval = ENOMEM;
int bufsize = 0, r = 0;
unsigned char *tmp = NULL;
ASN1_INTEGER *ap = NULL, *ag = NULL, *aq = NULL;
if ((ap = BN_to_ASN1_INTEGER(p, NULL)) == NULL)
goto cleanup;
if ((ag = BN_to_ASN1_INTEGER(g, NULL)) == NULL)
goto cleanup;
if ((aq = BN_to_ASN1_INTEGER(q, NULL)) == NULL)
goto cleanup;
bufsize = i2d_ASN1_INTEGER(ap, NULL);
bufsize += i2d_ASN1_INTEGER(ag, NULL);
bufsize += i2d_ASN1_INTEGER(aq, NULL);
r = ASN1_object_size(1, bufsize, V_ASN1_SEQUENCE);
tmp = *buf = malloc((size_t) r);
if (tmp == NULL)
goto cleanup;
ASN1_put_object(&tmp, 1, bufsize, V_ASN1_SEQUENCE, V_ASN1_UNIVERSAL);
i2d_ASN1_INTEGER(ap, &tmp);
i2d_ASN1_INTEGER(ag, &tmp);
i2d_ASN1_INTEGER(aq, &tmp);
*buf_len = r;
retval = 0;
cleanup:
if (ap != NULL)
ASN1_INTEGER_free(ap);
if (ag != NULL)
ASN1_INTEGER_free(ag);
if (aq != NULL)
ASN1_INTEGER_free(aq);
return retval;
}
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
/*
* We need to decode DomainParameters from RFC 3279 section 2.3.3. We would
* like to just call d2i_DHxparams(), but Microsoft's implementation may omit
* the q value in violation of the RFC. Instead we must copy the internal
* structures and sequence declarations from dh_asn1.c, modified to make the q
* field optional.
*/
typedef struct {
ASN1_BIT_STRING *seed;
BIGNUM *counter;
} int_dhvparams;
typedef struct {
BIGNUM *p;
BIGNUM *q;
BIGNUM *g;
BIGNUM *j;
int_dhvparams *vparams;
} int_dhx942_dh;
ASN1_SEQUENCE(DHvparams) = {
ASN1_SIMPLE(int_dhvparams, seed, ASN1_BIT_STRING),
ASN1_SIMPLE(int_dhvparams, counter, BIGNUM)
} static_ASN1_SEQUENCE_END_name(int_dhvparams, DHvparams)
ASN1_SEQUENCE(DHxparams) = {
ASN1_SIMPLE(int_dhx942_dh, p, BIGNUM),
ASN1_SIMPLE(int_dhx942_dh, g, BIGNUM),
ASN1_OPT(int_dhx942_dh, q, BIGNUM),
ASN1_OPT(int_dhx942_dh, j, BIGNUM),
ASN1_OPT(int_dhx942_dh, vparams, DHvparams),
} static_ASN1_SEQUENCE_END_name(int_dhx942_dh, DHxparams)
static DH *
decode_dh_params(const uint8_t *p, unsigned int len)
{
int_dhx942_dh *params;
DH *dh;
dh = DH_new();
if (dh == NULL)
return NULL;
params = (int_dhx942_dh *)ASN1_item_d2i(NULL, &p, len,
ASN1_ITEM_rptr(DHxparams));
if (params == NULL) {
DH_free(dh);
return NULL;
}
/* Steal the p, q, and g values from dhparams for dh. Ignore j and
* vparams. */
DH_set0_pqg(dh, params->p, params->q, params->g);
params->p = params->q = params->g = NULL;
ASN1_item_free((ASN1_VALUE *)params, ASN1_ITEM_rptr(DHxparams));
return dh;
}
#else /* OPENSSL_VERSION_NUMBER < 0x10100000L */
/*
* Do the same decoding (except without decoding j and vparams or checking the
* sequence length) using the pre-OpenSSL-1.1 asn1_mac.h. Define an internal
* function in the form demanded by the macros, then wrap it for caller
* convenience.
*/
static DH *
decode_dh_params_int(DH ** a, uint8_t **pp, unsigned int len)
{
ASN1_INTEGER ai, *aip = NULL;
long length = (long) len;
M_ASN1_D2I_vars(a, DH *, DH_new);
M_ASN1_D2I_Init();
M_ASN1_D2I_start_sequence();
aip = &ai;
ai.data = NULL;
ai.length = 0;
M_ASN1_D2I_get_x(ASN1_INTEGER, aip, d2i_ASN1_INTEGER);
if (aip == NULL)
return NULL;
else {
ret->p = ASN1_INTEGER_to_BN(aip, NULL);
if (ret->p == NULL)
return NULL;
if (ai.data != NULL) {
OPENSSL_free(ai.data);
ai.data = NULL;
ai.length = 0;
}
}
M_ASN1_D2I_get_x(ASN1_INTEGER, aip, d2i_ASN1_INTEGER);
if (aip == NULL)
return NULL;
else {
ret->g = ASN1_INTEGER_to_BN(aip, NULL);
if (ret->g == NULL)
return NULL;
if (ai.data != NULL) {
OPENSSL_free(ai.data);
ai.data = NULL;
ai.length = 0;
}
}
M_ASN1_D2I_get_opt(aip, d2i_ASN1_INTEGER, V_ASN1_INTEGER);
if (aip == NULL || ai.data == NULL)
ret->q = NULL;
else {
ret->q = ASN1_INTEGER_to_BN(aip, NULL);
if (ret->q == NULL)
return NULL;
if (ai.data != NULL) {
OPENSSL_free(ai.data);
ai.data = NULL;
ai.length = 0;
}
}
M_ASN1_D2I_end_sequence();
M_ASN1_D2I_Finish(a, DH_free, 0);
}
static DH *
decode_dh_params(const uint8_t *p, unsigned int len)
{
uint8_t *ptr = (uint8_t *)p;
return decode_dh_params_int(NULL, &ptr, len);
}
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
static krb5_error_code
pkinit_create_sequence_of_principal_identifiers(
krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int type,
krb5_pa_data ***e_data_out)
{
krb5_error_code retval = KRB5KRB_ERR_GENERIC;
krb5_external_principal_identifier **krb5_trusted_certifiers = NULL;
krb5_data *td_certifiers = NULL;
krb5_pa_data **pa_data = NULL;
switch(type) {
case TD_TRUSTED_CERTIFIERS:
retval = create_krb5_trustedCertifiers(context, plg_cryptoctx,
req_cryptoctx, id_cryptoctx, &krb5_trusted_certifiers);
if (retval) {
pkiDebug("create_krb5_trustedCertifiers failed\n");
goto cleanup;
}
break;
case TD_INVALID_CERTIFICATES:
retval = create_krb5_invalidCertificates(context, plg_cryptoctx,
req_cryptoctx, id_cryptoctx, &krb5_trusted_certifiers);
if (retval) {
pkiDebug("create_krb5_invalidCertificates failed\n");
goto cleanup;
}
break;
default:
retval = -1;
goto cleanup;
}
retval = k5int_encode_krb5_td_trusted_certifiers((krb5_external_principal_identifier *const *)krb5_trusted_certifiers, &td_certifiers);
if (retval) {
pkiDebug("encode_krb5_td_trusted_certifiers failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)td_certifiers->data,
td_certifiers->length, "/tmp/kdc_td_certifiers");
#endif
pa_data = malloc(2 * sizeof(krb5_pa_data *));
if (pa_data == NULL) {
retval = ENOMEM;
goto cleanup;
}
pa_data[1] = NULL;
pa_data[0] = malloc(sizeof(krb5_pa_data));
if (pa_data[0] == NULL) {
free(pa_data);
retval = ENOMEM;
goto cleanup;
}
pa_data[0]->pa_type = type;
pa_data[0]->length = td_certifiers->length;
pa_data[0]->contents = (krb5_octet *)td_certifiers->data;
*e_data_out = pa_data;
retval = 0;
cleanup:
if (krb5_trusted_certifiers != NULL)
free_krb5_external_principal_identifier(&krb5_trusted_certifiers);
free(td_certifiers);
return retval;
}
krb5_error_code
pkinit_create_td_trusted_certifiers(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_pa_data ***e_data_out)
{
krb5_error_code retval = KRB5KRB_ERR_GENERIC;
retval = pkinit_create_sequence_of_principal_identifiers(context,
plg_cryptoctx, req_cryptoctx, id_cryptoctx,
TD_TRUSTED_CERTIFIERS, e_data_out);
return retval;
}
krb5_error_code
pkinit_create_td_invalid_certificate(
krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_pa_data ***e_data_out)
{
krb5_error_code retval = KRB5KRB_ERR_GENERIC;
retval = pkinit_create_sequence_of_principal_identifiers(context,
plg_cryptoctx, req_cryptoctx, id_cryptoctx,
TD_INVALID_CERTIFICATES, e_data_out);
return retval;
}
krb5_error_code
pkinit_create_td_dh_parameters(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
pkinit_plg_opts *opts,
krb5_pa_data ***e_data_out)
{
krb5_error_code retval = ENOMEM;
unsigned int buf1_len = 0, buf2_len = 0, buf3_len = 0, i = 0;
unsigned char *buf1 = NULL, *buf2 = NULL, *buf3 = NULL;
krb5_pa_data **pa_data = NULL;
krb5_data *encoded_algId = NULL;
krb5_algorithm_identifier **algId = NULL;
const BIGNUM *p, *q, *g;
if (opts->dh_min_bits > 4096)
goto cleanup;
if (opts->dh_min_bits <= 1024) {
DH_get0_pqg(plg_cryptoctx->dh_1024, &p, &q, &g);
retval = pkinit_encode_dh_params(p, g, q, &buf1, &buf1_len);
if (retval)
goto cleanup;
}
if (opts->dh_min_bits <= 2048) {
DH_get0_pqg(plg_cryptoctx->dh_2048, &p, &q, &g);
retval = pkinit_encode_dh_params(p, g, q, &buf2, &buf2_len);
if (retval)
goto cleanup;
}
DH_get0_pqg(plg_cryptoctx->dh_4096, &p, &q, &g);
retval = pkinit_encode_dh_params(p, g, q, &buf3, &buf3_len);
if (retval)
goto cleanup;
if (opts->dh_min_bits <= 1024) {
algId = malloc(4 * sizeof(krb5_algorithm_identifier *));
if (algId == NULL)
goto cleanup;
algId[3] = NULL;
algId[0] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[0] == NULL)
goto cleanup;
algId[0]->parameters.data = malloc(buf2_len);
if (algId[0]->parameters.data == NULL)
goto cleanup;
memcpy(algId[0]->parameters.data, buf2, buf2_len);
algId[0]->parameters.length = buf2_len;
algId[0]->algorithm = dh_oid;
algId[1] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[1] == NULL)
goto cleanup;
algId[1]->parameters.data = malloc(buf3_len);
if (algId[1]->parameters.data == NULL)
goto cleanup;
memcpy(algId[1]->parameters.data, buf3, buf3_len);
algId[1]->parameters.length = buf3_len;
algId[1]->algorithm = dh_oid;
algId[2] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[2] == NULL)
goto cleanup;
algId[2]->parameters.data = malloc(buf1_len);
if (algId[2]->parameters.data == NULL)
goto cleanup;
memcpy(algId[2]->parameters.data, buf1, buf1_len);
algId[2]->parameters.length = buf1_len;
algId[2]->algorithm = dh_oid;
} else if (opts->dh_min_bits <= 2048) {
algId = malloc(3 * sizeof(krb5_algorithm_identifier *));
if (algId == NULL)
goto cleanup;
algId[2] = NULL;
algId[0] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[0] == NULL)
goto cleanup;
algId[0]->parameters.data = malloc(buf2_len);
if (algId[0]->parameters.data == NULL)
goto cleanup;
memcpy(algId[0]->parameters.data, buf2, buf2_len);
algId[0]->parameters.length = buf2_len;
algId[0]->algorithm = dh_oid;
algId[1] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[1] == NULL)
goto cleanup;
algId[1]->parameters.data = malloc(buf3_len);
if (algId[1]->parameters.data == NULL)
goto cleanup;
memcpy(algId[1]->parameters.data, buf3, buf3_len);
algId[1]->parameters.length = buf3_len;
algId[1]->algorithm = dh_oid;
} else if (opts->dh_min_bits <= 4096) {
algId = malloc(2 * sizeof(krb5_algorithm_identifier *));
if (algId == NULL)
goto cleanup;
algId[1] = NULL;
algId[0] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[0] == NULL)
goto cleanup;
algId[0]->parameters.data = malloc(buf3_len);
if (algId[0]->parameters.data == NULL)
goto cleanup;
memcpy(algId[0]->parameters.data, buf3, buf3_len);
algId[0]->parameters.length = buf3_len;
algId[0]->algorithm = dh_oid;
}
retval = k5int_encode_krb5_td_dh_parameters((krb5_algorithm_identifier *const *)algId, &encoded_algId);
if (retval)
goto cleanup;
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)encoded_algId->data,
encoded_algId->length, "/tmp/kdc_td_dh_params");
#endif
pa_data = malloc(2 * sizeof(krb5_pa_data *));
if (pa_data == NULL) {
retval = ENOMEM;
goto cleanup;
}
pa_data[1] = NULL;
pa_data[0] = malloc(sizeof(krb5_pa_data));
if (pa_data[0] == NULL) {
free(pa_data);
retval = ENOMEM;
goto cleanup;
}
pa_data[0]->pa_type = TD_DH_PARAMETERS;
pa_data[0]->length = encoded_algId->length;
pa_data[0]->contents = (krb5_octet *)encoded_algId->data;
*e_data_out = pa_data;
retval = 0;
cleanup:
free(buf1);
free(buf2);
free(buf3);
free(encoded_algId);
if (algId != NULL) {
while(algId[i] != NULL) {
free(algId[i]->parameters.data);
free(algId[i]);
i++;
}
free(algId);
}
return retval;
}
krb5_error_code
pkinit_check_kdc_pkid(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *pdid_buf,
unsigned int pkid_len,
int *valid_kdcPkId)
{
PKCS7_ISSUER_AND_SERIAL *is = NULL;
const unsigned char *p = pdid_buf;
int status = 1;
X509 *kdc_cert = sk_X509_value(id_cryptoctx->my_certs, id_cryptoctx->cert_index);
*valid_kdcPkId = 0;
pkiDebug("found kdcPkId in AS REQ\n");
is = d2i_PKCS7_ISSUER_AND_SERIAL(NULL, &p, (int)pkid_len);
if (is == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
status = X509_NAME_cmp(X509_get_issuer_name(kdc_cert), is->issuer);
if (!status) {
status = ASN1_INTEGER_cmp(X509_get_serialNumber(kdc_cert), is->serial);
if (!status)
*valid_kdcPkId = 1;
}
X509_NAME_free(is->issuer);
ASN1_INTEGER_free(is->serial);
free(is);
return 0;
}
/* Check parameters against a well-known DH group. */
static int
pkinit_check_dh_params(DH *dh1, DH *dh2)
{
const BIGNUM *p1, *p2, *g1, *g2;
DH_get0_pqg(dh1, &p1, NULL, &g1);
DH_get0_pqg(dh2, &p2, NULL, &g2);
if (BN_cmp(p1, p2) != 0) {
pkiDebug("p is not well-known group dhparameter\n");
return -1;
}
if (BN_cmp(g1, g2) != 0) {
pkiDebug("bad g dhparameter\n");
return -1;
}
pkiDebug("good %d dhparams\n", BN_num_bits(p1));
return 0;
}
krb5_error_code
pkinit_process_td_dh_params(krb5_context context,
pkinit_plg_crypto_context cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_algorithm_identifier **algId,
int *new_dh_size)
{
krb5_error_code retval = KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
int i = 0, use_sent_dh = 0, ok = 0;
pkiDebug("dh parameters\n");
while (algId[i] != NULL) {
DH *dh = NULL;
const BIGNUM *p;
int dh_prime_bits = 0;
if (algId[i]->algorithm.length != dh_oid.length ||
memcmp(algId[i]->algorithm.data, dh_oid.data, dh_oid.length))
goto cleanup;
dh = decode_dh_params((uint8_t *)algId[i]->parameters.data,
algId[i]->parameters.length);
if (dh == NULL)
goto cleanup;
DH_get0_pqg(dh, &p, NULL, NULL);
dh_prime_bits = BN_num_bits(p);
pkiDebug("client sent %d DH bits server prefers %d DH bits\n",
*new_dh_size, dh_prime_bits);
ok = check_dh_wellknown(cryptoctx, dh, dh_prime_bits);
if (ok) {
*new_dh_size = dh_prime_bits;
}
if (!ok) {
DH_check(dh, &retval);
if (retval != 0) {
pkiDebug("DH parameters provided by server are unacceptable\n");
retval = KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
}
else {
use_sent_dh = 1;
ok = 1;
}
}
if (!use_sent_dh)
DH_free(dh);
if (ok) {
if (req_cryptoctx->dh != NULL) {
DH_free(req_cryptoctx->dh);
req_cryptoctx->dh = NULL;
}
if (use_sent_dh)
req_cryptoctx->dh = dh;
break;
}
i++;
}
if (ok)
retval = 0;
cleanup:
return retval;
}
static int
openssl_callback(int ok, X509_STORE_CTX * ctx)
{
#ifdef DEBUG
if (!ok) {
X509 *cert = X509_STORE_CTX_get_current_cert(ctx);
int err = X509_STORE_CTX_get_error(ctx);
const char *errmsg = X509_verify_cert_error_string(err);
char buf[DN_BUF_LEN];
X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
pkiDebug("cert = %s\n", buf);
pkiDebug("callback function: %d (%s)\n", err, errmsg);
}
#endif
return ok;
}
static int
openssl_callback_ignore_crls(int ok, X509_STORE_CTX * ctx)
{
if (ok)
return ok;
return X509_STORE_CTX_get_error(ctx) == X509_V_ERR_UNABLE_TO_GET_CRL;
}
static ASN1_OBJECT *
pkinit_pkcs7type2oid(pkinit_plg_crypto_context cryptoctx, int pkcs7_type)
{
switch (pkcs7_type) {
case CMS_SIGN_CLIENT:
return cryptoctx->id_pkinit_authData;
case CMS_SIGN_DRAFT9:
return OBJ_nid2obj(NID_pkcs7_data);
case CMS_SIGN_SERVER:
return cryptoctx->id_pkinit_DHKeyData;
case CMS_ENVEL_SERVER:
return cryptoctx->id_pkinit_rkeyData;
default:
return NULL;
}
}
static int
wrap_signeddata(unsigned char *data, unsigned int data_len,
unsigned char **out, unsigned int *out_len)
{
unsigned int orig_len = 0, oid_len = 0, tot_len = 0;
ASN1_OBJECT *oid = NULL;
unsigned char *p = NULL;
/* Get length to wrap the original data with SEQUENCE tag */
tot_len = orig_len = ASN1_object_size(1, (int)data_len, V_ASN1_SEQUENCE);
/* Add the signedData OID and adjust lengths */
oid = OBJ_nid2obj(NID_pkcs7_signed);
oid_len = i2d_ASN1_OBJECT(oid, NULL);
tot_len = ASN1_object_size(1, (int)(orig_len+oid_len), V_ASN1_SEQUENCE);
p = *out = malloc(tot_len);
if (p == NULL) return -1;
ASN1_put_object(&p, 1, (int)(orig_len+oid_len),
V_ASN1_SEQUENCE, V_ASN1_UNIVERSAL);
i2d_ASN1_OBJECT(oid, &p);
ASN1_put_object(&p, 1, (int)data_len, 0, V_ASN1_CONTEXT_SPECIFIC);
memcpy(p, data, data_len);
*out_len = tot_len;
return 0;
}
static int
prepare_enc_data(const uint8_t *indata, int indata_len, uint8_t **outdata,
int *outdata_len)
{
int tag, class;
long tlen, slen;
const uint8_t *p = indata, *oldp;
if (ASN1_get_object(&p, &slen, &tag, &class, indata_len) & 0x80)
return EINVAL;
if (tag != V_ASN1_SEQUENCE)
return EINVAL;
oldp = p;
if (ASN1_get_object(&p, &tlen, &tag, &class, slen) & 0x80)
return EINVAL;
p += tlen;
slen -= (p - oldp);
if (ASN1_get_object(&p, &tlen, &tag, &class, slen) & 0x80)
return EINVAL;
*outdata = malloc(tlen);
if (*outdata == NULL)
return ENOMEM;
memcpy(*outdata, p, tlen);
*outdata_len = tlen;
return 0;
}
#ifndef WITHOUT_PKCS11
static void *
pkinit_C_LoadModule(const char *modname, CK_FUNCTION_LIST_PTR_PTR p11p)
{
void *handle;
CK_RV (*getflist)(CK_FUNCTION_LIST_PTR_PTR);
pkiDebug("loading module \"%s\"... ", modname);
handle = dlopen(modname, RTLD_NOW);
if (handle == NULL) {
pkiDebug("not found\n");
return NULL;
}
getflist = (CK_RV (*)(CK_FUNCTION_LIST_PTR_PTR)) dlsym(handle, "C_GetFunctionList");
if (getflist == NULL || (*getflist)(p11p) != CKR_OK) {
dlclose(handle);
pkiDebug("failed\n");
return NULL;
}
pkiDebug("ok\n");
return handle;
}
static CK_RV
pkinit_C_UnloadModule(void *handle)
{
dlclose(handle);
return CKR_OK;
}
static krb5_error_code
pkinit_login(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
CK_TOKEN_INFO *tip, const char *password)
{
krb5_data rdat;
char *prompt;
const char *warning;
krb5_prompt kprompt;
krb5_prompt_type prompt_type;
int r = 0;
if (tip->flags & CKF_PROTECTED_AUTHENTICATION_PATH) {
rdat.data = NULL;
rdat.length = 0;
} else if (password != NULL) {
rdat.data = strdup(password);
rdat.length = strlen(password);
} else if (id_cryptoctx->prompter == NULL) {
r = KRB5_LIBOS_CANTREADPWD;
rdat.data = NULL;
} else {
if (tip->flags & CKF_USER_PIN_LOCKED)
warning = " (Warning: PIN locked)";
else if (tip->flags & CKF_USER_PIN_FINAL_TRY)
warning = " (Warning: PIN final try)";
else if (tip->flags & CKF_USER_PIN_COUNT_LOW)
warning = " (Warning: PIN count low)";
else
warning = "";
if (asprintf(&prompt, "%.*s PIN%s", (int) sizeof (tip->label),
tip->label, warning) < 0)
return ENOMEM;
rdat.data = malloc(tip->ulMaxPinLen + 2);
rdat.length = tip->ulMaxPinLen + 1;
kprompt.prompt = prompt;
kprompt.hidden = 1;
kprompt.reply = &rdat;
prompt_type = KRB5_PROMPT_TYPE_PREAUTH;
/* PROMPTER_INVOCATION */
k5int_set_prompt_types(context, &prompt_type);
r = (*id_cryptoctx->prompter)(context, id_cryptoctx->prompter_data,
NULL, NULL, 1, &kprompt);
k5int_set_prompt_types(context, 0);
free(prompt);
}
if (r == 0) {
r = id_cryptoctx->p11->C_Login(id_cryptoctx->session, CKU_USER,
(u_char *) rdat.data, rdat.length);
if (r != CKR_OK) {
pkiDebug("C_Login: %s\n", pkinit_pkcs11_code_to_text(r));
r = KRB5KDC_ERR_PREAUTH_FAILED;
}
}
free(rdat.data);
return r;
}
static krb5_error_code
pkinit_open_session(krb5_context context,
pkinit_identity_crypto_context cctx)
{
CK_ULONG i, r;
unsigned char *cp;
size_t label_len;
CK_ULONG count = 0;
CK_SLOT_ID_PTR slotlist;
CK_TOKEN_INFO tinfo;
char *p11name;
const char *password;
if (cctx->p11_module != NULL)
return 0; /* session already open */
/* Load module */
cctx->p11_module =
pkinit_C_LoadModule(cctx->p11_module_name, &cctx->p11);
if (cctx->p11_module == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
/* Init */
if ((r = cctx->p11->C_Initialize(NULL)) != CKR_OK) {
pkiDebug("C_Initialize: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
/* Get the list of available slots */
if (cctx->p11->C_GetSlotList(TRUE, NULL, &count) != CKR_OK)
return KRB5KDC_ERR_PREAUTH_FAILED;
if (count == 0)
return KRB5KDC_ERR_PREAUTH_FAILED;
slotlist = calloc(count, sizeof(CK_SLOT_ID));
if (slotlist == NULL)
return ENOMEM;
if (cctx->p11->C_GetSlotList(TRUE, slotlist, &count) != CKR_OK)
return KRB5KDC_ERR_PREAUTH_FAILED;
/* Look for the given token label, or if none given take the first one */
for (i = 0; i < count; i++) {
/* Skip slots that don't match the specified slotid, if given. */
if (cctx->slotid != PK_NOSLOT && cctx->slotid != slotlist[i])
continue;
/* Open session */
if ((r = cctx->p11->C_OpenSession(slotlist[i], CKF_SERIAL_SESSION,
NULL, NULL, &cctx->session)) != CKR_OK) {
pkiDebug("C_OpenSession: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
/* Get token info */
if ((r = cctx->p11->C_GetTokenInfo(slotlist[i], &tinfo)) != CKR_OK) {
pkiDebug("C_GetTokenInfo: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
/* tinfo.label is zero-filled but not necessarily zero-terminated.
* Find the length, ignoring any trailing spaces. */
for (cp = tinfo.label + sizeof(tinfo.label); cp > tinfo.label; cp--) {
if (cp[-1] != '\0' && cp[-1] != ' ')
break;
}
label_len = cp - tinfo.label;
pkiDebug("open_session: slotid %d token \"%.*s\"\n",
(int)slotlist[i], (int)label_len, tinfo.label);
if (cctx->token_label == NULL ||
(strlen(cctx->token_label) == label_len &&
memcmp(cctx->token_label, tinfo.label, label_len) == 0))
break;
cctx->p11->C_CloseSession(cctx->session);
}
if (i >= count) {
free(slotlist);
pkiDebug("open_session: no matching token found\n");
return KRB5KDC_ERR_PREAUTH_FAILED;
}
cctx->slotid = slotlist[i];
free(slotlist);
pkiDebug("open_session: slotid %d (%lu of %d)\n", (int)cctx->slotid,
i + 1, (int) count);
/* Login if needed */
if (tinfo.flags & CKF_LOGIN_REQUIRED) {
if (cctx->p11_module_name != NULL) {
if (cctx->slotid != PK_NOSLOT) {
if (asprintf(&p11name,
"PKCS11:module_name=%s:slotid=%ld:token=%.*s",
cctx->p11_module_name, (long)cctx->slotid,
(int)label_len, tinfo.label) < 0)
p11name = NULL;
} else {
if (asprintf(&p11name,
"PKCS11:module_name=%s,token=%.*s",
cctx->p11_module_name,
(int)label_len, tinfo.label) < 0)
p11name = NULL;
}
} else {
p11name = NULL;
}
if (cctx->defer_id_prompt) {
/* Supply the identity name to be passed to the responder. */
pkinit_set_deferred_id(&cctx->deferred_ids,
p11name, tinfo.flags, NULL);
free(p11name);
return KRB5KRB_ERR_GENERIC;
}
/* Look up a responder-supplied password for the token. */
password = pkinit_find_deferred_id(cctx->deferred_ids, p11name);
free(p11name);
r = pkinit_login(context, cctx, &tinfo, password);
}
return r;
}
/*
* Look for a key that's:
* 1. private
* 2. capable of the specified operation (usually signing or decrypting)
* 3. RSA (this may be wrong but it's all we can do for now)
* 4. matches the id of the cert we chose
*
* You must call pkinit_get_certs before calling pkinit_find_private_key
* (that's because we need the ID of the private key)
*
* pkcs11 says the id of the key doesn't have to match that of the cert, but
* I can't figure out any other way to decide which key to use.
*
* We should only find one key that fits all the requirements.
* If there are more than one, we just take the first one.
*/
krb5_error_code
pkinit_find_private_key(pkinit_identity_crypto_context id_cryptoctx,
CK_ATTRIBUTE_TYPE usage,
CK_OBJECT_HANDLE *objp)
{
CK_OBJECT_CLASS cls;
CK_ATTRIBUTE attrs[4];
CK_ULONG count;
CK_KEY_TYPE keytype;
unsigned int nattrs = 0;
int r;
#ifdef PKINIT_USE_KEY_USAGE
CK_BBOOL true_false;
#endif
cls = CKO_PRIVATE_KEY;
attrs[nattrs].type = CKA_CLASS;
attrs[nattrs].pValue = &cls;
attrs[nattrs].ulValueLen = sizeof cls;
nattrs++;
#ifdef PKINIT_USE_KEY_USAGE
/*
* Some cards get confused if you try to specify a key usage,
* so don't, and hope for the best. This will fail if you have
* several keys with the same id and different usages but I have
* not seen this on real cards.
*/
true_false = TRUE;
attrs[nattrs].type = usage;
attrs[nattrs].pValue = &true_false;
attrs[nattrs].ulValueLen = sizeof true_false;
nattrs++;
#endif
keytype = CKK_RSA;
attrs[nattrs].type = CKA_KEY_TYPE;
attrs[nattrs].pValue = &keytype;
attrs[nattrs].ulValueLen = sizeof keytype;
nattrs++;
attrs[nattrs].type = CKA_ID;
attrs[nattrs].pValue = id_cryptoctx->cert_id;
attrs[nattrs].ulValueLen = id_cryptoctx->cert_id_len;
nattrs++;
r = id_cryptoctx->p11->C_FindObjectsInit(id_cryptoctx->session, attrs, nattrs);
if (r != CKR_OK) {
pkiDebug("krb5_pkinit_sign_data: C_FindObjectsInit: %s\n",
pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
r = id_cryptoctx->p11->C_FindObjects(id_cryptoctx->session, objp, 1, &count);
id_cryptoctx->p11->C_FindObjectsFinal(id_cryptoctx->session);
pkiDebug("found %d private keys (%s)\n", (int) count, pkinit_pkcs11_code_to_text(r));
if (r != CKR_OK || count < 1)
return KRB5KDC_ERR_PREAUTH_FAILED;
return 0;
}
#endif
static krb5_error_code
pkinit_decode_data_fs(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
const uint8_t *data, unsigned int data_len,
uint8_t **decoded_data, unsigned int *decoded_data_len)
{
X509 *cert = sk_X509_value(id_cryptoctx->my_certs,
id_cryptoctx->cert_index);
EVP_PKEY *pkey = id_cryptoctx->my_key;
uint8_t *buf;
int buf_len, decrypt_len;
*decoded_data = NULL;
*decoded_data_len = 0;
if (cert != NULL && !X509_check_private_key(cert, pkey)) {
pkiDebug("private key does not match certificate\n");
return KRB5KDC_ERR_PREAUTH_FAILED;
}
buf_len = EVP_PKEY_size(pkey);
buf = malloc(buf_len + 10);
if (buf == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
decrypt_len = EVP_PKEY_decrypt_old(buf, data, data_len, pkey);
if (decrypt_len <= 0) {
pkiDebug("unable to decrypt received data (len=%d)\n", data_len);
free(buf);
return KRB5KDC_ERR_PREAUTH_FAILED;
}
*decoded_data = buf;
*decoded_data_len = decrypt_len;
return 0;
}
#ifndef WITHOUT_PKCS11
/*
* When using the ActivCard Linux pkcs11 library (v2.0.1), the decrypt function
* fails. By inserting an extra function call, which serves nothing but to
* change the stack, we were able to work around the issue. If the ActivCard
* library is fixed in the future, this function can be inlined back into the
* caller.
*/
static CK_RV
pkinit_C_Decrypt(pkinit_identity_crypto_context id_cryptoctx,
CK_BYTE_PTR pEncryptedData,
CK_ULONG ulEncryptedDataLen,
CK_BYTE_PTR pData,
CK_ULONG_PTR pulDataLen)
{
CK_RV rv = CKR_OK;
rv = id_cryptoctx->p11->C_Decrypt(id_cryptoctx->session, pEncryptedData,
ulEncryptedDataLen, pData, pulDataLen);
if (rv == CKR_OK) {
pkiDebug("pData %p *pulDataLen %d\n", (void *) pData,
(int) *pulDataLen);
}
return rv;
}
static krb5_error_code
pkinit_decode_data_pkcs11(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
const uint8_t *data, unsigned int data_len,
uint8_t **decoded_data,
unsigned int *decoded_data_len)
{
CK_OBJECT_HANDLE obj;
CK_ULONG len;
CK_MECHANISM mech;
uint8_t *cp;
int r;
*decoded_data = NULL;
*decoded_data_len = 0;
if (pkinit_open_session(context, id_cryptoctx)) {
pkiDebug("can't open pkcs11 session\n");
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkinit_find_private_key(id_cryptoctx, CKA_DECRYPT, &obj);
mech.mechanism = CKM_RSA_PKCS;
mech.pParameter = NULL;
mech.ulParameterLen = 0;
if ((r = id_cryptoctx->p11->C_DecryptInit(id_cryptoctx->session, &mech,
obj)) != CKR_OK) {
pkiDebug("C_DecryptInit: 0x%x\n", (int) r);
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkiDebug("data_len = %d\n", data_len);
cp = malloc((size_t) data_len);
if (cp == NULL)
return ENOMEM;
len = data_len;
pkiDebug("session %p edata %p edata_len %d data %p datalen @%p %d\n",
(void *) id_cryptoctx->session, (void *) data, (int) data_len,
(void *) cp, (void *) &len, (int) len);
r = pkinit_C_Decrypt(id_cryptoctx, (CK_BYTE_PTR) data, (CK_ULONG) data_len,
cp, &len);
if (r != CKR_OK) {
pkiDebug("C_Decrypt: %s\n", pkinit_pkcs11_code_to_text(r));
if (r == CKR_BUFFER_TOO_SMALL)
pkiDebug("decrypt %d needs %d\n", (int) data_len, (int) len);
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkiDebug("decrypt %d -> %d\n", (int) data_len, (int) len);
*decoded_data_len = len;
*decoded_data = cp;
return 0;
}
#endif
krb5_error_code
pkinit_decode_data(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
const uint8_t *data, unsigned int data_len,
uint8_t **decoded_data, unsigned int *decoded_data_len)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
*decoded_data = NULL;
*decoded_data_len = 0;
if (id_cryptoctx->pkcs11_method != 1)
retval = pkinit_decode_data_fs(context, id_cryptoctx, data, data_len,
decoded_data, decoded_data_len);
#ifndef WITHOUT_PKCS11
else
retval = pkinit_decode_data_pkcs11(context, id_cryptoctx, data,
data_len, decoded_data, decoded_data_len);
#endif
return retval;
}
static krb5_error_code
pkinit_sign_data_fs(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data,
unsigned int data_len,
unsigned char **sig,
unsigned int *sig_len)
{
if (create_signature(sig, sig_len, data, data_len,
id_cryptoctx->my_key) != 0) {
pkiDebug("failed to create the signature\n");
return KRB5KDC_ERR_PREAUTH_FAILED;
}
return 0;
}
#ifndef WITHOUT_PKCS11
static krb5_error_code
pkinit_sign_data_pkcs11(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data,
unsigned int data_len,
unsigned char **sig,
unsigned int *sig_len)
{
CK_OBJECT_HANDLE obj;
CK_ULONG len;
CK_MECHANISM mech;
unsigned char *cp;
int r;
if (pkinit_open_session(context, id_cryptoctx)) {
pkiDebug("can't open pkcs11 session\n");
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkinit_find_private_key(id_cryptoctx, CKA_SIGN, &obj);
mech.mechanism = id_cryptoctx->mech;
mech.pParameter = NULL;
mech.ulParameterLen = 0;
if ((r = id_cryptoctx->p11->C_SignInit(id_cryptoctx->session, &mech,
obj)) != CKR_OK) {
pkiDebug("C_SignInit: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
/*
* Key len would give an upper bound on sig size, but there's no way to
* get that. So guess, and if it's too small, re-malloc.
*/
len = PK_SIGLEN_GUESS;
cp = malloc((size_t) len);
if (cp == NULL)
return ENOMEM;
r = id_cryptoctx->p11->C_Sign(id_cryptoctx->session, data,
(CK_ULONG) data_len, cp, &len);
if (r == CKR_BUFFER_TOO_SMALL || (r == CKR_OK && len >= PK_SIGLEN_GUESS)) {
free(cp);
pkiDebug("C_Sign realloc %d\n", (int) len);
cp = malloc((size_t) len);
r = id_cryptoctx->p11->C_Sign(id_cryptoctx->session, data,
(CK_ULONG) data_len, cp, &len);
}
if (r != CKR_OK) {
pkiDebug("C_Sign: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkiDebug("sign %d -> %d\n", (int) data_len, (int) len);
*sig_len = len;
*sig = cp;
return 0;
}
#endif
krb5_error_code
pkinit_sign_data(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data,
unsigned int data_len,
unsigned char **sig,
unsigned int *sig_len)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
if (id_cryptoctx == NULL || id_cryptoctx->pkcs11_method != 1)
retval = pkinit_sign_data_fs(context, id_cryptoctx, data, data_len,
sig, sig_len);
#ifndef WITHOUT_PKCS11
else
retval = pkinit_sign_data_pkcs11(context, id_cryptoctx, data, data_len,
sig, sig_len);
#endif
return retval;
}
static krb5_error_code
create_signature(unsigned char **sig, unsigned int *sig_len,
unsigned char *data, unsigned int data_len, EVP_PKEY *pkey)
{
krb5_error_code retval = ENOMEM;
EVP_MD_CTX *ctx;
if (pkey == NULL)
return retval;
ctx = EVP_MD_CTX_new();
if (ctx == NULL)
return ENOMEM;
EVP_SignInit(ctx, EVP_sha1());
EVP_SignUpdate(ctx, data, data_len);
*sig_len = EVP_PKEY_size(pkey);
if ((*sig = malloc(*sig_len)) == NULL)
goto cleanup;
EVP_SignFinal(ctx, *sig, sig_len, pkey);
retval = 0;
cleanup:
EVP_MD_CTX_free(ctx);
return retval;
}
/*
* Note:
* This is not the routine the KDC uses to get its certificate.
* This routine is intended to be called by the client
* to obtain the KDC's certificate from some local storage
* to be sent as a hint in its request to the KDC.
*/
krb5_error_code
pkinit_get_kdc_cert(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
req_cryptoctx->received_cert = NULL;
retval = 0;
return retval;
}
static char *
reassemble_pkcs12_name(const char *filename)
{
char *ret;
if (asprintf(&ret, "PKCS12:%s", filename) < 0)
return NULL;
return ret;
}
static krb5_error_code
pkinit_get_certs_pkcs12(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
char *prompt_string = NULL;
X509 *x = NULL;
PKCS12 *p12 = NULL;
int ret;
FILE *fp;
EVP_PKEY *y = NULL;
if (idopts->cert_filename == NULL) {
pkiDebug("%s: failed to get user's cert location\n", __FUNCTION__);
goto cleanup;
}
if (idopts->key_filename == NULL) {
pkiDebug("%s: failed to get user's private key location\n", __FUNCTION__);
goto cleanup;
}
fp = fopen(idopts->cert_filename, "rb");
if (fp == NULL) {
TRACE_PKINIT_PKCS_OPEN_FAIL(context, idopts->cert_filename, errno);
goto cleanup;
}
set_cloexec_file(fp);
p12 = d2i_PKCS12_fp(fp, NULL);
fclose(fp);
if (p12 == NULL) {
TRACE_PKINIT_PKCS_DECODE_FAIL(context, idopts->cert_filename);
goto cleanup;
}
/*
* Try parsing with no pass phrase first. If that fails,
* prompt for the pass phrase and try again.
*/
ret = PKCS12_parse(p12, NULL, &y, &x, NULL);
if (ret == 0) {
krb5_data rdat;
krb5_prompt kprompt;
krb5_prompt_type prompt_type;
krb5_error_code r;
char prompt_reply[128];
char *prompt_prefix = _("Pass phrase for");
char *p12name = reassemble_pkcs12_name(idopts->cert_filename);
const char *tmp;
TRACE_PKINIT_PKCS_PARSE_FAIL_FIRST(context);
if (id_cryptoctx->defer_id_prompt) {
/* Supply the identity name to be passed to the responder. */
pkinit_set_deferred_id(&id_cryptoctx->deferred_ids, p12name, 0,
NULL);
free(p12name);
retval = 0;
goto cleanup;
}
/* Try to read a responder-supplied password. */
tmp = pkinit_find_deferred_id(id_cryptoctx->deferred_ids, p12name);
free(p12name);
if (tmp != NULL) {
/* Try using the responder-supplied password. */
rdat.data = (char *)tmp;
rdat.length = strlen(tmp);
} else if (id_cryptoctx->prompter == NULL) {
/* We can't use a prompter. */
goto cleanup;
} else {
/* Ask using a prompter. */
memset(prompt_reply, '\0', sizeof(prompt_reply));
rdat.data = prompt_reply;
rdat.length = sizeof(prompt_reply);
if (asprintf(&prompt_string, "%s %s", prompt_prefix,
idopts->cert_filename) < 0) {
prompt_string = NULL;
goto cleanup;
}
kprompt.prompt = prompt_string;
kprompt.hidden = 1;
kprompt.reply = &rdat;
prompt_type = KRB5_PROMPT_TYPE_PREAUTH;
/* PROMPTER_INVOCATION */
k5int_set_prompt_types(context, &prompt_type);
r = (*id_cryptoctx->prompter)(context, id_cryptoctx->prompter_data,
NULL, NULL, 1, &kprompt);
k5int_set_prompt_types(context, 0);
if (r) {
TRACE_PKINIT_PKCS_PROMPT_FAIL(context);
goto cleanup;
}
}
ret = PKCS12_parse(p12, rdat.data, &y, &x, NULL);
if (ret == 0) {
TRACE_PKINIT_PKCS_PARSE_FAIL_SECOND(context);
goto cleanup;
}
}
id_cryptoctx->creds[0] = malloc(sizeof(struct _pkinit_cred_info));
if (id_cryptoctx->creds[0] == NULL)
goto cleanup;
id_cryptoctx->creds[0]->name =
reassemble_pkcs12_name(idopts->cert_filename);
id_cryptoctx->creds[0]->cert = x;
#ifndef WITHOUT_PKCS11
id_cryptoctx->creds[0]->cert_id = NULL;
id_cryptoctx->creds[0]->cert_id_len = 0;
#endif
id_cryptoctx->creds[0]->key = y;
id_cryptoctx->creds[1] = NULL;
retval = 0;
cleanup:
free(prompt_string);
if (p12)
PKCS12_free(p12);
if (retval) {
if (x != NULL)
X509_free(x);
if (y != NULL)
EVP_PKEY_free(y);
}
return retval;
}
static char *
reassemble_files_name(const char *certfile, const char *keyfile)
{
char *ret;
if (keyfile != NULL) {
if (asprintf(&ret, "FILE:%s,%s", certfile, keyfile) < 0)
return NULL;
} else {
if (asprintf(&ret, "FILE:%s", certfile) < 0)
return NULL;
}
return ret;
}
static krb5_error_code
pkinit_load_fs_cert_and_key(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
char *certname,
char *keyname,
int cindex)
{
krb5_error_code retval;
X509 *x = NULL;
EVP_PKEY *y = NULL;
char *fsname = NULL;
const char *password;
fsname = reassemble_files_name(certname, keyname);
/* Try to read a responder-supplied password. */
password = pkinit_find_deferred_id(id_cryptoctx->deferred_ids, fsname);
/* Load the certificate. */
retval = get_cert(certname, &x);
if (retval != 0 || x == NULL) {
retval = oerr(context, 0, _("Cannot read certificate file '%s'"),
certname);
goto cleanup;
}
/* Load the key. */
retval = get_key(context, id_cryptoctx, keyname, fsname, &y, password);
if (retval != 0 || y == NULL) {
retval = oerr(context, 0, _("Cannot read key file '%s'"), fsname);
goto cleanup;
}
id_cryptoctx->creds[cindex] = malloc(sizeof(struct _pkinit_cred_info));
if (id_cryptoctx->creds[cindex] == NULL) {
retval = ENOMEM;
goto cleanup;
}
id_cryptoctx->creds[cindex]->name = reassemble_files_name(certname,
keyname);
id_cryptoctx->creds[cindex]->cert = x;
#ifndef WITHOUT_PKCS11
id_cryptoctx->creds[cindex]->cert_id = NULL;
id_cryptoctx->creds[cindex]->cert_id_len = 0;
#endif
id_cryptoctx->creds[cindex]->key = y;
id_cryptoctx->creds[cindex+1] = NULL;
retval = 0;
cleanup:
free(fsname);
if (retval != 0 || y == NULL) {
if (x != NULL)
X509_free(x);
if (y != NULL)
EVP_PKEY_free(y);
}
return retval;
}
static krb5_error_code
pkinit_get_certs_fs(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
if (idopts->cert_filename == NULL) {
pkiDebug("%s: failed to get user's cert location\n", __FUNCTION__);
goto cleanup;
}
if (idopts->key_filename == NULL) {
TRACE_PKINIT_NO_PRIVKEY(context);
goto cleanup;
}
retval = pkinit_load_fs_cert_and_key(context, id_cryptoctx,
idopts->cert_filename,
idopts->key_filename, 0);
cleanup:
return retval;
}
static krb5_error_code
pkinit_get_certs_dir(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
krb5_error_code retval = ENOMEM;
DIR *d = NULL;
struct dirent *dentry = NULL;
char certname[1024];
char keyname[1024];
int i = 0, len;
char *dirname, *suf;
if (idopts->cert_filename == NULL) {
TRACE_PKINIT_NO_CERT(context);
return ENOENT;
}
dirname = idopts->cert_filename;
d = opendir(dirname);
if (d == NULL)
return errno;
/*
* We'll assume that certs are named XXX.crt and the corresponding
* key is named XXX.key
*/
while ((i < MAX_CREDS_ALLOWED) && (dentry = readdir(d)) != NULL) {
/* Ignore subdirectories and anything starting with a dot */
#ifdef DT_DIR
if (dentry->d_type == DT_DIR)
continue;
#endif
if (dentry->d_name[0] == '.')
continue;
len = strlen(dentry->d_name);
if (len < 5)
continue;
suf = dentry->d_name + (len - 4);
if (strncmp(suf, ".crt", 4) != 0)
continue;
/* Checked length */
if (strlen(dirname) + strlen(dentry->d_name) + 2 > sizeof(certname)) {
pkiDebug("%s: Path too long -- directory '%s' and file '%s'\n",
__FUNCTION__, dirname, dentry->d_name);
continue;
}
snprintf(certname, sizeof(certname), "%s/%s", dirname, dentry->d_name);
snprintf(keyname, sizeof(keyname), "%s/%s", dirname, dentry->d_name);
len = strlen(keyname);
keyname[len - 3] = 'k';
keyname[len - 2] = 'e';
keyname[len - 1] = 'y';
retval = pkinit_load_fs_cert_and_key(context, id_cryptoctx,
certname, keyname, i);
if (retval == 0) {
TRACE_PKINIT_LOADED_CERT(context, dentry->d_name);
i++;
}
else
continue;
}
if (!id_cryptoctx->defer_id_prompt && i == 0) {
TRACE_PKINIT_NO_CERT_AND_KEY(context, idopts->cert_filename);
retval = ENOENT;
goto cleanup;
}
retval = 0;
cleanup:
if (d)
closedir(d);
return retval;
}
#ifndef WITHOUT_PKCS11
static char *
reassemble_pkcs11_name(pkinit_identity_opts *idopts)
{
struct k5buf buf;
int n = 0;
char *ret;
k5_buf_init_dynamic(&buf);
k5_buf_add(&buf, "PKCS11:");
n = 0;
if (idopts->p11_module_name != NULL) {
k5_buf_add_fmt(&buf, "%smodule_name=%s", n++ ? ":" : "",
idopts->p11_module_name);
}
if (idopts->token_label != NULL) {
k5_buf_add_fmt(&buf, "%stoken=%s", n++ ? ":" : "",
idopts->token_label);
}
if (idopts->cert_label != NULL) {
k5_buf_add_fmt(&buf, "%scertlabel=%s", n++ ? ":" : "",
idopts->cert_label);
}
if (idopts->cert_id_string != NULL) {
k5_buf_add_fmt(&buf, "%scertid=%s", n++ ? ":" : "",
idopts->cert_id_string);
}
if (idopts->slotid != PK_NOSLOT) {
k5_buf_add_fmt(&buf, "%sslotid=%ld", n++ ? ":" : "",
(long)idopts->slotid);
}
if (k5_buf_status(&buf) == 0)
ret = strdup(buf.data);
else
ret = NULL;
k5_buf_free(&buf);
return ret;
}
static krb5_error_code
pkinit_get_certs_pkcs11(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
#ifdef PKINIT_USE_MECH_LIST
CK_MECHANISM_TYPE_PTR mechp;
CK_MECHANISM_INFO info;
#endif
CK_OBJECT_CLASS cls;
CK_OBJECT_HANDLE obj;
CK_ATTRIBUTE attrs[4];
CK_ULONG count;
CK_CERTIFICATE_TYPE certtype;
CK_BYTE_PTR cert = NULL, cert_id;
const unsigned char *cp;
int i, r;
unsigned int nattrs;
X509 *x = NULL;
/* Copy stuff from idopts -> id_cryptoctx */
if (idopts->p11_module_name != NULL) {
free(id_cryptoctx->p11_module_name);
id_cryptoctx->p11_module_name = strdup(idopts->p11_module_name);
if (id_cryptoctx->p11_module_name == NULL)
return ENOMEM;
}
if (idopts->token_label != NULL) {
id_cryptoctx->token_label = strdup(idopts->token_label);
if (id_cryptoctx->token_label == NULL)
return ENOMEM;
}
if (idopts->cert_label != NULL) {
id_cryptoctx->cert_label = strdup(idopts->cert_label);
if (id_cryptoctx->cert_label == NULL)
return ENOMEM;
}
/* Convert the ascii cert_id string into a binary blob */
if (idopts->cert_id_string != NULL) {
BIGNUM *bn = NULL;
BN_hex2bn(&bn, idopts->cert_id_string);
if (bn == NULL)
return ENOMEM;
id_cryptoctx->cert_id_len = BN_num_bytes(bn);
id_cryptoctx->cert_id = malloc((size_t) id_cryptoctx->cert_id_len);
if (id_cryptoctx->cert_id == NULL) {
BN_free(bn);
return ENOMEM;
}
BN_bn2bin(bn, id_cryptoctx->cert_id);
BN_free(bn);
}
id_cryptoctx->slotid = idopts->slotid;
id_cryptoctx->pkcs11_method = 1;
if (pkinit_open_session(context, id_cryptoctx)) {
pkiDebug("can't open pkcs11 session\n");
if (!id_cryptoctx->defer_id_prompt)
return KRB5KDC_ERR_PREAUTH_FAILED;
}
if (id_cryptoctx->defer_id_prompt) {
/*
* We need to reset all of the PKCS#11 state, so that the next time we
* poke at it, it'll be in as close to the state it was in after we
* loaded it the first time as we can make it.
*/
pkinit_fini_pkcs11(id_cryptoctx);
pkinit_init_pkcs11(id_cryptoctx);
return 0;
}
#ifndef PKINIT_USE_MECH_LIST
/*
* We'd like to use CKM_SHA1_RSA_PKCS for signing if it's available, but
* many cards seems to be confused about whether they are capable of
* this or not. The safe thing seems to be to ignore the mechanism list,
* always use CKM_RSA_PKCS and calculate the sha1 digest ourselves.
*/
id_cryptoctx->mech = CKM_RSA_PKCS;
#else
if ((r = id_cryptoctx->p11->C_GetMechanismList(id_cryptoctx->slotid, NULL,
&count)) != CKR_OK || count <= 0) {
pkiDebug("C_GetMechanismList: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
mechp = malloc(count * sizeof (CK_MECHANISM_TYPE));
if (mechp == NULL)
return ENOMEM;
if ((r = id_cryptoctx->p11->C_GetMechanismList(id_cryptoctx->slotid,
mechp, &count)) != CKR_OK)
return KRB5KDC_ERR_PREAUTH_FAILED;
for (i = 0; i < count; i++) {
if ((r = id_cryptoctx->p11->C_GetMechanismInfo(id_cryptoctx->slotid,
mechp[i], &info)) != CKR_OK)
return KRB5KDC_ERR_PREAUTH_FAILED;
#ifdef DEBUG_MECHINFO
pkiDebug("mech %x flags %x\n", (int) mechp[i], (int) info.flags);
if ((info.flags & (CKF_SIGN|CKF_DECRYPT)) == (CKF_SIGN|CKF_DECRYPT))
pkiDebug(" this mech is good for sign & decrypt\n");
#endif
if (mechp[i] == CKM_RSA_PKCS) {
/* This seems backwards... */
id_cryptoctx->mech =
(info.flags & CKF_SIGN) ? CKM_SHA1_RSA_PKCS : CKM_RSA_PKCS;
}
}
free(mechp);
pkiDebug("got %d mechs from card\n", (int) count);
#endif
cls = CKO_CERTIFICATE;
attrs[0].type = CKA_CLASS;
attrs[0].pValue = &cls;
attrs[0].ulValueLen = sizeof cls;
certtype = CKC_X_509;
attrs[1].type = CKA_CERTIFICATE_TYPE;
attrs[1].pValue = &certtype;
attrs[1].ulValueLen = sizeof certtype;
nattrs = 2;
/* If a cert id and/or label were given, use them too */
if (id_cryptoctx->cert_id_len > 0) {
attrs[nattrs].type = CKA_ID;
attrs[nattrs].pValue = id_cryptoctx->cert_id;
attrs[nattrs].ulValueLen = id_cryptoctx->cert_id_len;
nattrs++;
}
if (id_cryptoctx->cert_label != NULL) {
attrs[nattrs].type = CKA_LABEL;
attrs[nattrs].pValue = id_cryptoctx->cert_label;
attrs[nattrs].ulValueLen = strlen(id_cryptoctx->cert_label);
nattrs++;
}
r = id_cryptoctx->p11->C_FindObjectsInit(id_cryptoctx->session, attrs, nattrs);
if (r != CKR_OK) {
pkiDebug("C_FindObjectsInit: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
for (i = 0; ; i++) {
if (i >= MAX_CREDS_ALLOWED)
return KRB5KDC_ERR_PREAUTH_FAILED;
/* Look for x.509 cert */
if ((r = id_cryptoctx->p11->C_FindObjects(id_cryptoctx->session,
&obj, 1, &count)) != CKR_OK || count <= 0) {
id_cryptoctx->creds[i] = NULL;
break;
}
/* Get cert and id len */
attrs[0].type = CKA_VALUE;
attrs[0].pValue = NULL;
attrs[0].ulValueLen = 0;
attrs[1].type = CKA_ID;
attrs[1].pValue = NULL;
attrs[1].ulValueLen = 0;
if ((r = id_cryptoctx->p11->C_GetAttributeValue(id_cryptoctx->session,
obj, attrs, 2)) != CKR_OK && r != CKR_BUFFER_TOO_SMALL) {
pkiDebug("C_GetAttributeValue: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
cert = (CK_BYTE_PTR) malloc((size_t) attrs[0].ulValueLen + 1);
cert_id = (CK_BYTE_PTR) malloc((size_t) attrs[1].ulValueLen + 1);
if (cert == NULL || cert_id == NULL)
return ENOMEM;
/* Read the cert and id off the card */
attrs[0].type = CKA_VALUE;
attrs[0].pValue = cert;
attrs[1].type = CKA_ID;
attrs[1].pValue = cert_id;
if ((r = id_cryptoctx->p11->C_GetAttributeValue(id_cryptoctx->session,
obj, attrs, 2)) != CKR_OK) {
pkiDebug("C_GetAttributeValue: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkiDebug("cert %d size %d id %d idlen %d\n", i,
(int) attrs[0].ulValueLen, (int) cert_id[0],
(int) attrs[1].ulValueLen);
cp = (unsigned char *) cert;
x = d2i_X509(NULL, &cp, (int) attrs[0].ulValueLen);
if (x == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
id_cryptoctx->creds[i] = malloc(sizeof(struct _pkinit_cred_info));
if (id_cryptoctx->creds[i] == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
id_cryptoctx->creds[i]->name = reassemble_pkcs11_name(idopts);
id_cryptoctx->creds[i]->cert = x;
id_cryptoctx->creds[i]->key = NULL;
id_cryptoctx->creds[i]->cert_id = cert_id;
id_cryptoctx->creds[i]->cert_id_len = attrs[1].ulValueLen;
free(cert);
}
id_cryptoctx->p11->C_FindObjectsFinal(id_cryptoctx->session);
if (cert == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
return 0;
}
#endif
static void
free_cred_info(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
struct _pkinit_cred_info *cred)
{
if (cred != NULL) {
if (cred->cert != NULL)
X509_free(cred->cert);
if (cred->key != NULL)
EVP_PKEY_free(cred->key);
#ifndef WITHOUT_PKCS11
free(cred->cert_id);
#endif
free(cred->name);
free(cred);
}
}
krb5_error_code
crypto_free_cert_info(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx)
{
int i;
if (id_cryptoctx == NULL)
return EINVAL;
for (i = 0; i < MAX_CREDS_ALLOWED; i++) {
if (id_cryptoctx->creds[i] != NULL) {
free_cred_info(context, id_cryptoctx, id_cryptoctx->creds[i]);
id_cryptoctx->creds[i] = NULL;
}
}
return 0;
}
krb5_error_code
crypto_load_certs(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ,
krb5_boolean defer_id_prompts)
{
krb5_error_code retval;
id_cryptoctx->defer_id_prompt = defer_id_prompts;
switch(idopts->idtype) {
case IDTYPE_FILE:
retval = pkinit_get_certs_fs(context, plg_cryptoctx,
req_cryptoctx, idopts,
id_cryptoctx, princ);
break;
case IDTYPE_DIR:
retval = pkinit_get_certs_dir(context, plg_cryptoctx,
req_cryptoctx, idopts,
id_cryptoctx, princ);
break;
#ifndef WITHOUT_PKCS11
case IDTYPE_PKCS11:
retval = pkinit_get_certs_pkcs11(context, plg_cryptoctx,
req_cryptoctx, idopts,
id_cryptoctx, princ);
break;
#endif
case IDTYPE_PKCS12:
retval = pkinit_get_certs_pkcs12(context, plg_cryptoctx,
req_cryptoctx, idopts,
id_cryptoctx, princ);
break;
default:
retval = EINVAL;
}
if (retval)
goto cleanup;
cleanup:
return retval;
}
/*
* Get certificate Key Usage and Extended Key Usage
*/
static krb5_error_code
crypto_retrieve_X509_key_usage(krb5_context context,
pkinit_plg_crypto_context plgcctx,
pkinit_req_crypto_context reqcctx,
X509 *x,
unsigned int *ret_ku_bits,
unsigned int *ret_eku_bits)
{
krb5_error_code retval = 0;
int i;
unsigned int eku_bits = 0, ku_bits = 0;
ASN1_BIT_STRING *usage = NULL;
if (ret_ku_bits == NULL && ret_eku_bits == NULL)
return EINVAL;
if (ret_eku_bits)
*ret_eku_bits = 0;
else {
pkiDebug("%s: EKUs not requested, not checking\n", __FUNCTION__);
goto check_kus;
}
/* Start with Extended Key usage */
i = X509_get_ext_by_NID(x, NID_ext_key_usage, -1);
if (i >= 0) {
EXTENDED_KEY_USAGE *eku;
eku = X509_get_ext_d2i(x, NID_ext_key_usage, NULL, NULL);
if (eku) {
for (i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
ASN1_OBJECT *certoid;
certoid = sk_ASN1_OBJECT_value(eku, i);
if ((OBJ_cmp(certoid, plgcctx->id_pkinit_KPClientAuth)) == 0)
eku_bits |= PKINIT_EKU_PKINIT;
else if ((OBJ_cmp(certoid, OBJ_nid2obj(NID_ms_smartcard_login))) == 0)
eku_bits |= PKINIT_EKU_MSSCLOGIN;
else if ((OBJ_cmp(certoid, OBJ_nid2obj(NID_client_auth))) == 0)
eku_bits |= PKINIT_EKU_CLIENTAUTH;
else if ((OBJ_cmp(certoid, OBJ_nid2obj(NID_email_protect))) == 0)
eku_bits |= PKINIT_EKU_EMAILPROTECTION;
}
EXTENDED_KEY_USAGE_free(eku);
}
}
pkiDebug("%s: returning eku 0x%08x\n", __FUNCTION__, eku_bits);
*ret_eku_bits = eku_bits;
check_kus:
/* Now the Key Usage bits */
if (ret_ku_bits)
*ret_ku_bits = 0;
else {
pkiDebug("%s: KUs not requested, not checking\n", __FUNCTION__);
goto out;
}
/* Make sure usage exists before checking bits */
X509_check_ca(x);
usage = X509_get_ext_d2i(x, NID_key_usage, NULL, NULL);
if (usage) {
if (!ku_reject(x, X509v3_KU_DIGITAL_SIGNATURE))
ku_bits |= PKINIT_KU_DIGITALSIGNATURE;
if (!ku_reject(x, X509v3_KU_KEY_ENCIPHERMENT))
ku_bits |= PKINIT_KU_KEYENCIPHERMENT;
ASN1_BIT_STRING_free(usage);
}
pkiDebug("%s: returning ku 0x%08x\n", __FUNCTION__, ku_bits);
*ret_ku_bits = ku_bits;
retval = 0;
out:
return retval;
}
static krb5_error_code
rfc2253_name(X509_NAME *name, char **str_out)
{
BIO *b = NULL;
char *str;
*str_out = NULL;
b = BIO_new(BIO_s_mem());
if (b == NULL)
return ENOMEM;
if (X509_NAME_print_ex(b, name, 0, XN_FLAG_SEP_COMMA_PLUS) < 0)
goto error;
str = calloc(BIO_number_written(b) + 1, 1);
if (str == NULL)
goto error;
BIO_read(b, str, BIO_number_written(b));
BIO_free(b);
*str_out = str;
return 0;
error:
BIO_free(b);
return ENOMEM;
}
/*
* Get number of certificates available after crypto_load_certs()
*/
static krb5_error_code
crypto_cert_get_count(pkinit_identity_crypto_context id_cryptoctx,
int *cert_count)
{
int count;
*cert_count = 0;
if (id_cryptoctx == NULL || id_cryptoctx->creds[0] == NULL)
return EINVAL;
for (count = 0;
count <= MAX_CREDS_ALLOWED && id_cryptoctx->creds[count] != NULL;
count++);
*cert_count = count;
return 0;
}
void
crypto_cert_free_matching_data(krb5_context context,
pkinit_cert_matching_data *md)
{
int i;
if (md == NULL)
return;
free(md->subject_dn);
free(md->issuer_dn);
for (i = 0; md->sans != NULL && md->sans[i] != NULL; i++)
krb5_free_principal(context, md->sans[i]);
free(md->sans);
free(md);
}
/*
* Free certificate matching data.
*/
void
crypto_cert_free_matching_data_list(krb5_context context,
pkinit_cert_matching_data **list)
{
int i;
for (i = 0; list != NULL && list[i] != NULL; i++)
crypto_cert_free_matching_data(context, list[i]);
free(list);
}
/*
* Get certificate matching data for cert.
*/
static krb5_error_code
get_matching_data(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx, X509 *cert,
pkinit_cert_matching_data **md_out)
{
krb5_error_code ret = ENOMEM;
pkinit_cert_matching_data *md = NULL;
krb5_principal *pkinit_sans = NULL, *upn_sans = NULL;
size_t i, j;
*md_out = NULL;
md = calloc(1, sizeof(*md));
if (md == NULL)
goto cleanup;
ret = rfc2253_name(X509_get_subject_name(cert), &md->subject_dn);
if (ret)
goto cleanup;
ret = rfc2253_name(X509_get_issuer_name(cert), &md->issuer_dn);
if (ret)
goto cleanup;
/* Get the SAN data. */
ret = crypto_retrieve_X509_sans(context, plg_cryptoctx, req_cryptoctx,
cert, &pkinit_sans, &upn_sans, NULL);
if (ret)
goto cleanup;
j = 0;
if (pkinit_sans != NULL) {
for (i = 0; pkinit_sans[i] != NULL; i++)
j++;
}
if (upn_sans != NULL) {
for (i = 0; upn_sans[i] != NULL; i++)
j++;
}
if (j != 0) {
md->sans = calloc((size_t)j+1, sizeof(*md->sans));
if (md->sans == NULL) {
ret = ENOMEM;
goto cleanup;
}
j = 0;
if (pkinit_sans != NULL) {
for (i = 0; pkinit_sans[i] != NULL; i++)
md->sans[j++] = pkinit_sans[i];
free(pkinit_sans);
}
if (upn_sans != NULL) {
for (i = 0; upn_sans[i] != NULL; i++)
md->sans[j++] = upn_sans[i];
free(upn_sans);
}
md->sans[j] = NULL;
} else
md->sans = NULL;
/* Get the KU and EKU data. */
ret = crypto_retrieve_X509_key_usage(context, plg_cryptoctx,
req_cryptoctx, cert, &md->ku_bits,
&md->eku_bits);
if (ret)
goto cleanup;
*md_out = md;
md = NULL;
cleanup:
crypto_cert_free_matching_data(context, md);
return ret;
}
krb5_error_code
crypto_cert_get_matching_data(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
pkinit_cert_matching_data ***md_out)
{
krb5_error_code ret;
pkinit_cert_matching_data **md_list = NULL;
int count, i;
ret = crypto_cert_get_count(id_cryptoctx, &count);
if (ret)
goto cleanup;
md_list = calloc(count + 1, sizeof(*md_list));
if (md_list == NULL) {
ret = ENOMEM;
goto cleanup;
}
for (i = 0; i < count; i++) {
ret = get_matching_data(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx->creds[i]->cert, &md_list[i]);
if (ret) {
pkiDebug("%s: crypto_cert_get_matching_data error %d, %s\n",
__FUNCTION__, ret, error_message(ret));
goto cleanup;
}
}
*md_out = md_list;
md_list = NULL;
cleanup:
crypto_cert_free_matching_data_list(context, md_list);
return ret;
}
/*
* Set the certificate in idctx->creds[cred_index] as the selected certificate.
*/
krb5_error_code
crypto_cert_select(krb5_context context, pkinit_identity_crypto_context idctx,
size_t cred_index)
{
pkinit_cred_info ci = NULL;
if (cred_index >= MAX_CREDS_ALLOWED || idctx->creds[cred_index] == NULL)
return ENOENT;
ci = idctx->creds[cred_index];
/* copy the selected cert into our id_cryptoctx */
if (idctx->my_certs != NULL)
sk_X509_pop_free(idctx->my_certs, X509_free);
idctx->my_certs = sk_X509_new_null();
sk_X509_push(idctx->my_certs, ci->cert);
free(idctx->identity);
/* hang on to the selected credential name */
if (ci->name != NULL)
idctx->identity = strdup(ci->name);
else
idctx->identity = NULL;
ci->cert = NULL; /* Don't free it twice */
idctx->cert_index = 0;
if (idctx->pkcs11_method != 1) {
idctx->my_key = ci->key;
ci->key = NULL; /* Don't free it twice */
}
#ifndef WITHOUT_PKCS11
else {
idctx->cert_id = ci->cert_id;
ci->cert_id = NULL; /* Don't free it twice */
idctx->cert_id_len = ci->cert_id_len;
}
#endif
return 0;
}
/*
* Choose the default certificate as "the chosen one"
*/
krb5_error_code
crypto_cert_select_default(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx)
{
krb5_error_code retval;
int cert_count;
retval = crypto_cert_get_count(id_cryptoctx, &cert_count);
if (retval)
goto errout;
if (cert_count != 1) {
TRACE_PKINIT_NO_DEFAULT_CERT(context, cert_count);
retval = EINVAL;
goto errout;
}
/* copy the selected cert into our id_cryptoctx */
if (id_cryptoctx->my_certs != NULL) {
sk_X509_pop_free(id_cryptoctx->my_certs, X509_free);
}
id_cryptoctx->my_certs = sk_X509_new_null();
sk_X509_push(id_cryptoctx->my_certs, id_cryptoctx->creds[0]->cert);
id_cryptoctx->creds[0]->cert = NULL; /* Don't free it twice */
id_cryptoctx->cert_index = 0;
/* hang on to the selected credential name */
if (id_cryptoctx->creds[0]->name != NULL)
id_cryptoctx->identity = strdup(id_cryptoctx->creds[0]->name);
else
id_cryptoctx->identity = NULL;
if (id_cryptoctx->pkcs11_method != 1) {
id_cryptoctx->my_key = id_cryptoctx->creds[0]->key;
id_cryptoctx->creds[0]->key = NULL; /* Don't free it twice */
}
#ifndef WITHOUT_PKCS11
else {
id_cryptoctx->cert_id = id_cryptoctx->creds[0]->cert_id;
id_cryptoctx->creds[0]->cert_id = NULL; /* Don't free it twice */
id_cryptoctx->cert_id_len = id_cryptoctx->creds[0]->cert_id_len;
}
#endif
retval = 0;
errout:
return retval;
}
static krb5_error_code
load_cas_and_crls(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int catype,
char *filename)
{
STACK_OF(X509_INFO) *sk = NULL;
STACK_OF(X509) *ca_certs = NULL;
STACK_OF(X509_CRL) *ca_crls = NULL;
BIO *in = NULL;
krb5_error_code retval = ENOMEM;
int i = 0;
/* If there isn't already a stack in the context,
* create a temporary one now */
switch(catype) {
case CATYPE_ANCHORS:
if (id_cryptoctx->trustedCAs != NULL)
ca_certs = id_cryptoctx->trustedCAs;
else {
ca_certs = sk_X509_new_null();
if (ca_certs == NULL)
return ENOMEM;
}
break;
case CATYPE_INTERMEDIATES:
if (id_cryptoctx->intermediateCAs != NULL)
ca_certs = id_cryptoctx->intermediateCAs;
else {
ca_certs = sk_X509_new_null();
if (ca_certs == NULL)
return ENOMEM;
}
break;
case CATYPE_CRLS:
if (id_cryptoctx->revoked != NULL)
ca_crls = id_cryptoctx->revoked;
else {
ca_crls = sk_X509_CRL_new_null();
if (ca_crls == NULL)
return ENOMEM;
}
break;
default:
return ENOTSUP;
}
if (!(in = BIO_new_file(filename, "r"))) {
retval = oerr(context, 0, _("Cannot open file '%s'"), filename);
goto cleanup;
}
/* This loads from a file, a stack of x509/crl/pkey sets */
if ((sk = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL)) == NULL) {
pkiDebug("%s: error reading file '%s'\n", __FUNCTION__, filename);
retval = oerr(context, 0, _("Cannot read file '%s'"), filename);
goto cleanup;
}
/* scan over the stack created from loading the file contents,
* weed out duplicates, and push new ones onto the return stack
*/
for (i = 0; i < sk_X509_INFO_num(sk); i++) {
X509_INFO *xi = sk_X509_INFO_value(sk, i);
if (xi != NULL && xi->x509 != NULL && catype != CATYPE_CRLS) {
int j = 0, size = sk_X509_num(ca_certs), flag = 0;
if (!size) {
sk_X509_push(ca_certs, xi->x509);
xi->x509 = NULL;
continue;
}
for (j = 0; j < size; j++) {
X509 *x = sk_X509_value(ca_certs, j);
flag = X509_cmp(x, xi->x509);
if (flag == 0)
break;
else
continue;
}
if (flag != 0) {
sk_X509_push(ca_certs, X509_dup(xi->x509));
}
} else if (xi != NULL && xi->crl != NULL && catype == CATYPE_CRLS) {
int j = 0, size = sk_X509_CRL_num(ca_crls), flag = 0;
if (!size) {
sk_X509_CRL_push(ca_crls, xi->crl);
xi->crl = NULL;
continue;
}
for (j = 0; j < size; j++) {
X509_CRL *x = sk_X509_CRL_value(ca_crls, j);
flag = X509_CRL_cmp(x, xi->crl);
if (flag == 0)
break;
else
continue;
}
if (flag != 0) {
sk_X509_CRL_push(ca_crls, X509_CRL_dup(xi->crl));
}
}
}
/* If we added something and there wasn't a stack in the
* context before, add the temporary stack to the context.
*/
switch(catype) {
case CATYPE_ANCHORS:
if (sk_X509_num(ca_certs) == 0) {
TRACE_PKINIT_NO_CA_ANCHOR(context, filename);
if (id_cryptoctx->trustedCAs == NULL)
sk_X509_free(ca_certs);
} else {
if (id_cryptoctx->trustedCAs == NULL)
id_cryptoctx->trustedCAs = ca_certs;
}
break;
case CATYPE_INTERMEDIATES:
if (sk_X509_num(ca_certs) == 0) {
TRACE_PKINIT_NO_CA_INTERMEDIATE(context, filename);
if (id_cryptoctx->intermediateCAs == NULL)
sk_X509_free(ca_certs);
} else {
if (id_cryptoctx->intermediateCAs == NULL)
id_cryptoctx->intermediateCAs = ca_certs;
}
break;
case CATYPE_CRLS:
if (sk_X509_CRL_num(ca_crls) == 0) {
TRACE_PKINIT_NO_CRL(context, filename);
if (id_cryptoctx->revoked == NULL)
sk_X509_CRL_free(ca_crls);
} else {
if (id_cryptoctx->revoked == NULL)
id_cryptoctx->revoked = ca_crls;
}
break;
default:
/* Should have been caught above! */
retval = EINVAL;
goto cleanup;
break;
}
retval = 0;
cleanup:
if (in != NULL)
BIO_free(in);
if (sk != NULL)
sk_X509_INFO_pop_free(sk, X509_INFO_free);
return retval;
}
static krb5_error_code
load_cas_and_crls_dir(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int catype,
char *dirname)
{
krb5_error_code retval = EINVAL;
DIR *d = NULL;
struct dirent *dentry = NULL;
char filename[1024];
if (dirname == NULL)
return EINVAL;
d = opendir(dirname);
if (d == NULL)
return ENOENT;
while ((dentry = readdir(d))) {
if (strlen(dirname) + strlen(dentry->d_name) + 2 > sizeof(filename)) {
pkiDebug("%s: Path too long -- directory '%s' and file '%s'\n",
__FUNCTION__, dirname, dentry->d_name);
goto cleanup;
}
/* Ignore subdirectories and anything starting with a dot */
#ifdef DT_DIR
if (dentry->d_type == DT_DIR)
continue;
#endif
if (dentry->d_name[0] == '.')
continue;
snprintf(filename, sizeof(filename), "%s/%s", dirname, dentry->d_name);
retval = load_cas_and_crls(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx, catype, filename);
if (retval)
goto cleanup;
}
retval = 0;
cleanup:
if (d != NULL)
closedir(d);
return retval;
}
krb5_error_code
crypto_load_cas_and_crls(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
int idtype,
int catype,
char *id)
{
switch (idtype) {
case IDTYPE_FILE:
TRACE_PKINIT_LOAD_FROM_FILE(context);
return load_cas_and_crls(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx, catype, id);
break;
case IDTYPE_DIR:
TRACE_PKINIT_LOAD_FROM_DIR(context);
return load_cas_and_crls_dir(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx, catype, id);
break;
default:
return ENOTSUP;
break;
}
}
static krb5_error_code
create_identifiers_from_stack(STACK_OF(X509) *sk,
krb5_external_principal_identifier *** ids)
{
int i = 0, sk_size = sk_X509_num(sk);
krb5_external_principal_identifier **krb5_cas = NULL;
X509 *x = NULL;
X509_NAME *xn = NULL;
unsigned char *p = NULL;
int len = 0;
PKCS7_ISSUER_AND_SERIAL *is = NULL;
char buf[DN_BUF_LEN];
*ids = NULL;
krb5_cas = calloc(sk_size + 1, sizeof(*krb5_cas));
if (krb5_cas == NULL)
return ENOMEM;
for (i = 0; i < sk_size; i++) {
krb5_cas[i] = malloc(sizeof(krb5_external_principal_identifier));
x = sk_X509_value(sk, i);
X509_NAME_oneline(X509_get_subject_name(x), buf, sizeof(buf));
pkiDebug("#%d cert= %s\n", i, buf);
/* fill-in subjectName */
krb5_cas[i]->subjectName.magic = 0;
krb5_cas[i]->subjectName.length = 0;
krb5_cas[i]->subjectName.data = NULL;
xn = X509_get_subject_name(x);
len = i2d_X509_NAME(xn, NULL);
if ((p = malloc((size_t) len)) == NULL)
goto oom;
krb5_cas[i]->subjectName.data = (char *)p;
i2d_X509_NAME(xn, &p);
krb5_cas[i]->subjectName.length = len;
/* fill-in issuerAndSerialNumber */
krb5_cas[i]->issuerAndSerialNumber.length = 0;
krb5_cas[i]->issuerAndSerialNumber.magic = 0;
krb5_cas[i]->issuerAndSerialNumber.data = NULL;
is = PKCS7_ISSUER_AND_SERIAL_new();
if (is == NULL)
goto oom;
X509_NAME_set(&is->issuer, X509_get_issuer_name(x));
ASN1_INTEGER_free(is->serial);
is->serial = ASN1_INTEGER_dup(X509_get_serialNumber(x));
if (is->serial == NULL)
goto oom;
len = i2d_PKCS7_ISSUER_AND_SERIAL(is, NULL);
p = malloc(len);
if (p == NULL)
goto oom;
krb5_cas[i]->issuerAndSerialNumber.data = (char *)p;
i2d_PKCS7_ISSUER_AND_SERIAL(is, &p);
krb5_cas[i]->issuerAndSerialNumber.length = len;
/* fill-in subjectKeyIdentifier */
krb5_cas[i]->subjectKeyIdentifier.length = 0;
krb5_cas[i]->subjectKeyIdentifier.magic = 0;
krb5_cas[i]->subjectKeyIdentifier.data = NULL;
if (X509_get_ext_by_NID(x, NID_subject_key_identifier, -1) >= 0) {
ASN1_OCTET_STRING *ikeyid;
ikeyid = X509_get_ext_d2i(x, NID_subject_key_identifier, NULL,
NULL);
if (ikeyid != NULL) {
len = i2d_ASN1_OCTET_STRING(ikeyid, NULL);
p = malloc(len);
if (p == NULL)
goto oom;
krb5_cas[i]->subjectKeyIdentifier.data = (char *)p;
i2d_ASN1_OCTET_STRING(ikeyid, &p);
krb5_cas[i]->subjectKeyIdentifier.length = len;
ASN1_OCTET_STRING_free(ikeyid);
}
}
PKCS7_ISSUER_AND_SERIAL_free(is);
is = NULL;
}
*ids = krb5_cas;
return 0;
oom:
free_krb5_external_principal_identifier(&krb5_cas);
PKCS7_ISSUER_AND_SERIAL_free(is);
return ENOMEM;
}
static krb5_error_code
create_krb5_invalidCertificates(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_external_principal_identifier *** ids)
{
krb5_error_code retval = ENOMEM;
STACK_OF(X509) *sk = NULL;
*ids = NULL;
if (req_cryptoctx->received_cert == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
sk = sk_X509_new_null();
if (sk == NULL)
goto cleanup;
sk_X509_push(sk, req_cryptoctx->received_cert);
retval = create_identifiers_from_stack(sk, ids);
sk_X509_free(sk);
cleanup:
return retval;
}
krb5_error_code
create_krb5_supportedCMSTypes(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_algorithm_identifier ***oids)
{
krb5_error_code retval = ENOMEM;
krb5_algorithm_identifier **loids = NULL;
krb5_data des3oid = {0, 8, "\x2A\x86\x48\x86\xF7\x0D\x03\x07" };
*oids = NULL;
loids = malloc(2 * sizeof(krb5_algorithm_identifier *));
if (loids == NULL)
goto cleanup;
loids[1] = NULL;
loids[0] = malloc(sizeof(krb5_algorithm_identifier));
if (loids[0] == NULL) {
free(loids);
goto cleanup;
}
retval = pkinit_copy_krb5_data(&loids[0]->algorithm, &des3oid);
if (retval) {
free(loids[0]);
free(loids);
goto cleanup;
}
loids[0]->parameters.length = 0;
loids[0]->parameters.data = NULL;
*oids = loids;
retval = 0;
cleanup:
return retval;
}
krb5_error_code
create_krb5_trustedCertifiers(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_external_principal_identifier *** ids)
{
krb5_error_code retval = ENOMEM;
STACK_OF(X509) *sk = id_cryptoctx->trustedCAs;
*ids = NULL;
if (id_cryptoctx->trustedCAs == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
retval = create_identifiers_from_stack(sk, ids);
return retval;
}
krb5_error_code
create_issuerAndSerial(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char **out,
unsigned int *out_len)
{
unsigned char *p = NULL;
PKCS7_ISSUER_AND_SERIAL *is = NULL;
int len = 0;
krb5_error_code retval = ENOMEM;
X509 *cert = req_cryptoctx->received_cert;
*out = NULL;
*out_len = 0;
if (req_cryptoctx->received_cert == NULL)
return 0;
is = PKCS7_ISSUER_AND_SERIAL_new();
X509_NAME_set(&is->issuer, X509_get_issuer_name(cert));
ASN1_INTEGER_free(is->serial);
is->serial = ASN1_INTEGER_dup(X509_get_serialNumber(cert));
len = i2d_PKCS7_ISSUER_AND_SERIAL(is, NULL);
if ((p = *out = malloc((size_t) len)) == NULL)
goto cleanup;
i2d_PKCS7_ISSUER_AND_SERIAL(is, &p);
*out_len = len;
retval = 0;
cleanup:
X509_NAME_free(is->issuer);
ASN1_INTEGER_free(is->serial);
free(is);
return retval;
}
static int
pkcs7_decrypt(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
PKCS7 *p7,
BIO *data)
{
BIO *tmpmem = NULL;
int retval = 0, i = 0;
char buf[4096];
if(p7 == NULL)
return 0;
if(!PKCS7_type_is_enveloped(p7)) {
pkiDebug("wrong pkcs7 content type\n");
return 0;
}
if(!(tmpmem = pkcs7_dataDecode(context, id_cryptoctx, p7))) {
pkiDebug("unable to decrypt pkcs7 object\n");
return 0;
}
for(;;) {
i = BIO_read(tmpmem, buf, sizeof(buf));
if (i <= 0) break;
BIO_write(data, buf, i);
BIO_free_all(tmpmem);
return 1;
}
return retval;
}
krb5_error_code
pkinit_process_td_trusted_certifiers(
krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_external_principal_identifier **krb5_trusted_certifiers,
int td_type)
{
krb5_error_code retval = ENOMEM;
STACK_OF(X509_NAME) *sk_xn = NULL;
X509_NAME *xn = NULL;
PKCS7_ISSUER_AND_SERIAL *is = NULL;
ASN1_OCTET_STRING *id = NULL;
const unsigned char *p = NULL;
char buf[DN_BUF_LEN];
int i = 0;
if (td_type == TD_TRUSTED_CERTIFIERS)
pkiDebug("received trusted certifiers\n");
else
pkiDebug("received invalid certificate\n");
sk_xn = sk_X509_NAME_new_null();
while(krb5_trusted_certifiers[i] != NULL) {
if (krb5_trusted_certifiers[i]->subjectName.data != NULL) {
p = (unsigned char *)krb5_trusted_certifiers[i]->subjectName.data;
xn = d2i_X509_NAME(NULL, &p,
(int)krb5_trusted_certifiers[i]->subjectName.length);
if (xn == NULL)
goto cleanup;
X509_NAME_oneline(xn, buf, sizeof(buf));
if (td_type == TD_TRUSTED_CERTIFIERS)
pkiDebug("#%d cert = %s is trusted by kdc\n", i, buf);
else
pkiDebug("#%d cert = %s is invalid\n", i, buf);
sk_X509_NAME_push(sk_xn, xn);
}
if (krb5_trusted_certifiers[i]->issuerAndSerialNumber.data != NULL) {
p = (unsigned char *)
krb5_trusted_certifiers[i]->issuerAndSerialNumber.data;
is = d2i_PKCS7_ISSUER_AND_SERIAL(NULL, &p,
(int)krb5_trusted_certifiers[i]->issuerAndSerialNumber.length);
if (is == NULL)
goto cleanup;
X509_NAME_oneline(is->issuer, buf, sizeof(buf));
if (td_type == TD_TRUSTED_CERTIFIERS)
pkiDebug("#%d issuer = %s serial = %ld is trusted bu kdc\n", i,
buf, ASN1_INTEGER_get(is->serial));
else
pkiDebug("#%d issuer = %s serial = %ld is invalid\n", i, buf,
ASN1_INTEGER_get(is->serial));
PKCS7_ISSUER_AND_SERIAL_free(is);
}
if (krb5_trusted_certifiers[i]->subjectKeyIdentifier.data != NULL) {
p = (unsigned char *)
krb5_trusted_certifiers[i]->subjectKeyIdentifier.data;
id = d2i_ASN1_OCTET_STRING(NULL, &p,
(int)krb5_trusted_certifiers[i]->subjectKeyIdentifier.length);
if (id == NULL)
goto cleanup;
/* XXX */
ASN1_OCTET_STRING_free(id);
}
i++;
}
/* XXX Since we not doing anything with received trusted certifiers
* return an error. this is the place where we can pick a different
* client certificate based on the information in td_trusted_certifiers
*/
retval = KRB5KDC_ERR_PREAUTH_FAILED;
cleanup:
if (sk_xn != NULL)
sk_X509_NAME_pop_free(sk_xn, X509_NAME_free);
return retval;
}
static BIO *
pkcs7_dataDecode(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
PKCS7 *p7)
{
unsigned int eklen=0, tkeylen=0;
BIO *out=NULL,*etmp=NULL,*bio=NULL;
unsigned char *ek=NULL, *tkey=NULL;
ASN1_OCTET_STRING *data_body=NULL;
const EVP_CIPHER *evp_cipher=NULL;
EVP_CIPHER_CTX *evp_ctx=NULL;
X509_ALGOR *enc_alg=NULL;
STACK_OF(PKCS7_RECIP_INFO) *rsk=NULL;
PKCS7_RECIP_INFO *ri=NULL;
p7->state=PKCS7_S_HEADER;
rsk=p7->d.enveloped->recipientinfo;
enc_alg=p7->d.enveloped->enc_data->algorithm;
data_body=p7->d.enveloped->enc_data->enc_data;
evp_cipher=EVP_get_cipherbyobj(enc_alg->algorithm);
if (evp_cipher == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
goto cleanup;
}
if ((etmp=BIO_new(BIO_f_cipher())) == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,ERR_R_BIO_LIB);
goto cleanup;
}
/* It was encrypted, we need to decrypt the secret key
* with the private key */
/* RFC 4556 section 3.2.3.2 requires that there be exactly one
* recipientInfo. */
if (sk_PKCS7_RECIP_INFO_num(rsk) != 1) {
pkiDebug("invalid number of EnvelopedData RecipientInfos\n");
goto cleanup;
}
ri = sk_PKCS7_RECIP_INFO_value(rsk, 0);
(void)pkinit_decode_data(context, id_cryptoctx,
ASN1_STRING_get0_data(ri->enc_key),
ASN1_STRING_length(ri->enc_key), &ek, &eklen);
evp_ctx=NULL;
BIO_get_cipher_ctx(etmp,&evp_ctx);
if (EVP_CipherInit_ex(evp_ctx,evp_cipher,NULL,NULL,NULL,0) <= 0)
goto cleanup;
if (EVP_CIPHER_asn1_to_param(evp_ctx,enc_alg->parameter) < 0)
goto cleanup;
/* Generate a random symmetric key to avoid exposing timing data if RSA
* decryption fails the padding check. */
tkeylen = EVP_CIPHER_CTX_key_length(evp_ctx);
tkey = OPENSSL_malloc(tkeylen);
if (tkey == NULL)
goto cleanup;
if (EVP_CIPHER_CTX_rand_key(evp_ctx, tkey) <= 0)
goto cleanup;
if (ek == NULL) {
ek = tkey;
eklen = tkeylen;
tkey = NULL;
}
if (eklen != (unsigned)EVP_CIPHER_CTX_key_length(evp_ctx)) {
/* Some S/MIME clients don't use the same key
* and effective key length. The key length is
* determined by the size of the decrypted RSA key.
*/
if (!EVP_CIPHER_CTX_set_key_length(evp_ctx, (int)eklen)) {
ek = tkey;
eklen = tkeylen;
tkey = NULL;
}
}
if (EVP_CipherInit_ex(evp_ctx,NULL,NULL,ek,NULL,0) <= 0)
goto cleanup;
if (out == NULL)
out=etmp;
else
BIO_push(out,etmp);
etmp=NULL;
if (data_body->length > 0)
bio = BIO_new_mem_buf(data_body->data, data_body->length);
else {
bio=BIO_new(BIO_s_mem());
BIO_set_mem_eof_return(bio,0);
}
BIO_push(out,bio);
bio=NULL;
if (0) {
cleanup:
if (out != NULL) BIO_free_all(out);
if (etmp != NULL) BIO_free_all(etmp);
if (bio != NULL) BIO_free_all(bio);
out=NULL;
}
if (ek != NULL) {
OPENSSL_cleanse(ek, eklen);
OPENSSL_free(ek);
}
if (tkey != NULL) {
OPENSSL_cleanse(tkey, tkeylen);
OPENSSL_free(tkey);
}
return(out);
}
#ifdef DEBUG_DH
static void
print_dh(DH * dh, char *msg)
{
BIO *bio_err = NULL;
bio_err = BIO_new(BIO_s_file());
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
if (msg)
BIO_puts(bio_err, (const char *)msg);
if (dh)
DHparams_print(bio_err, dh);
BIO_puts(bio_err, "private key: ");
BN_print(bio_err, dh->priv_key);
BIO_puts(bio_err, (const char *)"\n");
BIO_free(bio_err);
}
static void
print_pubkey(BIGNUM * key, char *msg)
{
BIO *bio_err = NULL;
bio_err = BIO_new(BIO_s_file());
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
if (msg)
BIO_puts(bio_err, (const char *)msg);
if (key)
BN_print(bio_err, key);
BIO_puts(bio_err, "\n");
BIO_free(bio_err);
}
#endif
static char *
pkinit_pkcs11_code_to_text(int err)
{
int i;
static char uc[32];
for (i = 0; pkcs11_errstrings[i].text != NULL; i++)
if (pkcs11_errstrings[i].code == err)
break;
if (pkcs11_errstrings[i].text != NULL)
return (pkcs11_errstrings[i].text);
snprintf(uc, sizeof(uc), _("unknown code 0x%x"), err);
return (uc);
}
/*
* Add an item to the pkinit_identity_crypto_context's list of deferred
* identities.
*/
krb5_error_code
crypto_set_deferred_id(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
const char *identity, const char *password)
{
unsigned long ck_flags;
ck_flags = pkinit_get_deferred_id_flags(id_cryptoctx->deferred_ids,
identity);
return pkinit_set_deferred_id(&id_cryptoctx->deferred_ids,
identity, ck_flags, password);
}
/*
* Retrieve a read-only copy of the pkinit_identity_crypto_context's list of
* deferred identities, sure to be valid only until the next time someone calls
* either pkinit_set_deferred_id() or crypto_set_deferred_id().
*/
const pkinit_deferred_id *
crypto_get_deferred_ids(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx)
{
pkinit_deferred_id *deferred;
const pkinit_deferred_id *ret;
deferred = id_cryptoctx->deferred_ids;
ret = (const pkinit_deferred_id *)deferred;
return ret;
}
/* Return the received certificate as DER-encoded data. */
krb5_error_code
crypto_encode_der_cert(krb5_context context, pkinit_req_crypto_context reqctx,
uint8_t **der_out, size_t *der_len)
{
int len;
unsigned char *der, *p;
*der_out = NULL;
*der_len = 0;
if (reqctx->received_cert == NULL)
return EINVAL;
p = NULL;
len = i2d_X509(reqctx->received_cert, NULL);
if (len <= 0)
return EINVAL;
p = der = malloc(len);
if (der == NULL)
return ENOMEM;
if (i2d_X509(reqctx->received_cert, &p) <= 0) {
free(der);
return EINVAL;
}
*der_out = der;
*der_len = len;
return 0;
}
/*
* Get the certificate matching data from the request certificate.
*/
krb5_error_code
crypto_req_cert_matching_data(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
pkinit_cert_matching_data **md_out)
{
*md_out = NULL;
if (reqctx == NULL || reqctx->received_cert == NULL)
return ENOENT;
return get_matching_data(context, plgctx, reqctx, reqctx->received_cert,
md_out);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2834_0 |
crossvul-cpp_data_good_552_3 | /*
* Boa, an http server
* Copyright (C) 1995 Paul Phillips <paulp@go2net.com>
* Copyright (C) 1996-1999 Larry Doolittle <ldoolitt@boa.org>
* Copyright (C) 1999-2004 Jon Nelson <jnelson@boa.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 1, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
/* $Id: log.c,v 1.36.2.27 2005/02/22 14:11:29 jnelson Exp $*/
#include "boa.h"
int cgi_log_fd;
/*
* Name: open_logs
*
* Description: Opens access log, error log, and if specified, CGI log
* Ties stderr to error log, except during CGI execution, at which
* time CGI log is the stderr for CGIs.
*
* Access log is line buffered, error log is not buffered.
*
*/
void open_logs(void)
{
int access_log;
/* if error_log_name is set, dup2 stderr to it */
/* otherwise, leave stderr alone */
/* we don't want to tie stderr to /dev/null */
if (error_log_name) {
int error_log;
/* open the log file */
error_log = open_gen_fd(error_log_name);
if (error_log < 0) {
DIE("unable to open error log");
}
/* redirect stderr to error_log */
if (dup2(error_log, STDERR_FILENO) == -1) {
DIE("unable to dup2 the error log");
}
close(error_log);
}
if (access_log_name) {
access_log = open_gen_fd(access_log_name);
} else {
access_log = open("/dev/null", 0);
}
if (access_log < 0) {
DIE("unable to open access log");
}
if (dup2(access_log, STDOUT_FILENO) == -1) {
DIE("can't dup2 /dev/null to STDOUT_FILENO");
}
if (fcntl(access_log, F_SETFD, 1) == -1) {
DIE("unable to set close-on-exec flag for access_log");
}
close(access_log);
if (cgi_log_name) {
cgi_log_fd = open_gen_fd(cgi_log_name);
if (cgi_log_fd == -1) {
WARN("open cgi_log");
free(cgi_log_name);
cgi_log_name = NULL;
cgi_log_fd = 0;
} else {
if (fcntl(cgi_log_fd, F_SETFD, 1) == -1) {
WARN("unable to set close-on-exec flag for cgi_log");
free(cgi_log_name);
cgi_log_name = NULL;
close(cgi_log_fd);
cgi_log_fd = 0;
}
}
}
#ifdef SETVBUF_REVERSED
setvbuf(stderr, _IONBF, (char *) NULL, 0);
setvbuf(stdout, _IOLBF, (char *) NULL, 0);
#else
setvbuf(stderr, (char *) NULL, _IONBF, 0);
setvbuf(stdout, (char *) NULL, _IOLBF, 0);
#endif
}
/* Print the remote IP to the stream FP. */
static void
print_remote_ip (request * req, FILE *fp)
{
if (log_forwarded_for) {
const char *s = req->header_forwarded_for;
if (s && *s) {
for (; *s; s++) {
/* Take extra care not to write bogus characters. In
particular no spaces. We know that only IP addresses
and a comma are allowed in the XFF header. */
if (strchr ("0123456789.abcdef:ABCDEF,", *s))
putc (*s, fp);
else
putc ('_', fp);
}
}
else /* Missing - print remote IP in parenthesis. */
fprintf (fp, "(%s)", req->remote_ip_addr);
}
else
fputs (req->remote_ip_addr, fp);
}
/*
* Name: log_access
*
* Description: Writes log data to access_log.
*/
/* NOTES on the commonlog format:
* Taken from notes on the NetBuddy program
* http://www.computer-dynamics.com/commonlog.html
remotehost
remotehost rfc931 authuser [date] "request" status bytes
remotehost - IP of the client
rfc931 - remote name of the user (always '-')
authuser - username entered for authentication - almost always '-'
[date] - the date in [08/Nov/1997:01:05:03 -0600] (with brackets) format
"request" - literal request from the client (boa may clean this up,
replacing control-characters with '_' perhaps - NOTE: not done)
status - http status code
bytes - number of bytes transferred
boa appends:
referer
user-agent
and may prepend (depending on configuration):
virtualhost - the name or IP (depending on whether name-based
virtualhosting is enabled) of the host the client accessed
*/
void log_access(request * req)
{
if (!access_log_name)
return;
if (virtualhost) {
printf("%s ", req->local_ip_addr);
} else if (vhost_root) {
printf("%s ", (req->host ? req->host : "(null)"));
}
print_remote_ip (req, stdout);
printf(" - - %s\"%s\" %d %zu \"%s\" \"%s\"\n",
get_commonlog_time(),
req->logline ? req->logline : "-",
req->response_status,
req->bytes_written,
(req->header_referer ? req->header_referer : "-"),
(req->header_user_agent ? req->header_user_agent : "-"));
}
static char *escape_pathname(const char *inp)
{
const unsigned char *s;
char *escaped, *d;
if (!inp) {
return NULL;
}
escaped = malloc (4 * strlen(inp) + 1);
if (!escaped) {
perror("malloc");
return NULL;
}
for (d = escaped, s = (const unsigned char *)inp; *s; s++) {
if (needs_escape (*s)) {
snprintf (d, 5, "\\x%02x", *s);
d += strlen (d);
} else {
*d++ = *s;
}
}
*d++ = '\0';
return escaped;
}
/*
* Name: log_error_doc
*
* Description: Logs the current time and transaction identification
* to the stderr (the error log):
* should always be followed by an fprintf to stderr
*
* Example output:
[08/Nov/1997:01:05:03 -0600] request from 192.228.331.232 "GET /~joeblow/dir/ HTTP/1.0" ("/usr/user1/joeblow/public_html/dir/"): write: Broken pipe
Apache uses:
[Wed Oct 11 14:32:52 2000] [error] [client 127.0.0.1] client denied by server configuration: /export/home/live/ap/htdocs/test
*/
void log_error_doc(request * req)
{
int errno_save = errno;
char *escaped_pathname;
if (virtualhost) {
fprintf(stderr, "%s ", req->local_ip_addr);
} else if (vhost_root) {
fprintf(stderr, "%s ", (req->host ? req->host : "(null)"));
}
escaped_pathname = escape_pathname(req->pathname);
print_remote_ip (req, stderr);
if (vhost_root) {
fprintf(stderr, " - - %srequest [%s] \"%s\" (\"%s\"): ",
get_commonlog_time(),
(req->header_host ? req->header_host : "(null)"),
(req->logline ? req->logline : "(null)"),
(escaped_pathname ? escaped_pathname : "(null)"));
} else {
fprintf(stderr, " - - %srequest \"%s\" (\"%s\"): ",
get_commonlog_time(),
(req->logline ? req->logline : "(null)"),
(escaped_pathname ? escaped_pathname : "(null)"));
}
free(escaped_pathname);
errno = errno_save;
}
/*
* Name: boa_perror
*
* Description: logs an error to user and error file both
*
*/
void boa_perror(request * req, const char *message)
{
log_error_doc(req);
perror(message); /* don't need to save errno because log_error_doc does */
send_r_error(req);
}
/*
* Name: log_error_time
*
* Description: Logs the current time to the stderr (the error log):
* should always be followed by an fprintf to stderr
*/
void log_error_time(void)
{
int errno_save = errno;
fputs(get_commonlog_time(), stderr);
errno = errno_save;
}
/*
* Name: log_error
*
* Description: performs a log_error_time and writes a message to stderr
*
*/
void log_error(const char *mesg)
{
fprintf(stderr, "%s%s", get_commonlog_time(), mesg);
}
/*
* Name: log_error_mesg
*
* Description: performs a log_error_time, writes the file and lineno
* to stderr (saving errno), and then a perror with message
*
*/
#ifdef HAVE_FUNC
void log_error_mesg(const char *file, int line, const char *func, const char *mesg)
{
int errno_save = errno;
fprintf(stderr, "%s%s:%d (%s) - ", get_commonlog_time(), file, line, func);
errno = errno_save;
perror(mesg);
errno = errno_save;
}
void log_error_mesg_fatal(const char *file, int line, const char *func, const char *mesg)
{
int errno_save = errno;
fprintf(stderr, "%s%s:%d (%s) - ", get_commonlog_time(), file, line, func);
errno = errno_save;
perror(mesg);
exit(EXIT_FAILURE);
}
#else
void log_error_mesg(const char *file, int line, const char *mesg)
{
int errno_save = errno;
fprintf(stderr, "%s%s:%d - ", get_commonlog_time(), file, line);
errno = errno_save;
perror(mesg);
errno = errno_save;
}
void log_error_mesg_fatal(const char *file, int line, const char *mesg)
{
int errno_save = errno;
fprintf(stderr, "%s%s:%d - ", get_commonlog_time(), file, line);
errno = errno_save;
perror(mesg);
exit(EXIT_FAILURE);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_552_3 |
crossvul-cpp_data_bad_5871_1 |
/* -*- C -*- */
/*
* block_template.c : Generic framework for block encryption algorithms
*
* Written by Andrew Kuchling and others
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*/
#include "pycrypto_common.h"
#include "modsupport.h"
#include <string.h>
#include "_counter.h"
/* Cipher operation modes */
#define MODE_ECB 1
#define MODE_CBC 2
#define MODE_CFB 3
#define MODE_PGP 4
#define MODE_OFB 5
#define MODE_CTR 6
#define _STR(x) #x
#define _XSTR(x) _STR(x)
#define _PASTE(x,y) x##y
#define _PASTE2(x,y) _PASTE(x,y)
#ifdef IS_PY3K
#define _MODULE_NAME _PASTE2(PyInit_,MODULE_NAME)
#else
#define _MODULE_NAME _PASTE2(init,MODULE_NAME)
#endif
#define _MODULE_STRING _XSTR(MODULE_NAME)
/* Object references for the counter_shortcut */
static PyObject *_counter_module = NULL;
static PyTypeObject *PCT_CounterBEType = NULL;
static PyTypeObject *PCT_CounterLEType = NULL;
typedef struct
{
PyObject_HEAD
int mode, count, segment_size;
unsigned char IV[BLOCK_SIZE], oldCipher[BLOCK_SIZE];
PyObject *counter;
int counter_shortcut;
block_state st;
} ALGobject;
/* Please see PEP3123 for a discussion of PyObject_HEAD and changes made in 3.x to make it conform to Standard C.
* These changes also dictate using Py_TYPE to check type, and PyVarObject_HEAD_INIT(NULL, 0) to initialize
*/
staticforward PyTypeObject ALGtype;
static ALGobject *
newALGobject(void)
{
ALGobject * new;
new = PyObject_New(ALGobject, &ALGtype);
new->mode = MODE_ECB;
new->counter = NULL;
new->counter_shortcut = 0;
return new;
}
static void
ALGdealloc(PyObject *ptr)
{
ALGobject *self = (ALGobject *)ptr;
/* Overwrite the contents of the object */
Py_XDECREF(self->counter);
self->counter = NULL;
memset(self->IV, 0, BLOCK_SIZE);
memset(self->oldCipher, 0, BLOCK_SIZE);
memset((char*)&(self->st), 0, sizeof(block_state));
self->mode = self->count = self->segment_size = 0;
PyObject_Del(ptr);
}
static char ALGnew__doc__[] =
"new(key, [mode], [IV]): Return a new " _MODULE_STRING " encryption object.";
static char *kwlist[] = {"key", "mode", "IV", "counter", "segment_size",
#ifdef PCT_ARC2_MODULE
"effective_keylen",
#endif
NULL};
static ALGobject *
ALGnew(PyObject *self, PyObject *args, PyObject *kwdict)
{
unsigned char *key, *IV;
ALGobject * new=NULL;
int keylen, IVlen=0, mode=MODE_ECB, segment_size=0;
PyObject *counter = NULL;
int counter_shortcut = 0;
#ifdef PCT_ARC2_MODULE
int effective_keylen = 1024; /* this is a weird default, but it's compatible with old versions of PyCrypto */
#endif
/* Set default values */
if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s#|is#Oi"
#ifdef PCT_ARC2_MODULE
"i"
#endif
, kwlist,
&key, &keylen, &mode, &IV, &IVlen,
&counter, &segment_size
#ifdef PCT_ARC2_MODULE
, &effective_keylen
#endif
))
{
return NULL;
}
if (mode<MODE_ECB || mode>MODE_CTR)
{
PyErr_Format(PyExc_ValueError,
"Unknown cipher feedback mode %i",
mode);
return NULL;
}
if (mode == MODE_PGP) {
PyErr_Format(PyExc_ValueError,
"MODE_PGP is not supported anymore");
return NULL;
}
if (KEY_SIZE!=0 && keylen!=KEY_SIZE)
{
PyErr_Format(PyExc_ValueError,
"Key must be %i bytes long, not %i",
KEY_SIZE, keylen);
return NULL;
}
if (KEY_SIZE==0 && keylen==0)
{
PyErr_SetString(PyExc_ValueError,
"Key cannot be the null string");
return NULL;
}
if (IVlen != BLOCK_SIZE && mode != MODE_ECB && mode != MODE_CTR)
{
PyErr_Format(PyExc_ValueError,
"IV must be %i bytes long", BLOCK_SIZE);
return NULL;
}
/* Mode-specific checks */
if (mode == MODE_CFB) {
if (segment_size == 0) segment_size = 8;
if (segment_size < 1 || segment_size > BLOCK_SIZE*8 || ((segment_size & 7) != 0)) {
PyErr_Format(PyExc_ValueError,
"segment_size must be multiple of 8 (bits) "
"between 1 and %i", BLOCK_SIZE*8);
return NULL;
}
}
if (mode == MODE_CTR) {
if (counter == NULL) {
PyErr_SetString(PyExc_TypeError,
"'counter' keyword parameter is required with CTR mode");
return NULL;
} else if (Py_TYPE(counter) == PCT_CounterBEType || Py_TYPE(counter) == PCT_CounterLEType) {
counter_shortcut = 1;
} else if (!PyCallable_Check(counter)) {
PyErr_SetString(PyExc_ValueError,
"'counter' parameter must be a callable object");
return NULL;
}
} else {
if (counter != NULL) {
PyErr_SetString(PyExc_ValueError,
"'counter' parameter only useful with CTR mode");
return NULL;
}
}
/* Cipher-specific checks */
#ifdef PCT_ARC2_MODULE
if (effective_keylen<0 || effective_keylen>1024) {
PyErr_Format(PyExc_ValueError,
"RC2: effective_keylen must be between 0 and 1024, not %i",
effective_keylen);
return NULL;
}
#endif
/* Copy parameters into object */
new = newALGobject();
new->segment_size = segment_size;
new->counter = counter;
Py_XINCREF(counter);
new->counter_shortcut = counter_shortcut;
#ifdef PCT_ARC2_MODULE
new->st.effective_keylen = effective_keylen;
#endif
block_init(&(new->st), key, keylen);
if (PyErr_Occurred())
{
Py_DECREF(new);
return NULL;
}
memset(new->IV, 0, BLOCK_SIZE);
memset(new->oldCipher, 0, BLOCK_SIZE);
memcpy(new->IV, IV, IVlen);
new->mode = mode;
new->count=BLOCK_SIZE; /* stores how many bytes in new->oldCipher have been used */
return new;
}
static char ALG_Encrypt__doc__[] =
"Encrypt the provided string of binary data.";
static PyObject *
ALG_Encrypt(ALGobject *self, PyObject *args)
{
unsigned char *buffer, *str;
unsigned char temp[BLOCK_SIZE];
int i, j, len;
PyObject *result;
if (!PyArg_Parse(args, "s#", &str, &len))
return NULL;
if (len==0) /* Handle empty string */
{
return PyBytes_FromStringAndSize(NULL, 0);
}
if ( (len % BLOCK_SIZE) !=0 &&
(self->mode!=MODE_CFB) &&
(self->mode!=MODE_OFB) &&
(self->mode!=MODE_CTR))
{
PyErr_Format(PyExc_ValueError,
"Input strings must be "
"a multiple of %i in length",
BLOCK_SIZE);
return NULL;
}
if (self->mode == MODE_CFB &&
(len % (self->segment_size/8) !=0)) {
PyErr_Format(PyExc_ValueError,
"Input strings must be a multiple of "
"the segment size %i in length",
self->segment_size/8);
return NULL;
}
buffer=malloc(len);
if (buffer==NULL)
{
PyErr_SetString(PyExc_MemoryError,
"No memory available in "
_MODULE_STRING " encrypt");
return NULL;
}
Py_BEGIN_ALLOW_THREADS;
switch(self->mode)
{
case(MODE_ECB):
for(i=0; i<len; i+=BLOCK_SIZE)
{
block_encrypt(&(self->st), str+i, buffer+i);
}
break;
case(MODE_CBC):
for(i=0; i<len; i+=BLOCK_SIZE)
{
for(j=0; j<BLOCK_SIZE; j++)
{
temp[j]=str[i+j]^self->IV[j];
}
block_encrypt(&(self->st), temp, buffer+i);
memcpy(self->IV, buffer+i, BLOCK_SIZE);
}
break;
case(MODE_CFB):
for(i=0; i<len; i+=self->segment_size/8)
{
block_encrypt(&(self->st), self->IV, temp);
for (j=0; j<self->segment_size/8; j++) {
buffer[i+j] = str[i+j] ^ temp[j];
}
if (self->segment_size == BLOCK_SIZE * 8) {
/* s == b: segment size is identical to
the algorithm block size */
memcpy(self->IV, buffer + i, BLOCK_SIZE);
}
else if ((self->segment_size % 8) == 0) {
int sz = self->segment_size/8;
memmove(self->IV, self->IV + sz,
BLOCK_SIZE-sz);
memcpy(self->IV + BLOCK_SIZE - sz, buffer + i,
sz);
}
else {
/* segment_size is not a multiple of 8;
currently this can't happen */
}
}
break;
case(MODE_OFB):
/* OFB mode is a stream cipher whose keystream is generated by encrypting the previous ciphered output.
* - self->IV stores the current keystream block
* - self->count indicates the current offset within the current keystream block
* - str stores the input string
* - buffer stores the output string
* - len indicates the length of the input and output strings
* - i indicates the current offset within the input and output strings
* (len-i) is the number of bytes remaining to encrypt
* (BLOCK_SIZE-self->count) is the number of bytes remaining in the current keystream block
*/
i = 0;
while(i < len)
{
/* If we don't need more than what remains of the current keystream block, then just XOR it in */
if (len-i <= BLOCK_SIZE-self->count) { /* remaining_bytes_to_encrypt <= remaining_bytes_in_IV */
/* XOR until the input is used up */
for(j=0; j<(len-i); j++) {
assert(i+j < len);
assert(self->count+j < BLOCK_SIZE);
buffer[i+j] = self->IV[self->count+j] ^ str[i+j];
}
self->count += len-i;
i = len;
continue;
}
/* Use up the current keystream block */
for(j=0; j<BLOCK_SIZE-self->count; j++) {
assert(i+j < len);
assert(self->count+j < BLOCK_SIZE);
buffer[i+j] = self->IV[self->count+j] ^ str[i+j];
}
i += BLOCK_SIZE-self->count;
self->count = BLOCK_SIZE;
/* Generate a new keystream block */
block_encrypt(&(self->st), self->IV, temp);
memcpy(self->IV, temp, BLOCK_SIZE);
/* Move the pointer to the start of the keystream */
self->count = 0;
}
break;
case(MODE_CTR):
/* CTR mode is a stream cipher whose keystream is generated by encrypting unique counter values.
* - self->counter points to the Counter callable, which is
* responsible for generating keystream blocks
* - self->count indicates the current offset within the current keystream block
* - self->IV stores the current keystream block
* - str stores the input string
* - buffer stores the output string
* - len indicates the length if the input and output strings
* - i indicates the current offset within the input and output strings
* - (len-i) is the number of bytes remaining to encrypt
* - (BLOCK_SIZE-self->count) is the number of bytes remaining in the current keystream block
*/
i = 0;
while (i < len) {
/* If we don't need more than what remains of the current keystream block, then just XOR it in */
if (len-i <= BLOCK_SIZE-self->count) { /* remaining_bytes_to_encrypt <= remaining_bytes_in_IV */
/* XOR until the input is used up */
for(j=0; j<(len-i); j++) {
assert(i+j < len);
assert(self->count+j < BLOCK_SIZE);
buffer[i+j] = (self->IV[self->count+j] ^= str[i+j]);
}
self->count += len-i;
i = len;
continue;
}
/* Use up the current keystream block */
for(j=0; j<BLOCK_SIZE-self->count; j++) {
assert(i+j < len);
assert(self->count+j < BLOCK_SIZE);
buffer[i+j] = (self->IV[self->count+j] ^= str[i+j]);
}
i += BLOCK_SIZE-self->count;
self->count = BLOCK_SIZE;
/* Generate a new keystream block */
if (self->counter_shortcut) {
/* CTR mode shortcut: If we're using Util.Counter,
* bypass the normal Python function call mechanism
* and manipulate the counter directly. */
PCT_CounterObject *ctr = (PCT_CounterObject *)(self->counter);
if (ctr->carry && !ctr->allow_wraparound) {
Py_BLOCK_THREADS;
PyErr_SetString(PyExc_OverflowError,
"counter wrapped without allow_wraparound");
free(buffer);
return NULL;
}
if (ctr->buf_size != BLOCK_SIZE) {
Py_BLOCK_THREADS;
PyErr_Format(PyExc_TypeError,
"CTR counter function returned "
"string of length %zi, not %i",
ctr->buf_size, BLOCK_SIZE);
free(buffer);
return NULL;
}
block_encrypt(&(self->st),
(unsigned char *)ctr->val,
self->IV);
ctr->inc_func(ctr);
} else {
PyObject *ctr;
Py_BLOCK_THREADS;
ctr = PyObject_CallObject(self->counter, NULL);
if (ctr == NULL) {
free(buffer);
return NULL;
}
if (!PyBytes_Check(ctr))
{
PyErr_SetString(PyExc_TypeError,
"CTR counter function didn't return a bytestring");
Py_DECREF(ctr);
free(buffer);
return NULL;
}
if (PyBytes_Size(ctr) != BLOCK_SIZE) {
PyErr_Format(PyExc_TypeError,
"CTR counter function returned "
"bytestring not of length %i",
BLOCK_SIZE);
Py_DECREF(ctr);
free(buffer);
return NULL;
}
Py_UNBLOCK_THREADS;
block_encrypt(&(self->st), (unsigned char *)PyBytes_AsString(ctr),
self->IV);
Py_BLOCK_THREADS;
Py_DECREF(ctr);
Py_UNBLOCK_THREADS;
}
/* Move the pointer to the start of the keystream block */
self->count = 0;
}
break;
default:
Py_BLOCK_THREADS;
PyErr_Format(PyExc_SystemError,
"Unknown ciphertext feedback mode %i; "
"this shouldn't happen",
self->mode);
free(buffer);
return NULL;
}
Py_END_ALLOW_THREADS;
result=PyBytes_FromStringAndSize((char *) buffer, len);
free(buffer);
return(result);
}
static char ALG_Decrypt__doc__[] =
"decrypt(string): Decrypt the provided string of binary data.";
static PyObject *
ALG_Decrypt(ALGobject *self, PyObject *args)
{
unsigned char *buffer, *str;
unsigned char temp[BLOCK_SIZE];
int i, j, len;
PyObject *result;
/* CTR and OFB mode decryption is identical to encryption */
if (self->mode == MODE_CTR || self->mode == MODE_OFB)
return ALG_Encrypt(self, args);
if (!PyArg_Parse(args, "s#", &str, &len))
return NULL;
if (len==0) /* Handle empty string */
{
return PyBytes_FromStringAndSize(NULL, 0);
}
if ( (len % BLOCK_SIZE) !=0 && (self->mode!=MODE_CFB))
{
PyErr_Format(PyExc_ValueError,
"Input strings must be "
"a multiple of %i in length",
BLOCK_SIZE);
return NULL;
}
if (self->mode == MODE_CFB &&
(len % (self->segment_size/8) !=0)) {
PyErr_Format(PyExc_ValueError,
"Input strings must be a multiple of "
"the segment size %i in length",
self->segment_size/8);
return NULL;
}
buffer=malloc(len);
if (buffer==NULL)
{
PyErr_SetString(PyExc_MemoryError,
"No memory available in " _MODULE_STRING
" decrypt");
return NULL;
}
Py_BEGIN_ALLOW_THREADS;
switch(self->mode)
{
case(MODE_ECB):
for(i=0; i<len; i+=BLOCK_SIZE)
{
block_decrypt(&(self->st), str+i, buffer+i);
}
break;
case(MODE_CBC):
for(i=0; i<len; i+=BLOCK_SIZE)
{
memcpy(self->oldCipher, self->IV, BLOCK_SIZE);
block_decrypt(&(self->st), str+i, temp);
for(j=0; j<BLOCK_SIZE; j++)
{
buffer[i+j]=temp[j]^self->IV[j];
self->IV[j]=str[i+j];
}
}
break;
case(MODE_CFB):
for(i=0; i<len; i+=self->segment_size/8)
{
block_encrypt(&(self->st), self->IV, temp);
for (j=0; j<self->segment_size/8; j++) {
buffer[i+j] = str[i+j]^temp[j];
}
if (self->segment_size == BLOCK_SIZE * 8) {
/* s == b: segment size is identical to
the algorithm block size */
memcpy(self->IV, str + i, BLOCK_SIZE);
}
else if ((self->segment_size % 8) == 0) {
int sz = self->segment_size/8;
memmove(self->IV, self->IV + sz,
BLOCK_SIZE-sz);
memcpy(self->IV + BLOCK_SIZE - sz, str + i,
sz);
}
else {
/* segment_size is not a multiple of 8;
currently this can't happen */
}
}
break;
default:
Py_BLOCK_THREADS;
PyErr_Format(PyExc_SystemError,
"Unknown ciphertext feedback mode %i; "
"this shouldn't happen",
self->mode);
free(buffer);
return NULL;
}
Py_END_ALLOW_THREADS;
result=PyBytes_FromStringAndSize((char *) buffer, len);
free(buffer);
return(result);
}
/* ALG object methods */
static PyMethodDef ALGmethods[] =
{
{"encrypt", (PyCFunction) ALG_Encrypt, METH_O, ALG_Encrypt__doc__},
{"decrypt", (PyCFunction) ALG_Decrypt, METH_O, ALG_Decrypt__doc__},
{NULL, NULL} /* sentinel */
};
static int
ALGsetattr(PyObject *ptr, char *name, PyObject *v)
{
ALGobject *self=(ALGobject *)ptr;
if (strcmp(name, "IV") != 0)
{
PyErr_Format(PyExc_AttributeError,
"non-existent block cipher object attribute '%s'",
name);
return -1;
}
if (v==NULL)
{
PyErr_SetString(PyExc_AttributeError,
"Can't delete IV attribute of block cipher object");
return -1;
}
if (!PyBytes_Check(v))
{
PyErr_SetString(PyExc_TypeError,
"IV attribute of block cipher object must be bytestring");
return -1;
}
if (PyBytes_Size(v)!=BLOCK_SIZE)
{
PyErr_Format(PyExc_ValueError,
_MODULE_STRING " IV must be %i bytes long",
BLOCK_SIZE);
return -1;
}
memcpy(self->IV, PyBytes_AsString(v), BLOCK_SIZE);
return 0;
}
static PyObject *
ALGgetattro(PyObject *s, PyObject *attr)
{
ALGobject *self = (ALGobject*)s;
if (!PyString_Check(attr))
goto generic;
if (PyString_CompareWithASCIIString(attr, "IV") == 0)
{
return(PyBytes_FromStringAndSize((char *) self->IV, BLOCK_SIZE));
}
if (PyString_CompareWithASCIIString(attr, "mode") == 0)
{
return(PyInt_FromLong((long)(self->mode)));
}
if (PyString_CompareWithASCIIString(attr, "block_size") == 0)
{
return PyInt_FromLong(BLOCK_SIZE);
}
if (PyString_CompareWithASCIIString(attr, "key_size") == 0)
{
return PyInt_FromLong(KEY_SIZE);
}
generic:
#if PYTHON_API_VERSION >= 1011 /* Python 2.2 and later */
return PyObject_GenericGetAttr(s, attr);
#else
if (PyString_Check(attr) < 0) {
PyErr_SetObject(PyExc_AttributeError, attr);
return NULL;
}
return Py_FindMethod(ALGmethods, (PyObject *)self, PyString_AsString(attr));
#endif
}
/* List of functions defined in the module */
static struct PyMethodDef modulemethods[] =
{
{"new", (PyCFunction) ALGnew, METH_VARARGS|METH_KEYWORDS, ALGnew__doc__},
{NULL, NULL} /* sentinel */
};
static PyTypeObject ALGtype =
{
PyVarObject_HEAD_INIT(NULL, 0) /* deferred type init for compilation on Windows, type will be filled in at runtime */
_MODULE_STRING, /*tp_name*/
sizeof(ALGobject), /*tp_size*/
0, /*tp_itemsize*/
/* methods */
(destructor) ALGdealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
ALGsetattr, /*tp_setattr*/
0, /*tp_compare*/
(reprfunc) 0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence */
0, /*tp_as_mapping */
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
ALGgetattro, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
#if PYTHON_API_VERSION >= 1011 /* Python 2.2 and later */
0, /*tp_iter*/
0, /*tp_iternext*/
ALGmethods, /*tp_methods*/
#endif
};
#ifdef IS_PY3K
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"Crypto.Cipher." _MODULE_STRING,
NULL,
-1,
modulemethods,
NULL,
NULL,
NULL,
NULL
};
#endif
/* Initialization function for the module */
PyMODINIT_FUNC
_MODULE_NAME (void)
{
PyObject *m = NULL;
PyObject *abiver = NULL;
PyObject *__all__ = NULL;
if (PyType_Ready(&ALGtype) < 0)
goto errout;
/* Create the module and add the functions */
#ifdef IS_PY3K
m = PyModule_Create(&moduledef);
#else
m = Py_InitModule("Crypto.Cipher." _MODULE_STRING, modulemethods);
#endif
if (m == NULL)
goto errout;
/* Add the type object to the module (using the name of the module itself),
* so that its methods docstrings are discoverable by introspection tools. */
PyObject_SetAttrString(m, _MODULE_STRING, (PyObject *)&ALGtype);
/* Add some symbolic constants to the module */
PyModule_AddIntConstant(m, "MODE_ECB", MODE_ECB);
PyModule_AddIntConstant(m, "MODE_CBC", MODE_CBC);
PyModule_AddIntConstant(m, "MODE_CFB", MODE_CFB);
PyModule_AddIntConstant(m, "MODE_PGP", MODE_PGP); /** Vestigial **/
PyModule_AddIntConstant(m, "MODE_OFB", MODE_OFB);
PyModule_AddIntConstant(m, "MODE_CTR", MODE_CTR);
PyModule_AddIntConstant(m, "block_size", BLOCK_SIZE);
PyModule_AddIntConstant(m, "key_size", KEY_SIZE);
/* Import CounterBE and CounterLE from the _counter module */
Py_CLEAR(_counter_module);
_counter_module = PyImport_ImportModule("Crypto.Util._counter");
if (_counter_module == NULL)
goto errout;
PCT_CounterBEType = (PyTypeObject *)PyObject_GetAttrString(_counter_module, "CounterBE");
PCT_CounterLEType = (PyTypeObject *)PyObject_GetAttrString(_counter_module, "CounterLE");
/* Simple ABI version check in case the user doesn't re-compile all of
* the modules during an upgrade. */
abiver = PyObject_GetAttrString(_counter_module, "_PCT_CTR_ABI_VERSION");
if (PCT_CounterBEType == NULL || PyType_Check((PyObject *)PCT_CounterBEType) < 0 ||
PCT_CounterLEType == NULL || PyType_Check((PyObject *)PCT_CounterLEType) < 0 ||
abiver == NULL || PyInt_CheckExact(abiver) < 0 || PyInt_AS_LONG(abiver) != PCT_CTR_ABI_VERSION)
{
PyErr_SetString(PyExc_ImportError, "Crypto.Util._counter ABI mismatch. Was PyCrypto incorrectly compiled?");
goto errout;
}
/* Create __all__ (to help generate documentation) */
__all__ = PyList_New(10);
if (__all__ == NULL)
goto errout;
PyList_SetItem(__all__, 0, PyString_FromString(_MODULE_STRING)); /* This is the ALGType object */
PyList_SetItem(__all__, 1, PyString_FromString("new"));
PyList_SetItem(__all__, 2, PyString_FromString("MODE_ECB"));
PyList_SetItem(__all__, 3, PyString_FromString("MODE_CBC"));
PyList_SetItem(__all__, 4, PyString_FromString("MODE_CFB"));
PyList_SetItem(__all__, 5, PyString_FromString("MODE_PGP"));
PyList_SetItem(__all__, 6, PyString_FromString("MODE_OFB"));
PyList_SetItem(__all__, 7, PyString_FromString("MODE_CTR"));
PyList_SetItem(__all__, 8, PyString_FromString("block_size"));
PyList_SetItem(__all__, 9, PyString_FromString("key_size"));
PyObject_SetAttrString(m, "__all__", __all__);
out:
/* Final error check */
if (m == NULL && !PyErr_Occurred()) {
PyErr_SetString(PyExc_ImportError, "can't initialize module");
goto errout;
}
/* Free local objects here */
Py_CLEAR(abiver);
Py_CLEAR(__all__);
/* Return */
#ifdef IS_PY3K
return m;
#else
return;
#endif
errout:
/* Free the module and other global objects here */
Py_CLEAR(m);
Py_CLEAR(_counter_module);
Py_CLEAR(PCT_CounterBEType);
Py_CLEAR(PCT_CounterLEType);
goto out;
}
/* vim:set ts=4 sw=4 sts=0 noexpandtab: */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5871_1 |
crossvul-cpp_data_bad_641_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-119/c/bad_641_0 |
crossvul-cpp_data_bad_3638_0 | /*
* linux/fs/proc/root.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* proc root directory handling functions
*/
#include <asm/uaccess.h>
#include <linux/errno.h>
#include <linux/time.h>
#include <linux/proc_fs.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/module.h>
#include <linux/bitops.h>
#include <linux/mount.h>
#include <linux/pid_namespace.h>
#include "internal.h"
static int proc_test_super(struct super_block *sb, void *data)
{
return sb->s_fs_info == data;
}
static int proc_set_super(struct super_block *sb, void *data)
{
int err = set_anon_super(sb, NULL);
if (!err) {
struct pid_namespace *ns = (struct pid_namespace *)data;
sb->s_fs_info = get_pid_ns(ns);
}
return err;
}
static struct dentry *proc_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
int err;
struct super_block *sb;
struct pid_namespace *ns;
struct proc_inode *ei;
if (flags & MS_KERNMOUNT)
ns = (struct pid_namespace *)data;
else
ns = current->nsproxy->pid_ns;
sb = sget(fs_type, proc_test_super, proc_set_super, ns);
if (IS_ERR(sb))
return ERR_CAST(sb);
if (!sb->s_root) {
sb->s_flags = flags;
err = proc_fill_super(sb);
if (err) {
deactivate_locked_super(sb);
return ERR_PTR(err);
}
sb->s_flags |= MS_ACTIVE;
}
ei = PROC_I(sb->s_root->d_inode);
if (!ei->pid) {
rcu_read_lock();
ei->pid = get_pid(find_pid_ns(1, ns));
rcu_read_unlock();
}
return dget(sb->s_root);
}
static void proc_kill_sb(struct super_block *sb)
{
struct pid_namespace *ns;
ns = (struct pid_namespace *)sb->s_fs_info;
kill_anon_super(sb);
put_pid_ns(ns);
}
static struct file_system_type proc_fs_type = {
.name = "proc",
.mount = proc_mount,
.kill_sb = proc_kill_sb,
};
void __init proc_root_init(void)
{
struct vfsmount *mnt;
int err;
proc_init_inodecache();
err = register_filesystem(&proc_fs_type);
if (err)
return;
mnt = kern_mount_data(&proc_fs_type, &init_pid_ns);
if (IS_ERR(mnt)) {
unregister_filesystem(&proc_fs_type);
return;
}
init_pid_ns.proc_mnt = mnt;
proc_symlink("mounts", NULL, "self/mounts");
proc_net_init();
#ifdef CONFIG_SYSVIPC
proc_mkdir("sysvipc", NULL);
#endif
proc_mkdir("fs", NULL);
proc_mkdir("driver", NULL);
proc_mkdir("fs/nfsd", NULL); /* somewhere for the nfsd filesystem to be mounted */
#if defined(CONFIG_SUN_OPENPROMFS) || defined(CONFIG_SUN_OPENPROMFS_MODULE)
/* just give it a mountpoint */
proc_mkdir("openprom", NULL);
#endif
proc_tty_init();
#ifdef CONFIG_PROC_DEVICETREE
proc_device_tree_init();
#endif
proc_mkdir("bus", NULL);
proc_sys_init();
}
static int proc_root_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat
)
{
generic_fillattr(dentry->d_inode, stat);
stat->nlink = proc_root.nlink + nr_processes();
return 0;
}
static struct dentry *proc_root_lookup(struct inode * dir, struct dentry * dentry, struct nameidata *nd)
{
if (!proc_lookup(dir, dentry, nd)) {
return NULL;
}
return proc_pid_lookup(dir, dentry, nd);
}
static int proc_root_readdir(struct file * filp,
void * dirent, filldir_t filldir)
{
unsigned int nr = filp->f_pos;
int ret;
if (nr < FIRST_PROCESS_ENTRY) {
int error = proc_readdir(filp, dirent, filldir);
if (error <= 0)
return error;
filp->f_pos = FIRST_PROCESS_ENTRY;
}
ret = proc_pid_readdir(filp, dirent, filldir);
return ret;
}
/*
* The root /proc directory is special, as it has the
* <pid> directories. Thus we don't use the generic
* directory handling functions for that..
*/
static const struct file_operations proc_root_operations = {
.read = generic_read_dir,
.readdir = proc_root_readdir,
.llseek = default_llseek,
};
/*
* proc root can do almost nothing..
*/
static const struct inode_operations proc_root_inode_operations = {
.lookup = proc_root_lookup,
.getattr = proc_root_getattr,
};
/*
* This is the root "inode" in the /proc tree..
*/
struct proc_dir_entry proc_root = {
.low_ino = PROC_ROOT_INO,
.namelen = 5,
.mode = S_IFDIR | S_IRUGO | S_IXUGO,
.nlink = 2,
.count = ATOMIC_INIT(1),
.proc_iops = &proc_root_inode_operations,
.proc_fops = &proc_root_operations,
.parent = &proc_root,
.name = "/proc",
};
int pid_ns_prepare_proc(struct pid_namespace *ns)
{
struct vfsmount *mnt;
mnt = kern_mount_data(&proc_fs_type, ns);
if (IS_ERR(mnt))
return PTR_ERR(mnt);
ns->proc_mnt = mnt;
return 0;
}
void pid_ns_release_proc(struct pid_namespace *ns)
{
mntput(ns->proc_mnt);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3638_0 |
crossvul-cpp_data_bad_507_2 | /******************************************************************************
** Copyright (c) 2014-2018, Intel Corporation **
** All rights reserved. **
** **
** Redistribution and use in source and binary forms, with or without **
** modification, are permitted provided that the following conditions **
** are met: **
** 1. Redistributions of source code must retain the above copyright **
** notice, this list of conditions and the following disclaimer. **
** 2. Redistributions in binary form must reproduce the above copyright **
** notice, this list of conditions and the following disclaimer in the **
** documentation and/or other materials provided with the distribution. **
** 3. Neither the name of the copyright holder nor the names of its **
** contributors may be used to endorse or promote products derived **
** from this software without specific prior written permission. **
** **
** THIS SOFTWARE IS PROVIDED BY THE 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 **
** HOLDER 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. **
******************************************************************************/
/* Alexander Heinecke (Intel Corp.)
******************************************************************************/
#include <libxsmm.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <sys/time.h>
#define REPS 100
#define REALTYPE double
static double sec(struct timeval start, struct timeval end) {
return ((double)(((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)))) / 1.0e6;
}
int my_csr_reader( const char* i_csr_file_in,
unsigned int** o_row_idx,
unsigned int** o_column_idx,
REALTYPE** o_values,
unsigned int* o_row_count,
unsigned int* o_column_count,
unsigned int* o_element_count ) {
FILE *l_csr_file_handle;
const unsigned int l_line_length = 512;
char l_line[512/*l_line_length*/+1];
unsigned int l_header_read = 0;
unsigned int* l_row_idx_id = NULL;
unsigned int l_i = 0;
l_csr_file_handle = fopen( i_csr_file_in, "r" );
if ( l_csr_file_handle == NULL ) {
fprintf( stderr, "cannot open CSR file!\n" );
return -1;
}
while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) {
if ( strlen(l_line) == l_line_length ) {
fprintf( stderr, "could not read file length!\n" );
return -1;
}
/* check if we are still reading comments header */
if ( l_line[0] == '%' ) {
continue;
} else {
/* if we are the first line after comment header, we allocate our data structures */
if ( l_header_read == 0 ) {
if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) {
/* allocate CSC datastructure matching mtx file */
*o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count));
*o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1));
*o_values = (REALTYPE*) malloc(sizeof(double) * (*o_element_count));
l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count));
/* check if mallocs were successful */
if ( ( *o_row_idx == NULL ) ||
( *o_column_idx == NULL ) ||
( *o_values == NULL ) ||
( l_row_idx_id == NULL ) ) {
fprintf( stderr, "could not allocate sp data!\n" );
return -1;
}
/* set everything to zero for init */
memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1));
memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count));
memset(*o_values, 0, sizeof(double)*(*o_element_count));
memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count));
/* init column idx */
for ( l_i = 0; l_i < (*o_row_count + 1); l_i++)
(*o_row_idx)[l_i] = (*o_element_count);
/* init */
(*o_row_idx)[0] = 0;
l_i = 0;
l_header_read = 1;
} else {
fprintf( stderr, "could not csr description!\n" );
return -1;
}
/* now we read the actual content */
} else {
unsigned int l_row, l_column;
REALTYPE l_value;
/* read a line of content */
if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) {
fprintf( stderr, "could not read element!\n" );
return -1;
}
/* adjust numbers to zero termination */
l_row--;
l_column--;
/* add these values to row and value structure */
(*o_column_idx)[l_i] = l_column;
(*o_values)[l_i] = l_value;
l_i++;
/* handle columns, set id to own for this column, yeah we need to handle empty columns */
l_row_idx_id[l_row] = 1;
(*o_row_idx)[l_row+1] = l_i;
}
}
}
/* close mtx file */
fclose( l_csr_file_handle );
/* check if we read a file which was consistent */
if ( l_i != (*o_element_count) ) {
fprintf( stderr, "we were not able to read all elements!\n" );
return -1;
}
/* let's handle empty rows */
for ( l_i = 0; l_i < (*o_row_count); l_i++) {
if ( l_row_idx_id[l_i] == 0 ) {
(*o_row_idx)[l_i+1] = (*o_row_idx)[l_i];
}
}
/* free helper data structure */
if ( l_row_idx_id != NULL ) {
free( l_row_idx_id );
}
return 0;
}
int main(int argc, char* argv[]) {
char* l_csr_file;
REALTYPE* l_a_sp;
unsigned int* l_rowptr;
unsigned int* l_colidx;
unsigned int l_rowcount, l_colcount, l_elements;
REALTYPE* l_a_dense;
REALTYPE* l_b;
REALTYPE* l_c_betaone;
REALTYPE* l_c_betazero;
REALTYPE* l_c_gold_betaone;
REALTYPE* l_c_gold_betazero;
REALTYPE* l_c_dense_betaone;
REALTYPE* l_c_dense_betazero;
REALTYPE l_max_error = 0.0;
unsigned int l_m;
unsigned int l_n;
unsigned int l_k;
unsigned int l_i;
unsigned int l_j;
unsigned int l_z;
unsigned int l_elems;
unsigned int l_reps;
unsigned int l_n_block;
struct timeval l_start, l_end;
double l_total;
double alpha = 1.0;
double beta = 1.0;
char trans = 'N';
libxsmm_dfsspmdm* gemm_op_betazero = NULL;
libxsmm_dfsspmdm* gemm_op_betaone = NULL;
if (argc != 4 ) {
fprintf( stderr, "need csr-filename N reps!\n" );
exit(-1);
}
/* read sparse A */
l_csr_file = argv[1];
l_n = atoi(argv[2]);
l_reps = atoi(argv[3]);
if (my_csr_reader( l_csr_file,
&l_rowptr,
&l_colidx,
&l_a_sp,
&l_rowcount, &l_colcount, &l_elements ) != 0 )
{
exit(-1);
}
l_m = l_rowcount;
l_k = l_colcount;
printf("CSR matrix data structure we just read:\n");
printf("rows: %u, columns: %u, elements: %u\n", l_rowcount, l_colcount, l_elements);
/* allocate dense matrices */
l_a_dense = (REALTYPE*)_mm_malloc(l_k * l_m * sizeof(REALTYPE), 64);
l_b = (REALTYPE*)_mm_malloc(l_k * l_n * sizeof(REALTYPE), 64);
l_c_betazero = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64);
l_c_betaone = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64);
l_c_gold_betazero = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64);
l_c_gold_betaone = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64);
l_c_dense_betazero = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64);
l_c_dense_betaone = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64);
/* touch B */
for ( l_i = 0; l_i < l_k*l_n; l_i++) {
l_b[l_i] = (REALTYPE)libxsmm_rand_f64();
}
/* touch dense A */
for ( l_i = 0; l_i < l_k*l_m; l_i++) {
l_a_dense[l_i] = (REALTYPE)0.0;
}
/* init dense A using sparse A */
for ( l_i = 0; l_i < l_m; l_i++ ) {
l_elems = l_rowptr[l_i+1] - l_rowptr[l_i];
for ( l_z = 0; l_z < l_elems; l_z++ ) {
l_a_dense[(l_i*l_k)+l_colidx[l_rowptr[l_i]+l_z]] = l_a_sp[l_rowptr[l_i]+l_z];
}
}
/* touch C */
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
l_c_gold_betaone[l_i] = (REALTYPE)libxsmm_rand_f64();
}
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
l_c_betaone[l_i] = l_c_gold_betaone[l_i];
}
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
l_c_dense_betaone[l_i] = l_c_gold_betaone[l_i];
}
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
l_c_betazero[l_i] = l_c_betaone[l_i];
}
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
l_c_gold_betazero[l_i] = l_c_gold_betaone[l_i];
}
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
l_c_dense_betazero[l_i] = l_c_dense_betaone[l_i];
}
/* setting up fsspmdm */
l_n_block = 48;
beta = 0.0;
gemm_op_betazero = libxsmm_dfsspmdm_create( l_m, l_n_block, l_k, l_k, l_n, l_n, 1.0, beta, l_a_dense );
beta = 1.0;
gemm_op_betaone = libxsmm_dfsspmdm_create( l_m, l_n_block, l_k, l_k, l_n, l_n, 1.0, beta, l_a_dense );
/* compute golden results */
printf("computing golden solution...\n");
for ( l_j = 0; l_j < l_n; l_j++ ) {
for (l_i = 0; l_i < l_m; l_i++ ) {
l_elems = l_rowptr[l_i+1] - l_rowptr[l_i];
l_c_gold_betazero[(l_n*l_i) + l_j] = 0.0;
for (l_z = 0; l_z < l_elems; l_z++) {
l_c_gold_betazero[(l_n*l_i) + l_j] += l_a_sp[l_rowptr[l_i]+l_z] * l_b[(l_n*l_colidx[l_rowptr[l_i]+l_z])+l_j];
}
}
}
for ( l_j = 0; l_j < l_n; l_j++ ) {
for (l_i = 0; l_i < l_m; l_i++ ) {
l_elems = l_rowptr[l_i+1] - l_rowptr[l_i];
for (l_z = 0; l_z < l_elems; l_z++) {
l_c_gold_betaone[(l_n*l_i) + l_j] += l_a_sp[l_rowptr[l_i]+l_z] * l_b[(l_n*l_colidx[l_rowptr[l_i]+l_z])+l_j];
}
}
}
printf("...done!\n");
/* libxsmm generated code */
printf("computing libxsmm (A sparse) solution...\n");
#ifdef _OPENMP
#pragma omp parallel for private(l_z)
#endif
for (l_z = 0; l_z < l_n; l_z+=l_n_block) {
libxsmm_dfsspmdm_execute( gemm_op_betazero, l_b+l_z, l_c_betazero+l_z );
}
#ifdef _OPENMP
#pragma omp parallel for private(l_z)
#endif
for (l_z = 0; l_z < l_n; l_z+=l_n_block) {
libxsmm_dfsspmdm_execute( gemm_op_betaone, l_b+l_z, l_c_betaone+l_z );
}
printf("...done!\n");
/* BLAS code */
printf("computing BLAS (A dense) solution...\n");
beta = 0.0;
dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betazero, &l_n );
beta = 1.0;
dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betaone, &l_n );
printf("...done!\n");
/* check for errors */
l_max_error = (REALTYPE)0.0;
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
if (fabs(l_c_betazero[l_i]-l_c_gold_betazero[l_i]) > l_max_error ) {
l_max_error = fabs(l_c_betazero[l_i]-l_c_gold_betazero[l_i]);
}
}
printf("max error beta=0 (libxmm vs. gold): %f\n", l_max_error);
l_max_error = (REALTYPE)0.0;
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
if (fabs(l_c_betaone[l_i]-l_c_gold_betaone[l_i]) > l_max_error ) {
l_max_error = fabs(l_c_betaone[l_i]-l_c_gold_betaone[l_i]);
}
}
printf("max error beta=1 (libxmm vs. gold): %f\n", l_max_error);
l_max_error = (REALTYPE)0.0;
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
if (fabs(l_c_dense_betazero[l_i]-l_c_gold_betazero[l_i]) > l_max_error ) {
l_max_error = fabs(l_c_dense_betazero[l_i]-l_c_gold_betazero[l_i]);
}
}
printf("max error beta=0 (dense vs. gold): %f\n", l_max_error);
l_max_error = (REALTYPE)0.0;
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
if (fabs(l_c_dense_betaone[l_i]-l_c_gold_betaone[l_i]) > l_max_error ) {
l_max_error = fabs(l_c_dense_betaone[l_i]-l_c_gold_betaone[l_i]);
}
}
printf("max error beta=1 (dense vs. gold): %f\n", l_max_error);
/* Let's measure performance */
gettimeofday(&l_start, NULL);
for ( l_j = 0; l_j < l_reps; l_j++ ) {
#ifdef _OPENMP
#pragma omp parallel for private(l_z)
#endif
for (l_z = 0; l_z < l_n; l_z+=l_n_block) {
libxsmm_dfsspmdm_execute( gemm_op_betazero, l_b+l_z, l_c_betazero+l_z );
}
}
gettimeofday(&l_end, NULL);
l_total = sec(l_start, l_end);
fprintf(stdout, "time[s] LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, l_total/(double)l_reps );
fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f (sparse)\n", l_m, l_n, l_k, (2.0 * (double)l_elements * (double)l_n * (double)l_reps * 1.0e-9) / l_total );
fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f (dense)\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total );
fprintf(stdout, "GB/s LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total );
gettimeofday(&l_start, NULL);
for ( l_j = 0; l_j < l_reps; l_j++ ) {
#ifdef _OPENMP
#pragma omp parallel for private(l_z)
#endif
for (l_z = 0; l_z < l_n; l_z+=l_n_block) {
libxsmm_dfsspmdm_execute( gemm_op_betaone, l_b+l_z, l_c_betaone+l_z );
}
}
gettimeofday(&l_end, NULL);
l_total = sec(l_start, l_end);
fprintf(stdout, "time[s] LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, l_total/(double)l_reps );
fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f (sparse)\n", l_m, l_n, l_k, (2.0 * (double)l_elements * (double)l_n * (double)l_reps * 1.0e-9) / l_total );
fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f (dense)\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total );
fprintf(stdout, "GB/s LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total );
gettimeofday(&l_start, NULL);
beta = 0.0;
for ( l_j = 0; l_j < l_reps; l_j++ ) {
dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betazero, &l_n );
}
gettimeofday(&l_end, NULL);
l_total = sec(l_start, l_end);
fprintf(stdout, "time[s] MKL (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, l_total/(double)l_reps );
fprintf(stdout, "GFLOPS MKL (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total );
fprintf(stdout, "GB/s MKL (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total );
gettimeofday(&l_start, NULL);
beta = 1.0;
for ( l_j = 0; l_j < l_reps; l_j++ ) {
dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betaone, &l_n );
}
gettimeofday(&l_end, NULL);
l_total = sec(l_start, l_end);
fprintf(stdout, "time[s] MKL (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, l_total/(double)l_reps );
fprintf(stdout, "GFLOPS MKL (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total );
fprintf(stdout, "GB/s MKL (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total );
/* free */
libxsmm_dfsspmdm_destroy( gemm_op_betazero );
libxsmm_dfsspmdm_destroy( gemm_op_betaone );
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_507_2 |
crossvul-cpp_data_good_4774_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% RRRR L EEEEE %
% R R L E %
% RRRR L EEE %
% R R L E %
% R R LLLLL EEEEE %
% %
% %
% Read URT RLE Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-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/colormap.h"
#include "magick/colormap-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/pixel.h"
#include "magick/property.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s R L E %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsRLE() returns MagickTrue if the image format type, identified by the
% magick string, is RLE.
%
% The format of the ReadRLEImage method is:
%
% MagickBooleanType IsRLE(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
%
*/
static MagickBooleanType IsRLE(const unsigned char *magick,const size_t length)
{
if (length < 2)
return(MagickFalse);
if (memcmp(magick,"\122\314",2) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadRLEImage() reads a run-length encoded Utah Raster Toolkit
% image file and returns it. It allocates the memory necessary for the new
% Image structure and returns a pointer to the new image.
%
% The format of the ReadRLEImage method is:
%
% Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
%
*/
static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
IndexPacket
index;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
offset,
pixel_info_length;
ssize_t
count,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->matte=flags & 0x04 ? MagickTrue : MagickFalse;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) ||
((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate RLE pixels.
*/
if (image->matte != MagickFalse)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
MagickMax(number_planes_filled,4)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*
MagickMax(number_planes_filled,4);
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->matte == MagickFalse)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
operand++;
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
p=pixels+offset;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (IsValidColormapIndex(image,*p & mask,&index,exception) ==
MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
if (IsValidColormapIndex(image,(size_t) (x*map_length+
(*p & mask)),&index,exception) == MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p);
image->colormap[i].green=ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->matte == MagickFalse)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*p++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelRed(q,image->colormap[(ssize_t) index].red);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelGreen(q,image->colormap[(ssize_t) index].green);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelBlue(q,image->colormap[(ssize_t) index].blue);
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelPacket *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterRLEImage() adds attributes for the RLE image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterRLEImage method is:
%
% size_t RegisterRLEImage(void)
%
*/
ModuleExport size_t RegisterRLEImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("RLE");
entry->decoder=(DecodeImageHandler *) ReadRLEImage;
entry->magick=(IsImageFormatHandler *) IsRLE;
entry->adjoin=MagickFalse;
entry->description=ConstantString("Utah Run length encoded image");
entry->module=ConstantString("RLE");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterRLEImage() removes format registrations made by the
% RLE module from the list of supported formats.
%
% The format of the UnregisterRLEImage method is:
%
% UnregisterRLEImage(void)
%
*/
ModuleExport void UnregisterRLEImage(void)
{
(void) UnregisterMagickInfo("RLE");
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4774_0 |
crossvul-cpp_data_bad_183_0 | /* Redis CLI (command line interface)
*
* Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "fmacros.h"
#include "version.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <time.h>
#include <ctype.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <assert.h>
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <hiredis.h>
#include <sds.h> /* use sds.h from hiredis, so that only one set of sds functions will be present in the binary */
#include "zmalloc.h"
#include "linenoise.h"
#include "help.h"
#include "anet.h"
#include "ae.h"
#define UNUSED(V) ((void) V)
#define OUTPUT_STANDARD 0
#define OUTPUT_RAW 1
#define OUTPUT_CSV 2
#define REDIS_CLI_KEEPALIVE_INTERVAL 15 /* seconds */
#define REDIS_CLI_DEFAULT_PIPE_TIMEOUT 30 /* seconds */
#define REDIS_CLI_HISTFILE_ENV "REDISCLI_HISTFILE"
#define REDIS_CLI_HISTFILE_DEFAULT ".rediscli_history"
#define REDIS_CLI_RCFILE_ENV "REDISCLI_RCFILE"
#define REDIS_CLI_RCFILE_DEFAULT ".redisclirc"
/* --latency-dist palettes. */
int spectrum_palette_color_size = 19;
int spectrum_palette_color[] = {0,233,234,235,237,239,241,243,245,247,144,143,142,184,226,214,208,202,196};
int spectrum_palette_mono_size = 13;
int spectrum_palette_mono[] = {0,233,234,235,237,239,241,243,245,247,249,251,253};
/* The actual palette in use. */
int *spectrum_palette;
int spectrum_palette_size;
static redisContext *context;
static struct config {
char *hostip;
int hostport;
char *hostsocket;
long repeat;
long interval;
int dbnum;
int interactive;
int shutdown;
int monitor_mode;
int pubsub_mode;
int latency_mode;
int latency_dist_mode;
int latency_history;
int lru_test_mode;
long long lru_test_sample_size;
int cluster_mode;
int cluster_reissue_command;
int slave_mode;
int pipe_mode;
int pipe_timeout;
int getrdb_mode;
int stat_mode;
int scan_mode;
int intrinsic_latency_mode;
int intrinsic_latency_duration;
char *pattern;
char *rdb_filename;
int bigkeys;
int hotkeys;
int stdinarg; /* get last arg from stdin. (-x option) */
char *auth;
int output; /* output mode, see OUTPUT_* defines */
sds mb_delim;
char prompt[128];
char *eval;
int eval_ldb;
int eval_ldb_sync; /* Ask for synchronous mode of the Lua debugger. */
int eval_ldb_end; /* Lua debugging session ended. */
int enable_ldb_on_eval; /* Handle manual SCRIPT DEBUG + EVAL commands. */
int last_cmd_type;
} config;
/* User preferences. */
static struct pref {
int hints;
} pref;
static volatile sig_atomic_t force_cancel_loop = 0;
static void usage(void);
static void slaveMode(void);
char *redisGitSHA1(void);
char *redisGitDirty(void);
static int cliConnect(int force);
/*------------------------------------------------------------------------------
* Utility functions
*--------------------------------------------------------------------------- */
static long long ustime(void) {
struct timeval tv;
long long ust;
gettimeofday(&tv, NULL);
ust = ((long long)tv.tv_sec)*1000000;
ust += tv.tv_usec;
return ust;
}
static long long mstime(void) {
return ustime()/1000;
}
static void cliRefreshPrompt(void) {
int len;
if (config.eval_ldb) return;
if (config.hostsocket != NULL)
len = snprintf(config.prompt,sizeof(config.prompt),"redis %s",
config.hostsocket);
else
len = anetFormatAddr(config.prompt, sizeof(config.prompt),
config.hostip, config.hostport);
/* Add [dbnum] if needed */
if (config.dbnum != 0)
len += snprintf(config.prompt+len,sizeof(config.prompt)-len,"[%d]",
config.dbnum);
snprintf(config.prompt+len,sizeof(config.prompt)-len,"> ");
}
/* Return the name of the dotfile for the specified 'dotfilename'.
* Normally it just concatenates user $HOME to the file specified
* in 'dotfilename'. However if the environment varialbe 'envoverride'
* is set, its value is taken as the path.
*
* The function returns NULL (if the file is /dev/null or cannot be
* obtained for some error), or an SDS string that must be freed by
* the user. */
static sds getDotfilePath(char *envoverride, char *dotfilename) {
char *path = NULL;
sds dotPath = NULL;
/* Check the env for a dotfile override. */
path = getenv(envoverride);
if (path != NULL && *path != '\0') {
if (!strcmp("/dev/null", path)) {
return NULL;
}
/* If the env is set, return it. */
dotPath = sdsnew(path);
} else {
char *home = getenv("HOME");
if (home != NULL && *home != '\0') {
/* If no override is set use $HOME/<dotfilename>. */
dotPath = sdscatprintf(sdsempty(), "%s/%s", home, dotfilename);
}
}
return dotPath;
}
/* URL-style percent decoding. */
#define isHexChar(c) (isdigit(c) || (c >= 'a' && c <= 'f'))
#define decodeHexChar(c) (isdigit(c) ? c - '0' : c - 'a' + 10)
#define decodeHex(h, l) ((decodeHexChar(h) << 4) + decodeHexChar(l))
static sds percentDecode(const char *pe, size_t len) {
const char *end = pe + len;
sds ret = sdsempty();
const char *curr = pe;
while (curr < end) {
if (*curr == '%') {
if ((end - curr) < 2) {
fprintf(stderr, "Incomplete URI encoding\n");
exit(1);
}
char h = tolower(*(++curr));
char l = tolower(*(++curr));
if (!isHexChar(h) || !isHexChar(l)) {
fprintf(stderr, "Illegal character in URI encoding\n");
exit(1);
}
char c = decodeHex(h, l);
ret = sdscatlen(ret, &c, 1);
curr++;
} else {
ret = sdscatlen(ret, curr++, 1);
}
}
return ret;
}
/* Parse a URI and extract the server connection information.
* URI scheme is based on the the provisional specification[1] excluding support
* for query parameters. Valid URIs are:
* scheme: "redis://"
* authority: [<username> ":"] <password> "@"] [<hostname> [":" <port>]]
* path: ["/" [<db>]]
*
* [1]: https://www.iana.org/assignments/uri-schemes/prov/redis */
static void parseRedisUri(const char *uri) {
const char *scheme = "redis://";
const char *curr = uri;
const char *end = uri + strlen(uri);
const char *userinfo, *username, *port, *host, *path;
/* URI must start with a valid scheme. */
if (strncasecmp(scheme, curr, strlen(scheme))) {
fprintf(stderr,"Invalid URI scheme\n");
exit(1);
}
curr += strlen(scheme);
if (curr == end) return;
/* Extract user info. */
if ((userinfo = strchr(curr,'@'))) {
if ((username = strchr(curr, ':')) && username < userinfo) {
/* If provided, username is ignored. */
curr = username + 1;
}
config.auth = percentDecode(curr, userinfo - curr);
curr = userinfo + 1;
}
if (curr == end) return;
/* Extract host and port. */
path = strchr(curr, '/');
if (*curr != '/') {
host = path ? path - 1 : end;
if ((port = strchr(curr, ':'))) {
config.hostport = atoi(port + 1);
host = port - 1;
}
config.hostip = sdsnewlen(curr, host - curr + 1);
}
curr = path ? path + 1 : end;
if (curr == end) return;
/* Extract database number. */
config.dbnum = atoi(curr);
}
/*------------------------------------------------------------------------------
* Help functions
*--------------------------------------------------------------------------- */
#define CLI_HELP_COMMAND 1
#define CLI_HELP_GROUP 2
typedef struct {
int type;
int argc;
sds *argv;
sds full;
/* Only used for help on commands */
struct commandHelp *org;
} helpEntry;
static helpEntry *helpEntries;
static int helpEntriesLen;
static sds cliVersion(void) {
sds version;
version = sdscatprintf(sdsempty(), "%s", REDIS_VERSION);
/* Add git commit and working tree status when available */
if (strtoll(redisGitSHA1(),NULL,16)) {
version = sdscatprintf(version, " (git:%s", redisGitSHA1());
if (strtoll(redisGitDirty(),NULL,10))
version = sdscatprintf(version, "-dirty");
version = sdscat(version, ")");
}
return version;
}
static void cliInitHelp(void) {
int commandslen = sizeof(commandHelp)/sizeof(struct commandHelp);
int groupslen = sizeof(commandGroups)/sizeof(char*);
int i, len, pos = 0;
helpEntry tmp;
helpEntriesLen = len = commandslen+groupslen;
helpEntries = zmalloc(sizeof(helpEntry)*len);
for (i = 0; i < groupslen; i++) {
tmp.argc = 1;
tmp.argv = zmalloc(sizeof(sds));
tmp.argv[0] = sdscatprintf(sdsempty(),"@%s",commandGroups[i]);
tmp.full = tmp.argv[0];
tmp.type = CLI_HELP_GROUP;
tmp.org = NULL;
helpEntries[pos++] = tmp;
}
for (i = 0; i < commandslen; i++) {
tmp.argv = sdssplitargs(commandHelp[i].name,&tmp.argc);
tmp.full = sdsnew(commandHelp[i].name);
tmp.type = CLI_HELP_COMMAND;
tmp.org = &commandHelp[i];
helpEntries[pos++] = tmp;
}
}
/* cliInitHelp() setups the helpEntries array with the command and group
* names from the help.h file. However the Redis instance we are connecting
* to may support more commands, so this function integrates the previous
* entries with additional entries obtained using the COMMAND command
* available in recent versions of Redis. */
static void cliIntegrateHelp(void) {
if (cliConnect(0) == REDIS_ERR) return;
redisReply *reply = redisCommand(context, "COMMAND");
if(reply == NULL || reply->type != REDIS_REPLY_ARRAY) return;
/* Scan the array reported by COMMAND and fill only the entries that
* don't already match what we have. */
for (size_t j = 0; j < reply->elements; j++) {
redisReply *entry = reply->element[j];
if (entry->type != REDIS_REPLY_ARRAY || entry->elements < 4 ||
entry->element[0]->type != REDIS_REPLY_STRING ||
entry->element[1]->type != REDIS_REPLY_INTEGER ||
entry->element[3]->type != REDIS_REPLY_INTEGER) return;
char *cmdname = entry->element[0]->str;
int i;
for (i = 0; i < helpEntriesLen; i++) {
helpEntry *he = helpEntries+i;
if (!strcasecmp(he->argv[0],cmdname))
break;
}
if (i != helpEntriesLen) continue;
helpEntriesLen++;
helpEntries = zrealloc(helpEntries,sizeof(helpEntry)*helpEntriesLen);
helpEntry *new = helpEntries+(helpEntriesLen-1);
new->argc = 1;
new->argv = zmalloc(sizeof(sds));
new->argv[0] = sdsnew(cmdname);
new->full = new->argv[0];
new->type = CLI_HELP_COMMAND;
sdstoupper(new->argv[0]);
struct commandHelp *ch = zmalloc(sizeof(*ch));
ch->name = new->argv[0];
ch->params = sdsempty();
int args = llabs(entry->element[1]->integer);
if (entry->element[3]->integer == 1) {
ch->params = sdscat(ch->params,"key ");
args--;
}
while(args--) ch->params = sdscat(ch->params,"arg ");
if (entry->element[1]->integer < 0)
ch->params = sdscat(ch->params,"...options...");
ch->summary = "Help not available";
ch->group = 0;
ch->since = "not known";
new->org = ch;
}
freeReplyObject(reply);
}
/* Output command help to stdout. */
static void cliOutputCommandHelp(struct commandHelp *help, int group) {
printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help->name, help->params);
printf(" \x1b[33msummary:\x1b[0m %s\r\n", help->summary);
printf(" \x1b[33msince:\x1b[0m %s\r\n", help->since);
if (group) {
printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups[help->group]);
}
}
/* Print generic help. */
static void cliOutputGenericHelp(void) {
sds version = cliVersion();
printf(
"redis-cli %s\n"
"To get help about Redis commands type:\n"
" \"help @<group>\" to get a list of commands in <group>\n"
" \"help <command>\" for help on <command>\n"
" \"help <tab>\" to get a list of possible help topics\n"
" \"quit\" to exit\n"
"\n"
"To set redis-cli preferences:\n"
" \":set hints\" enable online hints\n"
" \":set nohints\" disable online hints\n"
"Set your preferences in ~/.redisclirc\n",
version
);
sdsfree(version);
}
/* Output all command help, filtering by group or command name. */
static void cliOutputHelp(int argc, char **argv) {
int i, j, len;
int group = -1;
helpEntry *entry;
struct commandHelp *help;
if (argc == 0) {
cliOutputGenericHelp();
return;
} else if (argc > 0 && argv[0][0] == '@') {
len = sizeof(commandGroups)/sizeof(char*);
for (i = 0; i < len; i++) {
if (strcasecmp(argv[0]+1,commandGroups[i]) == 0) {
group = i;
break;
}
}
}
assert(argc > 0);
for (i = 0; i < helpEntriesLen; i++) {
entry = &helpEntries[i];
if (entry->type != CLI_HELP_COMMAND) continue;
help = entry->org;
if (group == -1) {
/* Compare all arguments */
if (argc == entry->argc) {
for (j = 0; j < argc; j++) {
if (strcasecmp(argv[j],entry->argv[j]) != 0) break;
}
if (j == argc) {
cliOutputCommandHelp(help,1);
}
}
} else {
if (group == help->group) {
cliOutputCommandHelp(help,0);
}
}
}
printf("\r\n");
}
/* Linenoise completion callback. */
static void completionCallback(const char *buf, linenoiseCompletions *lc) {
size_t startpos = 0;
int mask;
int i;
size_t matchlen;
sds tmp;
if (strncasecmp(buf,"help ",5) == 0) {
startpos = 5;
while (isspace(buf[startpos])) startpos++;
mask = CLI_HELP_COMMAND | CLI_HELP_GROUP;
} else {
mask = CLI_HELP_COMMAND;
}
for (i = 0; i < helpEntriesLen; i++) {
if (!(helpEntries[i].type & mask)) continue;
matchlen = strlen(buf+startpos);
if (strncasecmp(buf+startpos,helpEntries[i].full,matchlen) == 0) {
tmp = sdsnewlen(buf,startpos);
tmp = sdscat(tmp,helpEntries[i].full);
linenoiseAddCompletion(lc,tmp);
sdsfree(tmp);
}
}
}
/* Linenoise hints callback. */
static char *hintsCallback(const char *buf, int *color, int *bold) {
if (!pref.hints) return NULL;
int i, argc, buflen = strlen(buf);
sds *argv = sdssplitargs(buf,&argc);
int endspace = buflen && isspace(buf[buflen-1]);
/* Check if the argument list is empty and return ASAP. */
if (argc == 0) {
sdsfreesplitres(argv,argc);
return NULL;
}
for (i = 0; i < helpEntriesLen; i++) {
if (!(helpEntries[i].type & CLI_HELP_COMMAND)) continue;
if (strcasecmp(argv[0],helpEntries[i].full) == 0)
{
*color = 90;
*bold = 0;
sds hint = sdsnew(helpEntries[i].org->params);
/* Remove arguments from the returned hint to show only the
* ones the user did not yet typed. */
int toremove = argc-1;
while(toremove > 0 && sdslen(hint)) {
if (hint[0] == '[') break;
if (hint[0] == ' ') toremove--;
sdsrange(hint,1,-1);
}
/* Add an initial space if needed. */
if (!endspace) {
sds newhint = sdsnewlen(" ",1);
newhint = sdscatsds(newhint,hint);
sdsfree(hint);
hint = newhint;
}
sdsfreesplitres(argv,argc);
return hint;
}
}
sdsfreesplitres(argv,argc);
return NULL;
}
static void freeHintsCallback(void *ptr) {
sdsfree(ptr);
}
/*------------------------------------------------------------------------------
* Networking / parsing
*--------------------------------------------------------------------------- */
/* Send AUTH command to the server */
static int cliAuth(void) {
redisReply *reply;
if (config.auth == NULL) return REDIS_OK;
reply = redisCommand(context,"AUTH %s",config.auth);
if (reply != NULL) {
freeReplyObject(reply);
return REDIS_OK;
}
return REDIS_ERR;
}
/* Send SELECT dbnum to the server */
static int cliSelect(void) {
redisReply *reply;
if (config.dbnum == 0) return REDIS_OK;
reply = redisCommand(context,"SELECT %d",config.dbnum);
if (reply != NULL) {
int result = REDIS_OK;
if (reply->type == REDIS_REPLY_ERROR) result = REDIS_ERR;
freeReplyObject(reply);
return result;
}
return REDIS_ERR;
}
/* Connect to the server. If force is not zero the connection is performed
* even if there is already a connected socket. */
static int cliConnect(int force) {
if (context == NULL || force) {
if (context != NULL) {
redisFree(context);
}
if (config.hostsocket == NULL) {
context = redisConnect(config.hostip,config.hostport);
} else {
context = redisConnectUnix(config.hostsocket);
}
if (context->err) {
fprintf(stderr,"Could not connect to Redis at ");
if (config.hostsocket == NULL)
fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr);
else
fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr);
redisFree(context);
context = NULL;
return REDIS_ERR;
}
/* Set aggressive KEEP_ALIVE socket option in the Redis context socket
* in order to prevent timeouts caused by the execution of long
* commands. At the same time this improves the detection of real
* errors. */
anetKeepAlive(NULL, context->fd, REDIS_CLI_KEEPALIVE_INTERVAL);
/* Do AUTH and select the right DB. */
if (cliAuth() != REDIS_OK)
return REDIS_ERR;
if (cliSelect() != REDIS_OK)
return REDIS_ERR;
}
return REDIS_OK;
}
static void cliPrintContextError(void) {
if (context == NULL) return;
fprintf(stderr,"Error: %s\n",context->errstr);
}
static sds cliFormatReplyTTY(redisReply *r, char *prefix) {
sds out = sdsempty();
switch (r->type) {
case REDIS_REPLY_ERROR:
out = sdscatprintf(out,"(error) %s\n", r->str);
break;
case REDIS_REPLY_STATUS:
out = sdscat(out,r->str);
out = sdscat(out,"\n");
break;
case REDIS_REPLY_INTEGER:
out = sdscatprintf(out,"(integer) %lld\n",r->integer);
break;
case REDIS_REPLY_STRING:
/* If you are producing output for the standard output we want
* a more interesting output with quoted characters and so forth */
out = sdscatrepr(out,r->str,r->len);
out = sdscat(out,"\n");
break;
case REDIS_REPLY_NIL:
out = sdscat(out,"(nil)\n");
break;
case REDIS_REPLY_ARRAY:
if (r->elements == 0) {
out = sdscat(out,"(empty list or set)\n");
} else {
unsigned int i, idxlen = 0;
char _prefixlen[16];
char _prefixfmt[16];
sds _prefix;
sds tmp;
/* Calculate chars needed to represent the largest index */
i = r->elements;
do {
idxlen++;
i /= 10;
} while(i);
/* Prefix for nested multi bulks should grow with idxlen+2 spaces */
memset(_prefixlen,' ',idxlen+2);
_prefixlen[idxlen+2] = '\0';
_prefix = sdscat(sdsnew(prefix),_prefixlen);
/* Setup prefix format for every entry */
snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%ud) ",idxlen);
for (i = 0; i < r->elements; i++) {
/* Don't use the prefix for the first element, as the parent
* caller already prepended the index number. */
out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1);
/* Format the multi bulk entry */
tmp = cliFormatReplyTTY(r->element[i],_prefix);
out = sdscatlen(out,tmp,sdslen(tmp));
sdsfree(tmp);
}
sdsfree(_prefix);
}
break;
default:
fprintf(stderr,"Unknown reply type: %d\n", r->type);
exit(1);
}
return out;
}
int isColorTerm(void) {
char *t = getenv("TERM");
return t != NULL && strstr(t,"xterm") != NULL;
}
/* Helper function for sdsCatColorizedLdbReply() appending colorize strings
* to an SDS string. */
sds sdscatcolor(sds o, char *s, size_t len, char *color) {
if (!isColorTerm()) return sdscatlen(o,s,len);
int bold = strstr(color,"bold") != NULL;
int ccode = 37; /* Defaults to white. */
if (strstr(color,"red")) ccode = 31;
else if (strstr(color,"green")) ccode = 32;
else if (strstr(color,"yellow")) ccode = 33;
else if (strstr(color,"blue")) ccode = 34;
else if (strstr(color,"magenta")) ccode = 35;
else if (strstr(color,"cyan")) ccode = 36;
else if (strstr(color,"white")) ccode = 37;
o = sdscatfmt(o,"\033[%i;%i;49m",bold,ccode);
o = sdscatlen(o,s,len);
o = sdscat(o,"\033[0m");
return o;
}
/* Colorize Lua debugger status replies according to the prefix they
* have. */
sds sdsCatColorizedLdbReply(sds o, char *s, size_t len) {
char *color = "white";
if (strstr(s,"<debug>")) color = "bold";
if (strstr(s,"<redis>")) color = "green";
if (strstr(s,"<reply>")) color = "cyan";
if (strstr(s,"<error>")) color = "red";
if (strstr(s,"<hint>")) color = "bold";
if (strstr(s,"<value>") || strstr(s,"<retval>")) color = "magenta";
if (len > 4 && isdigit(s[3])) {
if (s[1] == '>') color = "yellow"; /* Current line. */
else if (s[2] == '#') color = "bold"; /* Break point. */
}
return sdscatcolor(o,s,len,color);
}
static sds cliFormatReplyRaw(redisReply *r) {
sds out = sdsempty(), tmp;
size_t i;
switch (r->type) {
case REDIS_REPLY_NIL:
/* Nothing... */
break;
case REDIS_REPLY_ERROR:
out = sdscatlen(out,r->str,r->len);
out = sdscatlen(out,"\n",1);
break;
case REDIS_REPLY_STATUS:
case REDIS_REPLY_STRING:
if (r->type == REDIS_REPLY_STATUS && config.eval_ldb) {
/* The Lua debugger replies with arrays of simple (status)
* strings. We colorize the output for more fun if this
* is a debugging session. */
/* Detect the end of a debugging session. */
if (strstr(r->str,"<endsession>") == r->str) {
config.enable_ldb_on_eval = 0;
config.eval_ldb = 0;
config.eval_ldb_end = 1; /* Signal the caller session ended. */
config.output = OUTPUT_STANDARD;
cliRefreshPrompt();
} else {
out = sdsCatColorizedLdbReply(out,r->str,r->len);
}
} else {
out = sdscatlen(out,r->str,r->len);
}
break;
case REDIS_REPLY_INTEGER:
out = sdscatprintf(out,"%lld",r->integer);
break;
case REDIS_REPLY_ARRAY:
for (i = 0; i < r->elements; i++) {
if (i > 0) out = sdscat(out,config.mb_delim);
tmp = cliFormatReplyRaw(r->element[i]);
out = sdscatlen(out,tmp,sdslen(tmp));
sdsfree(tmp);
}
break;
default:
fprintf(stderr,"Unknown reply type: %d\n", r->type);
exit(1);
}
return out;
}
static sds cliFormatReplyCSV(redisReply *r) {
unsigned int i;
sds out = sdsempty();
switch (r->type) {
case REDIS_REPLY_ERROR:
out = sdscat(out,"ERROR,");
out = sdscatrepr(out,r->str,strlen(r->str));
break;
case REDIS_REPLY_STATUS:
out = sdscatrepr(out,r->str,r->len);
break;
case REDIS_REPLY_INTEGER:
out = sdscatprintf(out,"%lld",r->integer);
break;
case REDIS_REPLY_STRING:
out = sdscatrepr(out,r->str,r->len);
break;
case REDIS_REPLY_NIL:
out = sdscat(out,"NIL");
break;
case REDIS_REPLY_ARRAY:
for (i = 0; i < r->elements; i++) {
sds tmp = cliFormatReplyCSV(r->element[i]);
out = sdscatlen(out,tmp,sdslen(tmp));
if (i != r->elements-1) out = sdscat(out,",");
sdsfree(tmp);
}
break;
default:
fprintf(stderr,"Unknown reply type: %d\n", r->type);
exit(1);
}
return out;
}
static int cliReadReply(int output_raw_strings) {
void *_reply;
redisReply *reply;
sds out = NULL;
int output = 1;
if (redisGetReply(context,&_reply) != REDIS_OK) {
if (config.shutdown) {
redisFree(context);
context = NULL;
return REDIS_OK;
}
if (config.interactive) {
/* Filter cases where we should reconnect */
if (context->err == REDIS_ERR_IO &&
(errno == ECONNRESET || errno == EPIPE))
return REDIS_ERR;
if (context->err == REDIS_ERR_EOF)
return REDIS_ERR;
}
cliPrintContextError();
exit(1);
return REDIS_ERR; /* avoid compiler warning */
}
reply = (redisReply*)_reply;
config.last_cmd_type = reply->type;
/* Check if we need to connect to a different node and reissue the
* request. */
if (config.cluster_mode && reply->type == REDIS_REPLY_ERROR &&
(!strncmp(reply->str,"MOVED",5) || !strcmp(reply->str,"ASK")))
{
char *p = reply->str, *s;
int slot;
output = 0;
/* Comments show the position of the pointer as:
*
* [S] for pointer 's'
* [P] for pointer 'p'
*/
s = strchr(p,' '); /* MOVED[S]3999 127.0.0.1:6381 */
p = strchr(s+1,' '); /* MOVED[S]3999[P]127.0.0.1:6381 */
*p = '\0';
slot = atoi(s+1);
s = strrchr(p+1,':'); /* MOVED 3999[P]127.0.0.1[S]6381 */
*s = '\0';
sdsfree(config.hostip);
config.hostip = sdsnew(p+1);
config.hostport = atoi(s+1);
if (config.interactive)
printf("-> Redirected to slot [%d] located at %s:%d\n",
slot, config.hostip, config.hostport);
config.cluster_reissue_command = 1;
cliRefreshPrompt();
}
if (output) {
if (output_raw_strings) {
out = cliFormatReplyRaw(reply);
} else {
if (config.output == OUTPUT_RAW) {
out = cliFormatReplyRaw(reply);
out = sdscat(out,"\n");
} else if (config.output == OUTPUT_STANDARD) {
out = cliFormatReplyTTY(reply,"");
} else if (config.output == OUTPUT_CSV) {
out = cliFormatReplyCSV(reply);
out = sdscat(out,"\n");
}
}
fwrite(out,sdslen(out),1,stdout);
sdsfree(out);
}
freeReplyObject(reply);
return REDIS_OK;
}
static int cliSendCommand(int argc, char **argv, long repeat) {
char *command = argv[0];
size_t *argvlen;
int j, output_raw;
if (!config.eval_ldb && /* In debugging mode, let's pass "help" to Redis. */
(!strcasecmp(command,"help") || !strcasecmp(command,"?"))) {
cliOutputHelp(--argc, ++argv);
return REDIS_OK;
}
if (context == NULL) return REDIS_ERR;
output_raw = 0;
if (!strcasecmp(command,"info") ||
(argc >= 2 && !strcasecmp(command,"debug") &&
!strcasecmp(argv[1],"htstats")) ||
(argc >= 2 && !strcasecmp(command,"memory") &&
(!strcasecmp(argv[1],"malloc-stats") ||
!strcasecmp(argv[1],"doctor"))) ||
(argc == 2 && !strcasecmp(command,"cluster") &&
(!strcasecmp(argv[1],"nodes") ||
!strcasecmp(argv[1],"info"))) ||
(argc == 2 && !strcasecmp(command,"client") &&
!strcasecmp(argv[1],"list")) ||
(argc == 3 && !strcasecmp(command,"latency") &&
!strcasecmp(argv[1],"graph")) ||
(argc == 2 && !strcasecmp(command,"latency") &&
!strcasecmp(argv[1],"doctor")))
{
output_raw = 1;
}
if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
if (!strcasecmp(command,"subscribe") ||
!strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
if (!strcasecmp(command,"sync") ||
!strcasecmp(command,"psync")) config.slave_mode = 1;
/* When the user manually calls SCRIPT DEBUG, setup the activation of
* debugging mode on the next eval if needed. */
if (argc == 3 && !strcasecmp(argv[0],"script") &&
!strcasecmp(argv[1],"debug"))
{
if (!strcasecmp(argv[2],"yes") || !strcasecmp(argv[2],"sync")) {
config.enable_ldb_on_eval = 1;
} else {
config.enable_ldb_on_eval = 0;
}
}
/* Actually activate LDB on EVAL if needed. */
if (!strcasecmp(command,"eval") && config.enable_ldb_on_eval) {
config.eval_ldb = 1;
config.output = OUTPUT_RAW;
}
/* Setup argument length */
argvlen = zmalloc(argc*sizeof(size_t));
for (j = 0; j < argc; j++)
argvlen[j] = sdslen(argv[j]);
while(repeat-- > 0) {
redisAppendCommandArgv(context,argc,(const char**)argv,argvlen);
while (config.monitor_mode) {
if (cliReadReply(output_raw) != REDIS_OK) exit(1);
fflush(stdout);
}
if (config.pubsub_mode) {
if (config.output != OUTPUT_RAW)
printf("Reading messages... (press Ctrl-C to quit)\n");
while (1) {
if (cliReadReply(output_raw) != REDIS_OK) exit(1);
}
}
if (config.slave_mode) {
printf("Entering slave output mode... (press Ctrl-C to quit)\n");
slaveMode();
config.slave_mode = 0;
zfree(argvlen);
return REDIS_ERR; /* Error = slaveMode lost connection to master */
}
if (cliReadReply(output_raw) != REDIS_OK) {
zfree(argvlen);
return REDIS_ERR;
} else {
/* Store database number when SELECT was successfully executed. */
if (!strcasecmp(command,"select") && argc == 2 && config.last_cmd_type != REDIS_REPLY_ERROR) {
config.dbnum = atoi(argv[1]);
cliRefreshPrompt();
} else if (!strcasecmp(command,"auth") && argc == 2) {
cliSelect();
}
}
if (config.interval) usleep(config.interval);
fflush(stdout); /* Make it grep friendly */
}
zfree(argvlen);
return REDIS_OK;
}
/* Send a command reconnecting the link if needed. */
static redisReply *reconnectingRedisCommand(redisContext *c, const char *fmt, ...) {
redisReply *reply = NULL;
int tries = 0;
va_list ap;
assert(!c->err);
while(reply == NULL) {
while (c->err & (REDIS_ERR_IO | REDIS_ERR_EOF)) {
printf("\r\x1b[0K"); /* Cursor to left edge + clear line. */
printf("Reconnecting... %d\r", ++tries);
fflush(stdout);
redisFree(c);
c = redisConnect(config.hostip,config.hostport);
usleep(1000000);
}
va_start(ap,fmt);
reply = redisvCommand(c,fmt,ap);
va_end(ap);
if (c->err && !(c->err & (REDIS_ERR_IO | REDIS_ERR_EOF))) {
fprintf(stderr, "Error: %s\n", c->errstr);
exit(1);
} else if (tries > 0) {
printf("\r\x1b[0K"); /* Cursor to left edge + clear line. */
}
}
context = c;
return reply;
}
/*------------------------------------------------------------------------------
* User interface
*--------------------------------------------------------------------------- */
static int parseOptions(int argc, char **argv) {
int i;
for (i = 1; i < argc; i++) {
int lastarg = i==argc-1;
if (!strcmp(argv[i],"-h") && !lastarg) {
sdsfree(config.hostip);
config.hostip = sdsnew(argv[++i]);
} else if (!strcmp(argv[i],"-h") && lastarg) {
usage();
} else if (!strcmp(argv[i],"--help")) {
usage();
} else if (!strcmp(argv[i],"-x")) {
config.stdinarg = 1;
} else if (!strcmp(argv[i],"-p") && !lastarg) {
config.hostport = atoi(argv[++i]);
} else if (!strcmp(argv[i],"-s") && !lastarg) {
config.hostsocket = argv[++i];
} else if (!strcmp(argv[i],"-r") && !lastarg) {
config.repeat = strtoll(argv[++i],NULL,10);
} else if (!strcmp(argv[i],"-i") && !lastarg) {
double seconds = atof(argv[++i]);
config.interval = seconds*1000000;
} else if (!strcmp(argv[i],"-n") && !lastarg) {
config.dbnum = atoi(argv[++i]);
} else if (!strcmp(argv[i],"-a") && !lastarg) {
fputs("Warning: Using a password with '-a' option on the command line interface may not be safe.\n", stderr);
config.auth = argv[++i];
} else if (!strcmp(argv[i],"-u") && !lastarg) {
parseRedisUri(argv[++i]);
} else if (!strcmp(argv[i],"--raw")) {
config.output = OUTPUT_RAW;
} else if (!strcmp(argv[i],"--no-raw")) {
config.output = OUTPUT_STANDARD;
} else if (!strcmp(argv[i],"--csv")) {
config.output = OUTPUT_CSV;
} else if (!strcmp(argv[i],"--latency")) {
config.latency_mode = 1;
} else if (!strcmp(argv[i],"--latency-dist")) {
config.latency_dist_mode = 1;
} else if (!strcmp(argv[i],"--mono")) {
spectrum_palette = spectrum_palette_mono;
spectrum_palette_size = spectrum_palette_mono_size;
} else if (!strcmp(argv[i],"--latency-history")) {
config.latency_mode = 1;
config.latency_history = 1;
} else if (!strcmp(argv[i],"--lru-test") && !lastarg) {
config.lru_test_mode = 1;
config.lru_test_sample_size = strtoll(argv[++i],NULL,10);
} else if (!strcmp(argv[i],"--slave")) {
config.slave_mode = 1;
} else if (!strcmp(argv[i],"--stat")) {
config.stat_mode = 1;
} else if (!strcmp(argv[i],"--scan")) {
config.scan_mode = 1;
} else if (!strcmp(argv[i],"--pattern") && !lastarg) {
config.pattern = argv[++i];
} else if (!strcmp(argv[i],"--intrinsic-latency") && !lastarg) {
config.intrinsic_latency_mode = 1;
config.intrinsic_latency_duration = atoi(argv[++i]);
} else if (!strcmp(argv[i],"--rdb") && !lastarg) {
config.getrdb_mode = 1;
config.rdb_filename = argv[++i];
} else if (!strcmp(argv[i],"--pipe")) {
config.pipe_mode = 1;
} else if (!strcmp(argv[i],"--pipe-timeout") && !lastarg) {
config.pipe_timeout = atoi(argv[++i]);
} else if (!strcmp(argv[i],"--bigkeys")) {
config.bigkeys = 1;
} else if (!strcmp(argv[i],"--hotkeys")) {
config.hotkeys = 1;
} else if (!strcmp(argv[i],"--eval") && !lastarg) {
config.eval = argv[++i];
} else if (!strcmp(argv[i],"--ldb")) {
config.eval_ldb = 1;
config.output = OUTPUT_RAW;
} else if (!strcmp(argv[i],"--ldb-sync-mode")) {
config.eval_ldb = 1;
config.eval_ldb_sync = 1;
config.output = OUTPUT_RAW;
} else if (!strcmp(argv[i],"-c")) {
config.cluster_mode = 1;
} else if (!strcmp(argv[i],"-d") && !lastarg) {
sdsfree(config.mb_delim);
config.mb_delim = sdsnew(argv[++i]);
} else if (!strcmp(argv[i],"-v") || !strcmp(argv[i], "--version")) {
sds version = cliVersion();
printf("redis-cli %s\n", version);
sdsfree(version);
exit(0);
} else {
if (argv[i][0] == '-') {
fprintf(stderr,
"Unrecognized option or bad number of args for: '%s'\n",
argv[i]);
exit(1);
} else {
/* Likely the command name, stop here. */
break;
}
}
}
/* --ldb requires --eval. */
if (config.eval_ldb && config.eval == NULL) {
fprintf(stderr,"Options --ldb and --ldb-sync-mode require --eval.\n");
fprintf(stderr,"Try %s --help for more information.\n", argv[0]);
exit(1);
}
return i;
}
static sds readArgFromStdin(void) {
char buf[1024];
sds arg = sdsempty();
while(1) {
int nread = read(fileno(stdin),buf,1024);
if (nread == 0) break;
else if (nread == -1) {
perror("Reading from standard input");
exit(1);
}
arg = sdscatlen(arg,buf,nread);
}
return arg;
}
static void usage(void) {
sds version = cliVersion();
fprintf(stderr,
"redis-cli %s\n"
"\n"
"Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
" -h <hostname> Server hostname (default: 127.0.0.1).\n"
" -p <port> Server port (default: 6379).\n"
" -s <socket> Server socket (overrides hostname and port).\n"
" -a <password> Password to use when connecting to the server.\n"
" -u <uri> Server URI.\n"
" -r <repeat> Execute specified command N times.\n"
" -i <interval> When -r is used, waits <interval> seconds per command.\n"
" It is possible to specify sub-second times like -i 0.1.\n"
" -n <db> Database number.\n"
" -x Read last argument from STDIN.\n"
" -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n).\n"
" -c Enable cluster mode (follow -ASK and -MOVED redirections).\n"
" --raw Use raw formatting for replies (default when STDOUT is\n"
" not a tty).\n"
" --no-raw Force formatted output even when STDOUT is not a tty.\n"
" --csv Output in CSV format.\n"
" --stat Print rolling stats about server: mem, clients, ...\n"
" --latency Enter a special mode continuously sampling latency.\n"
" If you use this mode in an interactive session it runs\n"
" forever displaying real-time stats. Otherwise if --raw or\n"
" --csv is specified, or if you redirect the output to a non\n"
" TTY, it samples the latency for 1 second (you can use\n"
" -i to change the interval), then produces a single output\n"
" and exits.\n"
" --latency-history Like --latency but tracking latency changes over time.\n"
" Default time interval is 15 sec. Change it using -i.\n"
" --latency-dist Shows latency as a spectrum, requires xterm 256 colors.\n"
" Default time interval is 1 sec. Change it using -i.\n"
" --lru-test <keys> Simulate a cache workload with an 80-20 distribution.\n"
" --slave Simulate a slave showing commands received from the master.\n"
" --rdb <filename> Transfer an RDB dump from remote server to local file.\n"
" --pipe Transfer raw Redis protocol from stdin to server.\n"
" --pipe-timeout <n> In --pipe mode, abort with error if after sending all data.\n"
" no reply is received within <n> seconds.\n"
" Default timeout: %d. Use 0 to wait forever.\n"
" --bigkeys Sample Redis keys looking for big keys.\n"
" --hotkeys Sample Redis keys looking for hot keys.\n"
" only works when maxmemory-policy is *lfu.\n"
" --scan List all keys using the SCAN command.\n"
" --pattern <pat> Useful with --scan to specify a SCAN pattern.\n"
" --intrinsic-latency <sec> Run a test to measure intrinsic system latency.\n"
" The test will run for the specified amount of seconds.\n"
" --eval <file> Send an EVAL command using the Lua script at <file>.\n"
" --ldb Used with --eval enable the Redis Lua debugger.\n"
" --ldb-sync-mode Like --ldb but uses the synchronous Lua debugger, in\n"
" this mode the server is blocked and script changes are\n"
" are not rolled back from the server memory.\n"
" --help Output this help and exit.\n"
" --version Output version and exit.\n"
"\n"
"Examples:\n"
" cat /etc/passwd | redis-cli -x set mypasswd\n"
" redis-cli get mypasswd\n"
" redis-cli -r 100 lpush mylist x\n"
" redis-cli -r 100 -i 1 info | grep used_memory_human:\n"
" redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3\n"
" redis-cli --scan --pattern '*:12345*'\n"
"\n"
" (Note: when using --eval the comma separates KEYS[] from ARGV[] items)\n"
"\n"
"When no command is given, redis-cli starts in interactive mode.\n"
"Type \"help\" in interactive mode for information on available commands\n"
"and settings.\n"
"\n",
version, REDIS_CLI_DEFAULT_PIPE_TIMEOUT);
sdsfree(version);
exit(1);
}
/* Turn the plain C strings into Sds strings */
static char **convertToSds(int count, char** args) {
int j;
char **sds = zmalloc(sizeof(char*)*count);
for(j = 0; j < count; j++)
sds[j] = sdsnew(args[j]);
return sds;
}
static int issueCommandRepeat(int argc, char **argv, long repeat) {
while (1) {
config.cluster_reissue_command = 0;
if (cliSendCommand(argc,argv,repeat) != REDIS_OK) {
cliConnect(1);
/* If we still cannot send the command print error.
* We'll try to reconnect the next time. */
if (cliSendCommand(argc,argv,repeat) != REDIS_OK) {
cliPrintContextError();
return REDIS_ERR;
}
}
/* Issue the command again if we got redirected in cluster mode */
if (config.cluster_mode && config.cluster_reissue_command) {
cliConnect(1);
} else {
break;
}
}
return REDIS_OK;
}
static int issueCommand(int argc, char **argv) {
return issueCommandRepeat(argc, argv, config.repeat);
}
/* Split the user provided command into multiple SDS arguments.
* This function normally uses sdssplitargs() from sds.c which is able
* to understand "quoted strings", escapes and so forth. However when
* we are in Lua debugging mode and the "eval" command is used, we want
* the remaining Lua script (after "e " or "eval ") to be passed verbatim
* as a single big argument. */
static sds *cliSplitArgs(char *line, int *argc) {
if (config.eval_ldb && (strstr(line,"eval ") == line ||
strstr(line,"e ") == line))
{
sds *argv = sds_malloc(sizeof(sds)*2);
*argc = 2;
int len = strlen(line);
int elen = line[1] == ' ' ? 2 : 5; /* "e " or "eval "? */
argv[0] = sdsnewlen(line,elen-1);
argv[1] = sdsnewlen(line+elen,len-elen);
return argv;
} else {
return sdssplitargs(line,argc);
}
}
/* Set the CLI preferences. This function is invoked when an interactive
* ":command" is called, or when reading ~/.redisclirc file, in order to
* set user preferences. */
void cliSetPreferences(char **argv, int argc, int interactive) {
if (!strcasecmp(argv[0],":set") && argc >= 2) {
if (!strcasecmp(argv[1],"hints")) pref.hints = 1;
else if (!strcasecmp(argv[1],"nohints")) pref.hints = 0;
else {
printf("%sunknown redis-cli preference '%s'\n",
interactive ? "" : ".redisclirc: ",
argv[1]);
}
} else {
printf("%sunknown redis-cli internal command '%s'\n",
interactive ? "" : ".redisclirc: ",
argv[0]);
}
}
/* Load the ~/.redisclirc file if any. */
void cliLoadPreferences(void) {
sds rcfile = getDotfilePath(REDIS_CLI_RCFILE_ENV,REDIS_CLI_RCFILE_DEFAULT);
if (rcfile == NULL) return;
FILE *fp = fopen(rcfile,"r");
char buf[1024];
if (fp) {
while(fgets(buf,sizeof(buf),fp) != NULL) {
sds *argv;
int argc;
argv = sdssplitargs(buf,&argc);
if (argc > 0) cliSetPreferences(argv,argc,0);
sdsfreesplitres(argv,argc);
}
fclose(fp);
}
sdsfree(rcfile);
}
static void repl(void) {
sds historyfile = NULL;
int history = 0;
char *line;
int argc;
sds *argv;
/* Initialize the help and, if possible, use the COMMAND command in order
* to retrieve missing entries. */
cliInitHelp();
cliIntegrateHelp();
config.interactive = 1;
linenoiseSetMultiLine(1);
linenoiseSetCompletionCallback(completionCallback);
linenoiseSetHintsCallback(hintsCallback);
linenoiseSetFreeHintsCallback(freeHintsCallback);
/* Only use history and load the rc file when stdin is a tty. */
if (isatty(fileno(stdin))) {
historyfile = getDotfilePath(REDIS_CLI_HISTFILE_ENV,REDIS_CLI_HISTFILE_DEFAULT);
//keep in-memory history always regardless if history file can be determined
history = 1;
if (historyfile != NULL) {
linenoiseHistoryLoad(historyfile);
}
cliLoadPreferences();
}
cliRefreshPrompt();
while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) {
if (line[0] != '\0') {
long repeat = 1;
int skipargs = 0;
char *endptr = NULL;
argv = cliSplitArgs(line,&argc);
/* check if we have a repeat command option and
* need to skip the first arg */
if (argv && argc > 0) {
errno = 0;
repeat = strtol(argv[0], &endptr, 10);
if (argc > 1 && *endptr == '\0') {
if (errno == ERANGE || errno == EINVAL || repeat <= 0) {
fputs("Invalid redis-cli repeat command option value.\n", stdout);
sdsfreesplitres(argv, argc);
linenoiseFree(line);
continue;
}
skipargs = 1;
} else {
repeat = 1;
}
}
/* Won't save auth command in history file */
if (!(argv && argc > 0 && !strcasecmp(argv[0+skipargs], "auth"))) {
if (history) linenoiseHistoryAdd(line);
if (historyfile) linenoiseHistorySave(historyfile);
}
if (argv == NULL) {
printf("Invalid argument(s)\n");
linenoiseFree(line);
continue;
} else if (argc > 0) {
if (strcasecmp(argv[0],"quit") == 0 ||
strcasecmp(argv[0],"exit") == 0)
{
exit(0);
} else if (argv[0][0] == ':') {
cliSetPreferences(argv,argc,1);
sdsfreesplitres(argv,argc);
linenoiseFree(line);
continue;
} else if (strcasecmp(argv[0],"restart") == 0) {
if (config.eval) {
config.eval_ldb = 1;
config.output = OUTPUT_RAW;
return; /* Return to evalMode to restart the session. */
} else {
printf("Use 'restart' only in Lua debugging mode.");
}
} else if (argc == 3 && !strcasecmp(argv[0],"connect")) {
sdsfree(config.hostip);
config.hostip = sdsnew(argv[1]);
config.hostport = atoi(argv[2]);
cliRefreshPrompt();
cliConnect(1);
} else if (argc == 1 && !strcasecmp(argv[0],"clear")) {
linenoiseClearScreen();
} else {
long long start_time = mstime(), elapsed;
issueCommandRepeat(argc-skipargs, argv+skipargs, repeat);
/* If our debugging session ended, show the EVAL final
* reply. */
if (config.eval_ldb_end) {
config.eval_ldb_end = 0;
cliReadReply(0);
printf("\n(Lua debugging session ended%s)\n\n",
config.eval_ldb_sync ? "" :
" -- dataset changes rolled back");
}
elapsed = mstime()-start_time;
if (elapsed >= 500 &&
config.output == OUTPUT_STANDARD)
{
printf("(%.2fs)\n",(double)elapsed/1000);
}
}
}
/* Free the argument vector */
sdsfreesplitres(argv,argc);
}
/* linenoise() returns malloc-ed lines like readline() */
linenoiseFree(line);
}
exit(0);
}
static int noninteractive(int argc, char **argv) {
int retval = 0;
if (config.stdinarg) {
argv = zrealloc(argv, (argc+1)*sizeof(char*));
argv[argc] = readArgFromStdin();
retval = issueCommand(argc+1, argv);
} else {
retval = issueCommand(argc, argv);
}
return retval;
}
/*------------------------------------------------------------------------------
* Eval mode
*--------------------------------------------------------------------------- */
static int evalMode(int argc, char **argv) {
sds script = NULL;
FILE *fp;
char buf[1024];
size_t nread;
char **argv2;
int j, got_comma, keys;
int retval = REDIS_OK;
while(1) {
if (config.eval_ldb) {
printf(
"Lua debugging session started, please use:\n"
"quit -- End the session.\n"
"restart -- Restart the script in debug mode again.\n"
"help -- Show Lua script debugging commands.\n\n"
);
}
sdsfree(script);
script = sdsempty();
got_comma = 0;
keys = 0;
/* Load the script from the file, as an sds string. */
fp = fopen(config.eval,"r");
if (!fp) {
fprintf(stderr,
"Can't open file '%s': %s\n", config.eval, strerror(errno));
exit(1);
}
while((nread = fread(buf,1,sizeof(buf),fp)) != 0) {
script = sdscatlen(script,buf,nread);
}
fclose(fp);
/* If we are debugging a script, enable the Lua debugger. */
if (config.eval_ldb) {
redisReply *reply = redisCommand(context,
config.eval_ldb_sync ?
"SCRIPT DEBUG sync": "SCRIPT DEBUG yes");
if (reply) freeReplyObject(reply);
}
/* Create our argument vector */
argv2 = zmalloc(sizeof(sds)*(argc+3));
argv2[0] = sdsnew("EVAL");
argv2[1] = script;
for (j = 0; j < argc; j++) {
if (!got_comma && argv[j][0] == ',' && argv[j][1] == 0) {
got_comma = 1;
continue;
}
argv2[j+3-got_comma] = sdsnew(argv[j]);
if (!got_comma) keys++;
}
argv2[2] = sdscatprintf(sdsempty(),"%d",keys);
/* Call it */
int eval_ldb = config.eval_ldb; /* Save it, may be reverteed. */
retval = issueCommand(argc+3-got_comma, argv2);
if (eval_ldb) {
if (!config.eval_ldb) {
/* If the debugging session ended immediately, there was an
* error compiling the script. Show it and don't enter
* the REPL at all. */
printf("Eval debugging session can't start:\n");
cliReadReply(0);
break; /* Return to the caller. */
} else {
strncpy(config.prompt,"lua debugger> ",sizeof(config.prompt));
repl();
/* Restart the session if repl() returned. */
cliConnect(1);
printf("\n");
}
} else {
break; /* Return to the caller. */
}
}
return retval;
}
/*------------------------------------------------------------------------------
* Latency and latency history modes
*--------------------------------------------------------------------------- */
static void latencyModePrint(long long min, long long max, double avg, long long count) {
if (config.output == OUTPUT_STANDARD) {
printf("min: %lld, max: %lld, avg: %.2f (%lld samples)",
min, max, avg, count);
fflush(stdout);
} else if (config.output == OUTPUT_CSV) {
printf("%lld,%lld,%.2f,%lld\n", min, max, avg, count);
} else if (config.output == OUTPUT_RAW) {
printf("%lld %lld %.2f %lld\n", min, max, avg, count);
}
}
#define LATENCY_SAMPLE_RATE 10 /* milliseconds. */
#define LATENCY_HISTORY_DEFAULT_INTERVAL 15000 /* milliseconds. */
static void latencyMode(void) {
redisReply *reply;
long long start, latency, min = 0, max = 0, tot = 0, count = 0;
long long history_interval =
config.interval ? config.interval/1000 :
LATENCY_HISTORY_DEFAULT_INTERVAL;
double avg;
long long history_start = mstime();
/* Set a default for the interval in case of --latency option
* with --raw, --csv or when it is redirected to non tty. */
if (config.interval == 0) {
config.interval = 1000;
} else {
config.interval /= 1000; /* We need to convert to milliseconds. */
}
if (!context) exit(1);
while(1) {
start = mstime();
reply = reconnectingRedisCommand(context,"PING");
if (reply == NULL) {
fprintf(stderr,"\nI/O error\n");
exit(1);
}
latency = mstime()-start;
freeReplyObject(reply);
count++;
if (count == 1) {
min = max = tot = latency;
avg = (double) latency;
} else {
if (latency < min) min = latency;
if (latency > max) max = latency;
tot += latency;
avg = (double) tot/count;
}
if (config.output == OUTPUT_STANDARD) {
printf("\x1b[0G\x1b[2K"); /* Clear the line. */
latencyModePrint(min,max,avg,count);
} else {
if (config.latency_history) {
latencyModePrint(min,max,avg,count);
} else if (mstime()-history_start > config.interval) {
latencyModePrint(min,max,avg,count);
exit(0);
}
}
if (config.latency_history && mstime()-history_start > history_interval)
{
printf(" -- %.2f seconds range\n", (float)(mstime()-history_start)/1000);
history_start = mstime();
min = max = tot = count = 0;
}
usleep(LATENCY_SAMPLE_RATE * 1000);
}
}
/*------------------------------------------------------------------------------
* Latency distribution mode -- requires 256 colors xterm
*--------------------------------------------------------------------------- */
#define LATENCY_DIST_DEFAULT_INTERVAL 1000 /* milliseconds. */
/* Structure to store samples distribution. */
struct distsamples {
long long max; /* Max latency to fit into this interval (usec). */
long long count; /* Number of samples in this interval. */
int character; /* Associated character in visualization. */
};
/* Helper function for latencyDistMode(). Performs the spectrum visualization
* of the collected samples targeting an xterm 256 terminal.
*
* Takes an array of distsamples structures, ordered from smaller to bigger
* 'max' value. Last sample max must be 0, to mean that it olds all the
* samples greater than the previous one, and is also the stop sentinel.
*
* "tot' is the total number of samples in the different buckets, so it
* is the SUM(samples[i].conut) for i to 0 up to the max sample.
*
* As a side effect the function sets all the buckets count to 0. */
void showLatencyDistSamples(struct distsamples *samples, long long tot) {
int j;
/* We convert samples into a index inside the palette
* proportional to the percentage a given bucket represents.
* This way intensity of the different parts of the spectrum
* don't change relative to the number of requests, which avoids to
* pollute the visualization with non-latency related info. */
printf("\033[38;5;0m"); /* Set foreground color to black. */
for (j = 0; ; j++) {
int coloridx =
ceil((float) samples[j].count / tot * (spectrum_palette_size-1));
int color = spectrum_palette[coloridx];
printf("\033[48;5;%dm%c", (int)color, samples[j].character);
samples[j].count = 0;
if (samples[j].max == 0) break; /* Last sample. */
}
printf("\033[0m\n");
fflush(stdout);
}
/* Show the legend: different buckets values and colors meaning, so
* that the spectrum is more easily readable. */
void showLatencyDistLegend(void) {
int j;
printf("---------------------------------------------\n");
printf(". - * # .01 .125 .25 .5 milliseconds\n");
printf("1,2,3,...,9 from 1 to 9 milliseconds\n");
printf("A,B,C,D,E 10,20,30,40,50 milliseconds\n");
printf("F,G,H,I,J .1,.2,.3,.4,.5 seconds\n");
printf("K,L,M,N,O,P,Q,? 1,2,4,8,16,30,60,>60 seconds\n");
printf("From 0 to 100%%: ");
for (j = 0; j < spectrum_palette_size; j++) {
printf("\033[48;5;%dm ", spectrum_palette[j]);
}
printf("\033[0m\n");
printf("---------------------------------------------\n");
}
static void latencyDistMode(void) {
redisReply *reply;
long long start, latency, count = 0;
long long history_interval =
config.interval ? config.interval/1000 :
LATENCY_DIST_DEFAULT_INTERVAL;
long long history_start = ustime();
int j, outputs = 0;
struct distsamples samples[] = {
/* We use a mostly logarithmic scale, with certain linear intervals
* which are more interesting than others, like 1-10 milliseconds
* range. */
{10,0,'.'}, /* 0.01 ms */
{125,0,'-'}, /* 0.125 ms */
{250,0,'*'}, /* 0.25 ms */
{500,0,'#'}, /* 0.5 ms */
{1000,0,'1'}, /* 1 ms */
{2000,0,'2'}, /* 2 ms */
{3000,0,'3'}, /* 3 ms */
{4000,0,'4'}, /* 4 ms */
{5000,0,'5'}, /* 5 ms */
{6000,0,'6'}, /* 6 ms */
{7000,0,'7'}, /* 7 ms */
{8000,0,'8'}, /* 8 ms */
{9000,0,'9'}, /* 9 ms */
{10000,0,'A'}, /* 10 ms */
{20000,0,'B'}, /* 20 ms */
{30000,0,'C'}, /* 30 ms */
{40000,0,'D'}, /* 40 ms */
{50000,0,'E'}, /* 50 ms */
{100000,0,'F'}, /* 0.1 s */
{200000,0,'G'}, /* 0.2 s */
{300000,0,'H'}, /* 0.3 s */
{400000,0,'I'}, /* 0.4 s */
{500000,0,'J'}, /* 0.5 s */
{1000000,0,'K'}, /* 1 s */
{2000000,0,'L'}, /* 2 s */
{4000000,0,'M'}, /* 4 s */
{8000000,0,'N'}, /* 8 s */
{16000000,0,'O'}, /* 16 s */
{30000000,0,'P'}, /* 30 s */
{60000000,0,'Q'}, /* 1 minute */
{0,0,'?'}, /* > 1 minute */
};
if (!context) exit(1);
while(1) {
start = ustime();
reply = reconnectingRedisCommand(context,"PING");
if (reply == NULL) {
fprintf(stderr,"\nI/O error\n");
exit(1);
}
latency = ustime()-start;
freeReplyObject(reply);
count++;
/* Populate the relevant bucket. */
for (j = 0; ; j++) {
if (samples[j].max == 0 || latency <= samples[j].max) {
samples[j].count++;
break;
}
}
/* From time to time show the spectrum. */
if (count && (ustime()-history_start)/1000 > history_interval) {
if ((outputs++ % 20) == 0)
showLatencyDistLegend();
showLatencyDistSamples(samples,count);
history_start = ustime();
count = 0;
}
usleep(LATENCY_SAMPLE_RATE * 1000);
}
}
/*------------------------------------------------------------------------------
* Slave mode
*--------------------------------------------------------------------------- */
/* Sends SYNC and reads the number of bytes in the payload. Used both by
* slaveMode() and getRDB(). */
unsigned long long sendSync(int fd) {
/* To start we need to send the SYNC command and return the payload.
* The hiredis client lib does not understand this part of the protocol
* and we don't want to mess with its buffers, so everything is performed
* using direct low-level I/O. */
char buf[4096], *p;
ssize_t nread;
/* Send the SYNC command. */
if (write(fd,"SYNC\r\n",6) != 6) {
fprintf(stderr,"Error writing to master\n");
exit(1);
}
/* Read $<payload>\r\n, making sure to read just up to "\n" */
p = buf;
while(1) {
nread = read(fd,p,1);
if (nread <= 0) {
fprintf(stderr,"Error reading bulk length while SYNCing\n");
exit(1);
}
if (*p == '\n' && p != buf) break;
if (*p != '\n') p++;
}
*p = '\0';
if (buf[0] == '-') {
printf("SYNC with master failed: %s\n", buf);
exit(1);
}
return strtoull(buf+1,NULL,10);
}
static void slaveMode(void) {
int fd = context->fd;
unsigned long long payload = sendSync(fd);
char buf[1024];
int original_output = config.output;
fprintf(stderr,"SYNC with master, discarding %llu "
"bytes of bulk transfer...\n", payload);
/* Discard the payload. */
while(payload) {
ssize_t nread;
nread = read(fd,buf,(payload > sizeof(buf)) ? sizeof(buf) : payload);
if (nread <= 0) {
fprintf(stderr,"Error reading RDB payload while SYNCing\n");
exit(1);
}
payload -= nread;
}
fprintf(stderr,"SYNC done. Logging commands from master.\n");
/* Now we can use hiredis to read the incoming protocol. */
config.output = OUTPUT_CSV;
while (cliReadReply(0) == REDIS_OK);
config.output = original_output;
}
/*------------------------------------------------------------------------------
* RDB transfer mode
*--------------------------------------------------------------------------- */
/* This function implements --rdb, so it uses the replication protocol in order
* to fetch the RDB file from a remote server. */
static void getRDB(void) {
int s = context->fd;
int fd;
unsigned long long payload = sendSync(s);
char buf[4096];
fprintf(stderr,"SYNC sent to master, writing %llu bytes to '%s'\n",
payload, config.rdb_filename);
/* Write to file. */
if (!strcmp(config.rdb_filename,"-")) {
fd = STDOUT_FILENO;
} else {
fd = open(config.rdb_filename, O_CREAT|O_WRONLY, 0644);
if (fd == -1) {
fprintf(stderr, "Error opening '%s': %s\n", config.rdb_filename,
strerror(errno));
exit(1);
}
}
while(payload) {
ssize_t nread, nwritten;
nread = read(s,buf,(payload > sizeof(buf)) ? sizeof(buf) : payload);
if (nread <= 0) {
fprintf(stderr,"I/O Error reading RDB payload from socket\n");
exit(1);
}
nwritten = write(fd, buf, nread);
if (nwritten != nread) {
fprintf(stderr,"Error writing data to file: %s\n",
strerror(errno));
exit(1);
}
payload -= nread;
}
close(s); /* Close the file descriptor ASAP as fsync() may take time. */
fsync(fd);
fprintf(stderr,"Transfer finished with success.\n");
exit(0);
}
/*------------------------------------------------------------------------------
* Bulk import (pipe) mode
*--------------------------------------------------------------------------- */
#define PIPEMODE_WRITE_LOOP_MAX_BYTES (128*1024)
static void pipeMode(void) {
int fd = context->fd;
long long errors = 0, replies = 0, obuf_len = 0, obuf_pos = 0;
char ibuf[1024*16], obuf[1024*16]; /* Input and output buffers */
char aneterr[ANET_ERR_LEN];
redisReader *reader = redisReaderCreate();
redisReply *reply;
int eof = 0; /* True once we consumed all the standard input. */
int done = 0;
char magic[20]; /* Special reply we recognize. */
time_t last_read_time = time(NULL);
srand(time(NULL));
/* Use non blocking I/O. */
if (anetNonBlock(aneterr,fd) == ANET_ERR) {
fprintf(stderr, "Can't set the socket in non blocking mode: %s\n",
aneterr);
exit(1);
}
/* Transfer raw protocol and read replies from the server at the same
* time. */
while(!done) {
int mask = AE_READABLE;
if (!eof || obuf_len != 0) mask |= AE_WRITABLE;
mask = aeWait(fd,mask,1000);
/* Handle the readable state: we can read replies from the server. */
if (mask & AE_READABLE) {
ssize_t nread;
/* Read from socket and feed the hiredis reader. */
do {
nread = read(fd,ibuf,sizeof(ibuf));
if (nread == -1 && errno != EAGAIN && errno != EINTR) {
fprintf(stderr, "Error reading from the server: %s\n",
strerror(errno));
exit(1);
}
if (nread > 0) {
redisReaderFeed(reader,ibuf,nread);
last_read_time = time(NULL);
}
} while(nread > 0);
/* Consume replies. */
do {
if (redisReaderGetReply(reader,(void**)&reply) == REDIS_ERR) {
fprintf(stderr, "Error reading replies from server\n");
exit(1);
}
if (reply) {
if (reply->type == REDIS_REPLY_ERROR) {
fprintf(stderr,"%s\n", reply->str);
errors++;
} else if (eof && reply->type == REDIS_REPLY_STRING &&
reply->len == 20) {
/* Check if this is the reply to our final ECHO
* command. If so everything was received
* from the server. */
if (memcmp(reply->str,magic,20) == 0) {
printf("Last reply received from server.\n");
done = 1;
replies--;
}
}
replies++;
freeReplyObject(reply);
}
} while(reply);
}
/* Handle the writable state: we can send protocol to the server. */
if (mask & AE_WRITABLE) {
ssize_t loop_nwritten = 0;
while(1) {
/* Transfer current buffer to server. */
if (obuf_len != 0) {
ssize_t nwritten = write(fd,obuf+obuf_pos,obuf_len);
if (nwritten == -1) {
if (errno != EAGAIN && errno != EINTR) {
fprintf(stderr, "Error writing to the server: %s\n",
strerror(errno));
exit(1);
} else {
nwritten = 0;
}
}
obuf_len -= nwritten;
obuf_pos += nwritten;
loop_nwritten += nwritten;
if (obuf_len != 0) break; /* Can't accept more data. */
}
/* If buffer is empty, load from stdin. */
if (obuf_len == 0 && !eof) {
ssize_t nread = read(STDIN_FILENO,obuf,sizeof(obuf));
if (nread == 0) {
/* The ECHO sequence starts with a "\r\n" so that if there
* is garbage in the protocol we read from stdin, the ECHO
* will likely still be properly formatted.
* CRLF is ignored by Redis, so it has no effects. */
char echo[] =
"\r\n*2\r\n$4\r\nECHO\r\n$20\r\n01234567890123456789\r\n";
int j;
eof = 1;
/* Everything transferred, so we queue a special
* ECHO command that we can match in the replies
* to make sure everything was read from the server. */
for (j = 0; j < 20; j++)
magic[j] = rand() & 0xff;
memcpy(echo+21,magic,20);
memcpy(obuf,echo,sizeof(echo)-1);
obuf_len = sizeof(echo)-1;
obuf_pos = 0;
printf("All data transferred. Waiting for the last reply...\n");
} else if (nread == -1) {
fprintf(stderr, "Error reading from stdin: %s\n",
strerror(errno));
exit(1);
} else {
obuf_len = nread;
obuf_pos = 0;
}
}
if ((obuf_len == 0 && eof) ||
loop_nwritten > PIPEMODE_WRITE_LOOP_MAX_BYTES) break;
}
}
/* Handle timeout, that is, we reached EOF, and we are not getting
* replies from the server for a few seconds, nor the final ECHO is
* received. */
if (eof && config.pipe_timeout > 0 &&
time(NULL)-last_read_time > config.pipe_timeout)
{
fprintf(stderr,"No replies for %d seconds: exiting.\n",
config.pipe_timeout);
errors++;
break;
}
}
redisReaderFree(reader);
printf("errors: %lld, replies: %lld\n", errors, replies);
if (errors)
exit(1);
else
exit(0);
}
/*------------------------------------------------------------------------------
* Find big keys
*--------------------------------------------------------------------------- */
#define TYPE_STRING 0
#define TYPE_LIST 1
#define TYPE_SET 2
#define TYPE_HASH 3
#define TYPE_ZSET 4
#define TYPE_STREAM 5
#define TYPE_NONE 6
#define TYPE_COUNT 7
static redisReply *sendScan(unsigned long long *it) {
redisReply *reply = redisCommand(context, "SCAN %llu", *it);
/* Handle any error conditions */
if(reply == NULL) {
fprintf(stderr, "\nI/O error\n");
exit(1);
} else if(reply->type == REDIS_REPLY_ERROR) {
fprintf(stderr, "SCAN error: %s\n", reply->str);
exit(1);
} else if(reply->type != REDIS_REPLY_ARRAY) {
fprintf(stderr, "Non ARRAY response from SCAN!\n");
exit(1);
} else if(reply->elements != 2) {
fprintf(stderr, "Invalid element count from SCAN!\n");
exit(1);
}
/* Validate our types are correct */
assert(reply->element[0]->type == REDIS_REPLY_STRING);
assert(reply->element[1]->type == REDIS_REPLY_ARRAY);
/* Update iterator */
*it = strtoull(reply->element[0]->str, NULL, 10);
return reply;
}
static int getDbSize(void) {
redisReply *reply;
int size;
reply = redisCommand(context, "DBSIZE");
if(reply == NULL || reply->type != REDIS_REPLY_INTEGER) {
fprintf(stderr, "Couldn't determine DBSIZE!\n");
exit(1);
}
/* Grab the number of keys and free our reply */
size = reply->integer;
freeReplyObject(reply);
return size;
}
static int toIntType(char *key, char *type) {
if(!strcmp(type, "string")) {
return TYPE_STRING;
} else if(!strcmp(type, "list")) {
return TYPE_LIST;
} else if(!strcmp(type, "set")) {
return TYPE_SET;
} else if(!strcmp(type, "hash")) {
return TYPE_HASH;
} else if(!strcmp(type, "zset")) {
return TYPE_ZSET;
} else if(!strcmp(type, "none")) {
return TYPE_NONE;
} else {
fprintf(stderr, "Unknown type '%s' for key '%s'\n", type, key);
exit(1);
}
}
static void getKeyTypes(redisReply *keys, int *types) {
redisReply *reply;
unsigned int i;
/* Pipeline TYPE commands */
for(i=0;i<keys->elements;i++) {
redisAppendCommand(context, "TYPE %s", keys->element[i]->str);
}
/* Retrieve types */
for(i=0;i<keys->elements;i++) {
if(redisGetReply(context, (void**)&reply)!=REDIS_OK) {
fprintf(stderr, "Error getting type for key '%s' (%d: %s)\n",
keys->element[i]->str, context->err, context->errstr);
exit(1);
} else if(reply->type != REDIS_REPLY_STATUS) {
if(reply->type == REDIS_REPLY_ERROR) {
fprintf(stderr, "TYPE returned an error: %s\n", reply->str);
} else {
fprintf(stderr,
"Invalid reply type (%d) for TYPE on key '%s'!\n",
reply->type, keys->element[i]->str);
}
exit(1);
}
types[i] = toIntType(keys->element[i]->str, reply->str);
freeReplyObject(reply);
}
}
static void getKeySizes(redisReply *keys, int *types,
unsigned long long *sizes)
{
redisReply *reply;
char *sizecmds[] = {"STRLEN","LLEN","SCARD","HLEN","ZCARD"};
unsigned int i;
/* Pipeline size commands */
for(i=0;i<keys->elements;i++) {
/* Skip keys that were deleted */
if(types[i]==TYPE_NONE)
continue;
redisAppendCommand(context, "%s %s", sizecmds[types[i]],
keys->element[i]->str);
}
/* Retreive sizes */
for(i=0;i<keys->elements;i++) {
/* Skip keys that dissapeared between SCAN and TYPE */
if(types[i] == TYPE_NONE) {
sizes[i] = 0;
continue;
}
/* Retreive size */
if(redisGetReply(context, (void**)&reply)!=REDIS_OK) {
fprintf(stderr, "Error getting size for key '%s' (%d: %s)\n",
keys->element[i]->str, context->err, context->errstr);
exit(1);
} else if(reply->type != REDIS_REPLY_INTEGER) {
/* Theoretically the key could have been removed and
* added as a different type between TYPE and SIZE */
fprintf(stderr,
"Warning: %s on '%s' failed (may have changed type)\n",
sizecmds[types[i]], keys->element[i]->str);
sizes[i] = 0;
} else {
sizes[i] = reply->integer;
}
freeReplyObject(reply);
}
}
static void findBigKeys(void) {
unsigned long long biggest[TYPE_COUNT] = {0}, counts[TYPE_COUNT] = {0}, totalsize[TYPE_COUNT] = {0};
unsigned long long sampled = 0, total_keys, totlen=0, *sizes=NULL, it=0;
sds maxkeys[TYPE_COUNT] = {0};
char *typename[] = {"string","list","set","hash","zset","stream","none"};
char *typeunit[] = {"bytes","items","members","fields","members","entries",""};
redisReply *reply, *keys;
unsigned int arrsize=0, i;
int type, *types=NULL;
double pct;
/* Total keys pre scanning */
total_keys = getDbSize();
/* Status message */
printf("\n# Scanning the entire keyspace to find biggest keys as well as\n");
printf("# average sizes per key type. You can use -i 0.1 to sleep 0.1 sec\n");
printf("# per 100 SCAN commands (not usually needed).\n\n");
/* New up sds strings to keep track of overall biggest per type */
for(i=0;i<TYPE_NONE; i++) {
maxkeys[i] = sdsempty();
if(!maxkeys[i]) {
fprintf(stderr, "Failed to allocate memory for largest key names!\n");
exit(1);
}
}
/* SCAN loop */
do {
/* Calculate approximate percentage completion */
pct = 100 * (double)sampled/total_keys;
/* Grab some keys and point to the keys array */
reply = sendScan(&it);
keys = reply->element[1];
/* Reallocate our type and size array if we need to */
if(keys->elements > arrsize) {
types = zrealloc(types, sizeof(int)*keys->elements);
sizes = zrealloc(sizes, sizeof(unsigned long long)*keys->elements);
if(!types || !sizes) {
fprintf(stderr, "Failed to allocate storage for keys!\n");
exit(1);
}
arrsize = keys->elements;
}
/* Retreive types and then sizes */
getKeyTypes(keys, types);
getKeySizes(keys, types, sizes);
/* Now update our stats */
for(i=0;i<keys->elements;i++) {
if((type = types[i]) == TYPE_NONE)
continue;
totalsize[type] += sizes[i];
counts[type]++;
totlen += keys->element[i]->len;
sampled++;
if(biggest[type]<sizes[i]) {
printf(
"[%05.2f%%] Biggest %-6s found so far '%s' with %llu %s\n",
pct, typename[type], keys->element[i]->str, sizes[i],
typeunit[type]);
/* Keep track of biggest key name for this type */
maxkeys[type] = sdscpy(maxkeys[type], keys->element[i]->str);
if(!maxkeys[type]) {
fprintf(stderr, "Failed to allocate memory for key!\n");
exit(1);
}
/* Keep track of the biggest size for this type */
biggest[type] = sizes[i];
}
/* Update overall progress */
if(sampled % 1000000 == 0) {
printf("[%05.2f%%] Sampled %llu keys so far\n", pct, sampled);
}
}
/* Sleep if we've been directed to do so */
if(sampled && (sampled %100) == 0 && config.interval) {
usleep(config.interval);
}
freeReplyObject(reply);
} while(it != 0);
if(types) zfree(types);
if(sizes) zfree(sizes);
/* We're done */
printf("\n-------- summary -------\n\n");
printf("Sampled %llu keys in the keyspace!\n", sampled);
printf("Total key length in bytes is %llu (avg len %.2f)\n\n",
totlen, totlen ? (double)totlen/sampled : 0);
/* Output the biggest keys we found, for types we did find */
for(i=0;i<TYPE_NONE;i++) {
if(sdslen(maxkeys[i])>0) {
printf("Biggest %6s found '%s' has %llu %s\n", typename[i], maxkeys[i],
biggest[i], typeunit[i]);
}
}
printf("\n");
for(i=0;i<TYPE_NONE;i++) {
printf("%llu %ss with %llu %s (%05.2f%% of keys, avg size %.2f)\n",
counts[i], typename[i], totalsize[i], typeunit[i],
sampled ? 100 * (double)counts[i]/sampled : 0,
counts[i] ? (double)totalsize[i]/counts[i] : 0);
}
/* Free sds strings containing max keys */
for(i=0;i<TYPE_NONE;i++) {
sdsfree(maxkeys[i]);
}
/* Success! */
exit(0);
}
static void getKeyFreqs(redisReply *keys, unsigned long long *freqs) {
redisReply *reply;
unsigned int i;
/* Pipeline OBJECT freq commands */
for(i=0;i<keys->elements;i++) {
redisAppendCommand(context, "OBJECT freq %s", keys->element[i]->str);
}
/* Retrieve freqs */
for(i=0;i<keys->elements;i++) {
if(redisGetReply(context, (void**)&reply)!=REDIS_OK) {
fprintf(stderr, "Error getting freq for key '%s' (%d: %s)\n",
keys->element[i]->str, context->err, context->errstr);
exit(1);
} else if(reply->type != REDIS_REPLY_INTEGER) {
if(reply->type == REDIS_REPLY_ERROR) {
fprintf(stderr, "Error: %s\n", reply->str);
exit(1);
} else {
fprintf(stderr, "Warning: OBJECT freq on '%s' failed (may have been deleted)\n", keys->element[i]->str);
freqs[i] = 0;
}
} else {
freqs[i] = reply->integer;
}
freeReplyObject(reply);
}
}
#define HOTKEYS_SAMPLE 16
static void findHotKeys(void) {
redisReply *keys, *reply;
unsigned long long counters[HOTKEYS_SAMPLE] = {0};
sds hotkeys[HOTKEYS_SAMPLE] = {NULL};
unsigned long long sampled = 0, total_keys, *freqs = NULL, it = 0;
unsigned int arrsize = 0, i, k;
double pct;
/* Total keys pre scanning */
total_keys = getDbSize();
/* Status message */
printf("\n# Scanning the entire keyspace to find hot keys as well as\n");
printf("# average sizes per key type. You can use -i 0.1 to sleep 0.1 sec\n");
printf("# per 100 SCAN commands (not usually needed).\n\n");
/* SCAN loop */
do {
/* Calculate approximate percentage completion */
pct = 100 * (double)sampled/total_keys;
/* Grab some keys and point to the keys array */
reply = sendScan(&it);
keys = reply->element[1];
/* Reallocate our freqs array if we need to */
if(keys->elements > arrsize) {
freqs = zrealloc(freqs, sizeof(unsigned long long)*keys->elements);
if(!freqs) {
fprintf(stderr, "Failed to allocate storage for keys!\n");
exit(1);
}
arrsize = keys->elements;
}
getKeyFreqs(keys, freqs);
/* Now update our stats */
for(i=0;i<keys->elements;i++) {
sampled++;
/* Update overall progress */
if(sampled % 1000000 == 0) {
printf("[%05.2f%%] Sampled %llu keys so far\n", pct, sampled);
}
/* Use eviction pool here */
k = 0;
while (k < HOTKEYS_SAMPLE && freqs[i] > counters[k]) k++;
if (k == 0) continue;
k--;
if (k == 0 || counters[k] == 0) {
sdsfree(hotkeys[k]);
} else {
sdsfree(hotkeys[0]);
memmove(counters,counters+1,sizeof(counters[0])*k);
memmove(hotkeys,hotkeys+1,sizeof(hotkeys[0])*k);
}
counters[k] = freqs[i];
hotkeys[k] = sdsnew(keys->element[i]->str);
printf(
"[%05.2f%%] Hot key '%s' found so far with counter %llu\n",
pct, keys->element[i]->str, freqs[i]);
}
/* Sleep if we've been directed to do so */
if(sampled && (sampled %100) == 0 && config.interval) {
usleep(config.interval);
}
freeReplyObject(reply);
} while(it != 0);
if (freqs) zfree(freqs);
/* We're done */
printf("\n-------- summary -------\n\n");
printf("Sampled %llu keys in the keyspace!\n", sampled);
for (i=1; i<= HOTKEYS_SAMPLE; i++) {
k = HOTKEYS_SAMPLE - i;
if(counters[k]>0) {
printf("hot key found with counter: %llu\tkeyname: %s\n", counters[k], hotkeys[k]);
sdsfree(hotkeys[k]);
}
}
exit(0);
}
/*------------------------------------------------------------------------------
* Stats mode
*--------------------------------------------------------------------------- */
/* Return the specified INFO field from the INFO command output "info".
* A new buffer is allocated for the result, that needs to be free'd.
* If the field is not found NULL is returned. */
static char *getInfoField(char *info, char *field) {
char *p = strstr(info,field);
char *n1, *n2;
char *result;
if (!p) return NULL;
p += strlen(field)+1;
n1 = strchr(p,'\r');
n2 = strchr(p,',');
if (n2 && n2 < n1) n1 = n2;
result = zmalloc(sizeof(char)*(n1-p)+1);
memcpy(result,p,(n1-p));
result[n1-p] = '\0';
return result;
}
/* Like the above function but automatically convert the result into
* a long. On error (missing field) LONG_MIN is returned. */
static long getLongInfoField(char *info, char *field) {
char *value = getInfoField(info,field);
long l;
if (!value) return LONG_MIN;
l = strtol(value,NULL,10);
zfree(value);
return l;
}
/* Convert number of bytes into a human readable string of the form:
* 100B, 2G, 100M, 4K, and so forth. */
void bytesToHuman(char *s, long long n) {
double d;
if (n < 0) {
*s = '-';
s++;
n = -n;
}
if (n < 1024) {
/* Bytes */
sprintf(s,"%lldB",n);
return;
} else if (n < (1024*1024)) {
d = (double)n/(1024);
sprintf(s,"%.2fK",d);
} else if (n < (1024LL*1024*1024)) {
d = (double)n/(1024*1024);
sprintf(s,"%.2fM",d);
} else if (n < (1024LL*1024*1024*1024)) {
d = (double)n/(1024LL*1024*1024);
sprintf(s,"%.2fG",d);
}
}
static void statMode(void) {
redisReply *reply;
long aux, requests = 0;
int i = 0;
while(1) {
char buf[64];
int j;
reply = reconnectingRedisCommand(context,"INFO");
if (reply->type == REDIS_REPLY_ERROR) {
printf("ERROR: %s\n", reply->str);
exit(1);
}
if ((i++ % 20) == 0) {
printf(
"------- data ------ --------------------- load -------------------- - child -\n"
"keys mem clients blocked requests connections \n");
}
/* Keys */
aux = 0;
for (j = 0; j < 20; j++) {
long k;
sprintf(buf,"db%d:keys",j);
k = getLongInfoField(reply->str,buf);
if (k == LONG_MIN) continue;
aux += k;
}
sprintf(buf,"%ld",aux);
printf("%-11s",buf);
/* Used memory */
aux = getLongInfoField(reply->str,"used_memory");
bytesToHuman(buf,aux);
printf("%-8s",buf);
/* Clients */
aux = getLongInfoField(reply->str,"connected_clients");
sprintf(buf,"%ld",aux);
printf(" %-8s",buf);
/* Blocked (BLPOPPING) Clients */
aux = getLongInfoField(reply->str,"blocked_clients");
sprintf(buf,"%ld",aux);
printf("%-8s",buf);
/* Requests */
aux = getLongInfoField(reply->str,"total_commands_processed");
sprintf(buf,"%ld (+%ld)",aux,requests == 0 ? 0 : aux-requests);
printf("%-19s",buf);
requests = aux;
/* Connections */
aux = getLongInfoField(reply->str,"total_connections_received");
sprintf(buf,"%ld",aux);
printf(" %-12s",buf);
/* Children */
aux = getLongInfoField(reply->str,"bgsave_in_progress");
aux |= getLongInfoField(reply->str,"aof_rewrite_in_progress") << 1;
aux |= getLongInfoField(reply->str,"loading") << 2;
switch(aux) {
case 0: break;
case 1:
printf("SAVE");
break;
case 2:
printf("AOF");
break;
case 3:
printf("SAVE+AOF");
break;
case 4:
printf("LOAD");
break;
}
printf("\n");
freeReplyObject(reply);
usleep(config.interval);
}
}
/*------------------------------------------------------------------------------
* Scan mode
*--------------------------------------------------------------------------- */
static void scanMode(void) {
redisReply *reply;
unsigned long long cur = 0;
do {
if (config.pattern)
reply = redisCommand(context,"SCAN %llu MATCH %s",
cur,config.pattern);
else
reply = redisCommand(context,"SCAN %llu",cur);
if (reply == NULL) {
printf("I/O error\n");
exit(1);
} else if (reply->type == REDIS_REPLY_ERROR) {
printf("ERROR: %s\n", reply->str);
exit(1);
} else {
unsigned int j;
cur = strtoull(reply->element[0]->str,NULL,10);
for (j = 0; j < reply->element[1]->elements; j++)
printf("%s\n", reply->element[1]->element[j]->str);
}
freeReplyObject(reply);
} while(cur != 0);
exit(0);
}
/*------------------------------------------------------------------------------
* LRU test mode
*--------------------------------------------------------------------------- */
/* Return an integer from min to max (both inclusive) using a power-law
* distribution, depending on the value of alpha: the greater the alpha
* the more bias towards lower values.
*
* With alpha = 6.2 the output follows the 80-20 rule where 20% of
* the returned numbers will account for 80% of the frequency. */
long long powerLawRand(long long min, long long max, double alpha) {
double pl, r;
max += 1;
r = ((double)rand()) / RAND_MAX;
pl = pow(
((pow(max,alpha+1) - pow(min,alpha+1))*r + pow(min,alpha+1)),
(1.0/(alpha+1)));
return (max-1-(long long)pl)+min;
}
/* Generates a key name among a set of lru_test_sample_size keys, using
* an 80-20 distribution. */
void LRUTestGenKey(char *buf, size_t buflen) {
snprintf(buf, buflen, "lru:%lld",
powerLawRand(1, config.lru_test_sample_size, 6.2));
}
#define LRU_CYCLE_PERIOD 1000 /* 1000 milliseconds. */
#define LRU_CYCLE_PIPELINE_SIZE 250
static void LRUTestMode(void) {
redisReply *reply;
char key[128];
long long start_cycle;
int j;
srand(time(NULL)^getpid());
while(1) {
/* Perform cycles of 1 second with 50% writes and 50% reads.
* We use pipelining batching writes / reads N times per cycle in order
* to fill the target instance easily. */
start_cycle = mstime();
long long hits = 0, misses = 0;
while(mstime() - start_cycle < 1000) {
/* Write cycle. */
for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++) {
char val[6];
val[5] = '\0';
for (int i = 0; i < 5; i++) val[i] = 'A'+rand()%('z'-'A');
LRUTestGenKey(key,sizeof(key));
redisAppendCommand(context, "SET %s %s",key,val);
}
for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++)
redisGetReply(context, (void**)&reply);
/* Read cycle. */
for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++) {
LRUTestGenKey(key,sizeof(key));
redisAppendCommand(context, "GET %s",key);
}
for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++) {
if (redisGetReply(context, (void**)&reply) == REDIS_OK) {
switch(reply->type) {
case REDIS_REPLY_ERROR:
printf("%s\n", reply->str);
break;
case REDIS_REPLY_NIL:
misses++;
break;
default:
hits++;
break;
}
}
}
if (context->err) {
fprintf(stderr,"I/O error during LRU test\n");
exit(1);
}
}
/* Print stats. */
printf(
"%lld Gets/sec | Hits: %lld (%.2f%%) | Misses: %lld (%.2f%%)\n",
hits+misses,
hits, (double)hits/(hits+misses)*100,
misses, (double)misses/(hits+misses)*100);
}
exit(0);
}
/*------------------------------------------------------------------------------
* Intrisic latency mode.
*
* Measure max latency of a running process that does not result from
* syscalls. Basically this software should provide an hint about how much
* time the kernel leaves the process without a chance to run.
*--------------------------------------------------------------------------- */
/* This is just some computation the compiler can't optimize out.
* Should run in less than 100-200 microseconds even using very
* slow hardware. Runs in less than 10 microseconds in modern HW. */
unsigned long compute_something_fast(void) {
unsigned char s[256], i, j, t;
int count = 1000, k;
unsigned long output = 0;
for (k = 0; k < 256; k++) s[k] = k;
i = 0;
j = 0;
while(count--) {
i++;
j = j + s[i];
t = s[i];
s[i] = s[j];
s[j] = t;
output += s[(s[i]+s[j])&255];
}
return output;
}
static void intrinsicLatencyModeStop(int s) {
UNUSED(s);
force_cancel_loop = 1;
}
static void intrinsicLatencyMode(void) {
long long test_end, run_time, max_latency = 0, runs = 0;
run_time = config.intrinsic_latency_duration*1000000;
test_end = ustime() + run_time;
signal(SIGINT, intrinsicLatencyModeStop);
while(1) {
long long start, end, latency;
start = ustime();
compute_something_fast();
end = ustime();
latency = end-start;
runs++;
if (latency <= 0) continue;
/* Reporting */
if (latency > max_latency) {
max_latency = latency;
printf("Max latency so far: %lld microseconds.\n", max_latency);
}
double avg_us = (double)run_time/runs;
double avg_ns = avg_us * 1e3;
if (force_cancel_loop || end > test_end) {
printf("\n%lld total runs "
"(avg latency: "
"%.4f microseconds / %.2f nanoseconds per run).\n",
runs, avg_us, avg_ns);
printf("Worst run took %.0fx longer than the average latency.\n",
max_latency / avg_us);
exit(0);
}
}
}
/*------------------------------------------------------------------------------
* Program main()
*--------------------------------------------------------------------------- */
int main(int argc, char **argv) {
int firstarg;
config.hostip = sdsnew("127.0.0.1");
config.hostport = 6379;
config.hostsocket = NULL;
config.repeat = 1;
config.interval = 0;
config.dbnum = 0;
config.interactive = 0;
config.shutdown = 0;
config.monitor_mode = 0;
config.pubsub_mode = 0;
config.latency_mode = 0;
config.latency_dist_mode = 0;
config.latency_history = 0;
config.lru_test_mode = 0;
config.lru_test_sample_size = 0;
config.cluster_mode = 0;
config.slave_mode = 0;
config.getrdb_mode = 0;
config.stat_mode = 0;
config.scan_mode = 0;
config.intrinsic_latency_mode = 0;
config.pattern = NULL;
config.rdb_filename = NULL;
config.pipe_mode = 0;
config.pipe_timeout = REDIS_CLI_DEFAULT_PIPE_TIMEOUT;
config.bigkeys = 0;
config.hotkeys = 0;
config.stdinarg = 0;
config.auth = NULL;
config.eval = NULL;
config.eval_ldb = 0;
config.eval_ldb_end = 0;
config.eval_ldb_sync = 0;
config.enable_ldb_on_eval = 0;
config.last_cmd_type = -1;
pref.hints = 1;
spectrum_palette = spectrum_palette_color;
spectrum_palette_size = spectrum_palette_color_size;
if (!isatty(fileno(stdout)) && (getenv("FAKETTY") == NULL))
config.output = OUTPUT_RAW;
else
config.output = OUTPUT_STANDARD;
config.mb_delim = sdsnew("\n");
firstarg = parseOptions(argc,argv);
argc -= firstarg;
argv += firstarg;
/* Latency mode */
if (config.latency_mode) {
if (cliConnect(0) == REDIS_ERR) exit(1);
latencyMode();
}
/* Latency distribution mode */
if (config.latency_dist_mode) {
if (cliConnect(0) == REDIS_ERR) exit(1);
latencyDistMode();
}
/* Slave mode */
if (config.slave_mode) {
if (cliConnect(0) == REDIS_ERR) exit(1);
slaveMode();
}
/* Get RDB mode. */
if (config.getrdb_mode) {
if (cliConnect(0) == REDIS_ERR) exit(1);
getRDB();
}
/* Pipe mode */
if (config.pipe_mode) {
if (cliConnect(0) == REDIS_ERR) exit(1);
pipeMode();
}
/* Find big keys */
if (config.bigkeys) {
if (cliConnect(0) == REDIS_ERR) exit(1);
findBigKeys();
}
/* Find hot keys */
if (config.hotkeys) {
if (cliConnect(0) == REDIS_ERR) exit(1);
findHotKeys();
}
/* Stat mode */
if (config.stat_mode) {
if (cliConnect(0) == REDIS_ERR) exit(1);
if (config.interval == 0) config.interval = 1000000;
statMode();
}
/* Scan mode */
if (config.scan_mode) {
if (cliConnect(0) == REDIS_ERR) exit(1);
scanMode();
}
/* LRU test mode */
if (config.lru_test_mode) {
if (cliConnect(0) == REDIS_ERR) exit(1);
LRUTestMode();
}
/* Intrinsic latency mode */
if (config.intrinsic_latency_mode) intrinsicLatencyMode();
/* Start interactive mode when no command is provided */
if (argc == 0 && !config.eval) {
/* Ignore SIGPIPE in interactive mode to force a reconnect */
signal(SIGPIPE, SIG_IGN);
/* Note that in repl mode we don't abort on connection error.
* A new attempt will be performed for every command send. */
cliConnect(0);
repl();
}
/* Otherwise, we have some arguments to execute */
if (cliConnect(0) != REDIS_OK) exit(1);
if (config.eval) {
return evalMode(argc,argv);
} else {
return noninteractive(argc,convertToSds(argc,argv));
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_183_0 |
crossvul-cpp_data_good_5762_0 | /*
* Luminary Micro Stellaris Ethernet Controller
*
* Copyright (c) 2007 CodeSourcery.
* Written by Paul Brook
*
* This code is licensed under the GPL.
*/
#include "hw/sysbus.h"
#include "net/net.h"
#include <zlib.h>
//#define DEBUG_STELLARIS_ENET 1
#ifdef DEBUG_STELLARIS_ENET
#define DPRINTF(fmt, ...) \
do { printf("stellaris_enet: " fmt , ## __VA_ARGS__); } while (0)
#define BADF(fmt, ...) \
do { fprintf(stderr, "stellaris_enet: error: " fmt , ## __VA_ARGS__); exit(1);} while (0)
#else
#define DPRINTF(fmt, ...) do {} while(0)
#define BADF(fmt, ...) \
do { fprintf(stderr, "stellaris_enet: error: " fmt , ## __VA_ARGS__);} while (0)
#endif
#define SE_INT_RX 0x01
#define SE_INT_TXER 0x02
#define SE_INT_TXEMP 0x04
#define SE_INT_FOV 0x08
#define SE_INT_RXER 0x10
#define SE_INT_MD 0x20
#define SE_INT_PHY 0x40
#define SE_RCTL_RXEN 0x01
#define SE_RCTL_AMUL 0x02
#define SE_RCTL_PRMS 0x04
#define SE_RCTL_BADCRC 0x08
#define SE_RCTL_RSTFIFO 0x10
#define SE_TCTL_TXEN 0x01
#define SE_TCTL_PADEN 0x02
#define SE_TCTL_CRC 0x04
#define SE_TCTL_DUPLEX 0x08
#define TYPE_STELLARIS_ENET "stellaris_enet"
#define STELLARIS_ENET(obj) \
OBJECT_CHECK(stellaris_enet_state, (obj), TYPE_STELLARIS_ENET)
typedef struct {
uint8_t data[2048];
uint32_t len;
} StellarisEnetRxFrame;
typedef struct {
SysBusDevice parent_obj;
uint32_t ris;
uint32_t im;
uint32_t rctl;
uint32_t tctl;
uint32_t thr;
uint32_t mctl;
uint32_t mdv;
uint32_t mtxd;
uint32_t mrxd;
uint32_t np;
uint32_t tx_fifo_len;
uint8_t tx_fifo[2048];
/* Real hardware has a 2k fifo, which works out to be at most 31 packets.
We implement a full 31 packet fifo. */
StellarisEnetRxFrame rx[31];
uint32_t rx_fifo_offset;
uint32_t next_packet;
NICState *nic;
NICConf conf;
qemu_irq irq;
MemoryRegion mmio;
} stellaris_enet_state;
static const VMStateDescription vmstate_rx_frame = {
.name = "stellaris_enet/rx_frame",
.version_id = 1,
.minimum_version_id = 1,
.fields = (VMStateField[]) {
VMSTATE_UINT8_ARRAY(data, StellarisEnetRxFrame, 2048),
VMSTATE_UINT32(len, StellarisEnetRxFrame),
VMSTATE_END_OF_LIST()
}
};
static int stellaris_enet_post_load(void *opaque, int version_id)
{
stellaris_enet_state *s = opaque;
int i;
/* Sanitize inbound state. Note that next_packet is an index but
* np is a size; hence their valid upper bounds differ.
*/
if (s->next_packet >= ARRAY_SIZE(s->rx)) {
return -1;
}
if (s->np > ARRAY_SIZE(s->rx)) {
return -1;
}
for (i = 0; i < ARRAY_SIZE(s->rx); i++) {
if (s->rx[i].len > ARRAY_SIZE(s->rx[i].data)) {
return -1;
}
}
if (s->rx_fifo_offset > ARRAY_SIZE(s->rx[0].data) - 4) {
return -1;
}
if (s->tx_fifo_len > ARRAY_SIZE(s->tx_fifo)) {
return -1;
}
return 0;
}
static const VMStateDescription vmstate_stellaris_enet = {
.name = "stellaris_enet",
.version_id = 2,
.minimum_version_id = 2,
.post_load = stellaris_enet_post_load,
.fields = (VMStateField[]) {
VMSTATE_UINT32(ris, stellaris_enet_state),
VMSTATE_UINT32(im, stellaris_enet_state),
VMSTATE_UINT32(rctl, stellaris_enet_state),
VMSTATE_UINT32(tctl, stellaris_enet_state),
VMSTATE_UINT32(thr, stellaris_enet_state),
VMSTATE_UINT32(mctl, stellaris_enet_state),
VMSTATE_UINT32(mdv, stellaris_enet_state),
VMSTATE_UINT32(mtxd, stellaris_enet_state),
VMSTATE_UINT32(mrxd, stellaris_enet_state),
VMSTATE_UINT32(np, stellaris_enet_state),
VMSTATE_UINT32(tx_fifo_len, stellaris_enet_state),
VMSTATE_UINT8_ARRAY(tx_fifo, stellaris_enet_state, 2048),
VMSTATE_STRUCT_ARRAY(rx, stellaris_enet_state, 31, 1,
vmstate_rx_frame, StellarisEnetRxFrame),
VMSTATE_UINT32(rx_fifo_offset, stellaris_enet_state),
VMSTATE_UINT32(next_packet, stellaris_enet_state),
VMSTATE_END_OF_LIST()
}
};
static void stellaris_enet_update(stellaris_enet_state *s)
{
qemu_set_irq(s->irq, (s->ris & s->im) != 0);
}
/* Return the data length of the packet currently being assembled
* in the TX fifo.
*/
static inline int stellaris_txpacket_datalen(stellaris_enet_state *s)
{
return s->tx_fifo[0] | (s->tx_fifo[1] << 8);
}
/* Return true if the packet currently in the TX FIFO is complete,
* ie the FIFO holds enough bytes for the data length, ethernet header,
* payload and optionally CRC.
*/
static inline bool stellaris_txpacket_complete(stellaris_enet_state *s)
{
int framelen = stellaris_txpacket_datalen(s);
framelen += 16;
if (!(s->tctl & SE_TCTL_CRC)) {
framelen += 4;
}
/* Cover the corner case of a 2032 byte payload with auto-CRC disabled:
* this requires more bytes than will fit in the FIFO. It's not totally
* clear how the h/w handles this, but if using threshold-based TX
* it will definitely try to transmit something.
*/
framelen = MIN(framelen, ARRAY_SIZE(s->tx_fifo));
return s->tx_fifo_len >= framelen;
}
/* Return true if the TX FIFO threshold is enabled and the FIFO
* has filled enough to reach it.
*/
static inline bool stellaris_tx_thr_reached(stellaris_enet_state *s)
{
return (s->thr < 0x3f &&
(s->tx_fifo_len >= 4 * (s->thr * 8 + 1)));
}
/* Send the packet currently in the TX FIFO */
static void stellaris_enet_send(stellaris_enet_state *s)
{
int framelen = stellaris_txpacket_datalen(s);
/* Ethernet header is in the FIFO but not in the datacount.
* We don't implement explicit CRC, so just ignore any
* CRC value in the FIFO.
*/
framelen += 14;
if ((s->tctl & SE_TCTL_PADEN) && framelen < 60) {
memset(&s->tx_fifo[framelen + 2], 0, 60 - framelen);
framelen = 60;
}
/* This MIN will have no effect unless the FIFO data is corrupt
* (eg bad data from an incoming migration); otherwise the check
* on the datalen at the start of writing the data into the FIFO
* will have caught this. Silently write a corrupt half-packet,
* which is what the hardware does in FIFO underrun situations.
*/
framelen = MIN(framelen, ARRAY_SIZE(s->tx_fifo) - 2);
qemu_send_packet(qemu_get_queue(s->nic), s->tx_fifo + 2, framelen);
s->tx_fifo_len = 0;
s->ris |= SE_INT_TXEMP;
stellaris_enet_update(s);
DPRINTF("Done TX\n");
}
/* TODO: Implement MAC address filtering. */
static ssize_t stellaris_enet_receive(NetClientState *nc, const uint8_t *buf, size_t size)
{
stellaris_enet_state *s = qemu_get_nic_opaque(nc);
int n;
uint8_t *p;
uint32_t crc;
if ((s->rctl & SE_RCTL_RXEN) == 0)
return -1;
if (s->np >= 31) {
DPRINTF("Packet dropped\n");
return -1;
}
DPRINTF("Received packet len=%zu\n", size);
n = s->next_packet + s->np;
if (n >= 31)
n -= 31;
s->np++;
s->rx[n].len = size + 6;
p = s->rx[n].data;
*(p++) = (size + 6);
*(p++) = (size + 6) >> 8;
memcpy (p, buf, size);
p += size;
crc = crc32(~0, buf, size);
*(p++) = crc;
*(p++) = crc >> 8;
*(p++) = crc >> 16;
*(p++) = crc >> 24;
/* Clear the remaining bytes in the last word. */
if ((size & 3) != 2) {
memset(p, 0, (6 - size) & 3);
}
s->ris |= SE_INT_RX;
stellaris_enet_update(s);
return size;
}
static int stellaris_enet_can_receive(NetClientState *nc)
{
stellaris_enet_state *s = qemu_get_nic_opaque(nc);
if ((s->rctl & SE_RCTL_RXEN) == 0)
return 1;
return (s->np < 31);
}
static uint64_t stellaris_enet_read(void *opaque, hwaddr offset,
unsigned size)
{
stellaris_enet_state *s = (stellaris_enet_state *)opaque;
uint32_t val;
switch (offset) {
case 0x00: /* RIS */
DPRINTF("IRQ status %02x\n", s->ris);
return s->ris;
case 0x04: /* IM */
return s->im;
case 0x08: /* RCTL */
return s->rctl;
case 0x0c: /* TCTL */
return s->tctl;
case 0x10: /* DATA */
{
uint8_t *rx_fifo;
if (s->np == 0) {
BADF("RX underflow\n");
return 0;
}
rx_fifo = s->rx[s->next_packet].data + s->rx_fifo_offset;
val = rx_fifo[0] | (rx_fifo[1] << 8) | (rx_fifo[2] << 16)
| (rx_fifo[3] << 24);
s->rx_fifo_offset += 4;
if (s->rx_fifo_offset >= s->rx[s->next_packet].len) {
s->rx_fifo_offset = 0;
s->next_packet++;
if (s->next_packet >= 31)
s->next_packet = 0;
s->np--;
DPRINTF("RX done np=%d\n", s->np);
}
return val;
}
case 0x14: /* IA0 */
return s->conf.macaddr.a[0] | (s->conf.macaddr.a[1] << 8)
| (s->conf.macaddr.a[2] << 16)
| ((uint32_t)s->conf.macaddr.a[3] << 24);
case 0x18: /* IA1 */
return s->conf.macaddr.a[4] | (s->conf.macaddr.a[5] << 8);
case 0x1c: /* THR */
return s->thr;
case 0x20: /* MCTL */
return s->mctl;
case 0x24: /* MDV */
return s->mdv;
case 0x28: /* MADD */
return 0;
case 0x2c: /* MTXD */
return s->mtxd;
case 0x30: /* MRXD */
return s->mrxd;
case 0x34: /* NP */
return s->np;
case 0x38: /* TR */
return 0;
case 0x3c: /* Undocuented: Timestamp? */
return 0;
default:
hw_error("stellaris_enet_read: Bad offset %x\n", (int)offset);
return 0;
}
}
static void stellaris_enet_write(void *opaque, hwaddr offset,
uint64_t value, unsigned size)
{
stellaris_enet_state *s = (stellaris_enet_state *)opaque;
switch (offset) {
case 0x00: /* IACK */
s->ris &= ~value;
DPRINTF("IRQ ack %02" PRIx64 "/%02x\n", value, s->ris);
stellaris_enet_update(s);
/* Clearing TXER also resets the TX fifo. */
if (value & SE_INT_TXER) {
s->tx_fifo_len = 0;
}
break;
case 0x04: /* IM */
DPRINTF("IRQ mask %02" PRIx64 "/%02x\n", value, s->ris);
s->im = value;
stellaris_enet_update(s);
break;
case 0x08: /* RCTL */
s->rctl = value;
if (value & SE_RCTL_RSTFIFO) {
s->np = 0;
s->rx_fifo_offset = 0;
stellaris_enet_update(s);
}
break;
case 0x0c: /* TCTL */
s->tctl = value;
break;
case 0x10: /* DATA */
if (s->tx_fifo_len == 0) {
/* The first word is special, it contains the data length */
int framelen = value & 0xffff;
if (framelen > 2032) {
DPRINTF("TX frame too long (%d)\n", framelen);
s->ris |= SE_INT_TXER;
stellaris_enet_update(s);
break;
}
}
if (s->tx_fifo_len + 4 <= ARRAY_SIZE(s->tx_fifo)) {
s->tx_fifo[s->tx_fifo_len++] = value;
s->tx_fifo[s->tx_fifo_len++] = value >> 8;
s->tx_fifo[s->tx_fifo_len++] = value >> 16;
s->tx_fifo[s->tx_fifo_len++] = value >> 24;
}
if (stellaris_tx_thr_reached(s) && stellaris_txpacket_complete(s)) {
stellaris_enet_send(s);
}
break;
case 0x14: /* IA0 */
s->conf.macaddr.a[0] = value;
s->conf.macaddr.a[1] = value >> 8;
s->conf.macaddr.a[2] = value >> 16;
s->conf.macaddr.a[3] = value >> 24;
break;
case 0x18: /* IA1 */
s->conf.macaddr.a[4] = value;
s->conf.macaddr.a[5] = value >> 8;
break;
case 0x1c: /* THR */
s->thr = value;
break;
case 0x20: /* MCTL */
s->mctl = value;
break;
case 0x24: /* MDV */
s->mdv = value;
break;
case 0x28: /* MADD */
/* ignored. */
break;
case 0x2c: /* MTXD */
s->mtxd = value & 0xff;
break;
case 0x38: /* TR */
if (value & 1) {
stellaris_enet_send(s);
}
break;
case 0x30: /* MRXD */
case 0x34: /* NP */
/* Ignored. */
case 0x3c: /* Undocuented: Timestamp? */
/* Ignored. */
break;
default:
hw_error("stellaris_enet_write: Bad offset %x\n", (int)offset);
}
}
static const MemoryRegionOps stellaris_enet_ops = {
.read = stellaris_enet_read,
.write = stellaris_enet_write,
.endianness = DEVICE_NATIVE_ENDIAN,
};
static void stellaris_enet_reset(stellaris_enet_state *s)
{
s->mdv = 0x80;
s->rctl = SE_RCTL_BADCRC;
s->im = SE_INT_PHY | SE_INT_MD | SE_INT_RXER | SE_INT_FOV | SE_INT_TXEMP
| SE_INT_TXER | SE_INT_RX;
s->thr = 0x3f;
s->tx_fifo_len = 0;
}
static void stellaris_enet_cleanup(NetClientState *nc)
{
stellaris_enet_state *s = qemu_get_nic_opaque(nc);
s->nic = NULL;
}
static NetClientInfo net_stellaris_enet_info = {
.type = NET_CLIENT_OPTIONS_KIND_NIC,
.size = sizeof(NICState),
.can_receive = stellaris_enet_can_receive,
.receive = stellaris_enet_receive,
.cleanup = stellaris_enet_cleanup,
};
static int stellaris_enet_init(SysBusDevice *sbd)
{
DeviceState *dev = DEVICE(sbd);
stellaris_enet_state *s = STELLARIS_ENET(dev);
memory_region_init_io(&s->mmio, OBJECT(s), &stellaris_enet_ops, s,
"stellaris_enet", 0x1000);
sysbus_init_mmio(sbd, &s->mmio);
sysbus_init_irq(sbd, &s->irq);
qemu_macaddr_default_if_unset(&s->conf.macaddr);
s->nic = qemu_new_nic(&net_stellaris_enet_info, &s->conf,
object_get_typename(OBJECT(dev)), dev->id, s);
qemu_format_nic_info_str(qemu_get_queue(s->nic), s->conf.macaddr.a);
stellaris_enet_reset(s);
return 0;
}
static void stellaris_enet_unrealize(DeviceState *dev, Error **errp)
{
stellaris_enet_state *s = STELLARIS_ENET(dev);
memory_region_destroy(&s->mmio);
}
static Property stellaris_enet_properties[] = {
DEFINE_NIC_PROPERTIES(stellaris_enet_state, conf),
DEFINE_PROP_END_OF_LIST(),
};
static void stellaris_enet_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);
k->init = stellaris_enet_init;
dc->unrealize = stellaris_enet_unrealize;
dc->props = stellaris_enet_properties;
dc->vmsd = &vmstate_stellaris_enet;
}
static const TypeInfo stellaris_enet_info = {
.name = TYPE_STELLARIS_ENET,
.parent = TYPE_SYS_BUS_DEVICE,
.instance_size = sizeof(stellaris_enet_state),
.class_init = stellaris_enet_class_init,
};
static void stellaris_enet_register_types(void)
{
type_register_static(&stellaris_enet_info);
}
type_init(stellaris_enet_register_types)
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5762_0 |
crossvul-cpp_data_good_2947_1 | /*
* parser.c : an XML 1.0 parser, namespaces and validity support are mostly
* implemented on top of the SAX interfaces
*
* References:
* The XML specification:
* http://www.w3.org/TR/REC-xml
* Original 1.0 version:
* http://www.w3.org/TR/1998/REC-xml-19980210
* XML second edition working draft
* http://www.w3.org/TR/2000/WD-xml-2e-20000814
*
* Okay this is a big file, the parser core is around 7000 lines, then it
* is followed by the progressive parser top routines, then the various
* high level APIs to call the parser and a few miscellaneous functions.
* A number of helper functions and deprecated ones have been moved to
* parserInternals.c to reduce this file size.
* As much as possible the functions are associated with their relative
* production in the XML specification. A few productions defining the
* different ranges of character are actually implanted either in
* parserInternals.h or parserInternals.c
* The DOM tree build is realized from the default SAX callbacks in
* the module SAX.c.
* The routines doing the validation checks are in valid.c and called either
* from the SAX callbacks or as standalone functions using a preparsed
* document.
*
* See Copyright for the status of this software.
*
* daniel@veillard.com
*/
#define IN_LIBXML
#include "libxml.h"
#if defined(WIN32) && !defined (__CYGWIN__)
#define XML_DIR_SEP '\\'
#else
#define XML_DIR_SEP '/'
#endif
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <stdarg.h>
#include <stddef.h>
#include <libxml/xmlmemory.h>
#include <libxml/threads.h>
#include <libxml/globals.h>
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/parserInternals.h>
#include <libxml/valid.h>
#include <libxml/entities.h>
#include <libxml/xmlerror.h>
#include <libxml/encoding.h>
#include <libxml/xmlIO.h>
#include <libxml/uri.h>
#ifdef LIBXML_CATALOG_ENABLED
#include <libxml/catalog.h>
#endif
#ifdef LIBXML_SCHEMAS_ENABLED
#include <libxml/xmlschemastypes.h>
#include <libxml/relaxng.h>
#endif
#ifdef HAVE_CTYPE_H
#include <ctype.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_ZLIB_H
#include <zlib.h>
#endif
#ifdef HAVE_LZMA_H
#include <lzma.h>
#endif
#include "buf.h"
#include "enc.h"
static void
xmlFatalErr(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *info);
static xmlParserCtxtPtr
xmlCreateEntityParserCtxtInternal(const xmlChar *URL, const xmlChar *ID,
const xmlChar *base, xmlParserCtxtPtr pctx);
static void xmlHaltParser(xmlParserCtxtPtr ctxt);
/************************************************************************
* *
* Arbitrary limits set in the parser. See XML_PARSE_HUGE *
* *
************************************************************************/
#define XML_PARSER_BIG_ENTITY 1000
#define XML_PARSER_LOT_ENTITY 5000
/*
* XML_PARSER_NON_LINEAR is the threshold where the ratio of parsed entity
* replacement over the size in byte of the input indicates that you have
* and eponential behaviour. A value of 10 correspond to at least 3 entity
* replacement per byte of input.
*/
#define XML_PARSER_NON_LINEAR 10
/*
* xmlParserEntityCheck
*
* Function to check non-linear entity expansion behaviour
* This is here to detect and stop exponential linear entity expansion
* This is not a limitation of the parser but a safety
* boundary feature. It can be disabled with the XML_PARSE_HUGE
* parser option.
*/
static int
xmlParserEntityCheck(xmlParserCtxtPtr ctxt, size_t size,
xmlEntityPtr ent, size_t replacement)
{
size_t consumed = 0;
if ((ctxt == NULL) || (ctxt->options & XML_PARSE_HUGE))
return (0);
if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP)
return (1);
/*
* This may look absurd but is needed to detect
* entities problems
*/
if ((ent != NULL) && (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) &&
(ent->content != NULL) && (ent->checked == 0) &&
(ctxt->errNo != XML_ERR_ENTITY_LOOP)) {
unsigned long oldnbent = ctxt->nbentities;
xmlChar *rep;
ent->checked = 1;
++ctxt->depth;
rep = xmlStringDecodeEntities(ctxt, ent->content,
XML_SUBSTITUTE_REF, 0, 0, 0);
--ctxt->depth;
if (ctxt->errNo == XML_ERR_ENTITY_LOOP) {
ent->content[0] = 0;
}
ent->checked = (ctxt->nbentities - oldnbent + 1) * 2;
if (rep != NULL) {
if (xmlStrchr(rep, '<'))
ent->checked |= 1;
xmlFree(rep);
rep = NULL;
}
}
if (replacement != 0) {
if (replacement < XML_MAX_TEXT_LENGTH)
return(0);
/*
* If the volume of entity copy reaches 10 times the
* amount of parsed data and over the large text threshold
* then that's very likely to be an abuse.
*/
if (ctxt->input != NULL) {
consumed = ctxt->input->consumed +
(ctxt->input->cur - ctxt->input->base);
}
consumed += ctxt->sizeentities;
if (replacement < XML_PARSER_NON_LINEAR * consumed)
return(0);
} else if (size != 0) {
/*
* Do the check based on the replacement size of the entity
*/
if (size < XML_PARSER_BIG_ENTITY)
return(0);
/*
* A limit on the amount of text data reasonably used
*/
if (ctxt->input != NULL) {
consumed = ctxt->input->consumed +
(ctxt->input->cur - ctxt->input->base);
}
consumed += ctxt->sizeentities;
if ((size < XML_PARSER_NON_LINEAR * consumed) &&
(ctxt->nbentities * 3 < XML_PARSER_NON_LINEAR * consumed))
return (0);
} else if (ent != NULL) {
/*
* use the number of parsed entities in the replacement
*/
size = ent->checked / 2;
/*
* The amount of data parsed counting entities size only once
*/
if (ctxt->input != NULL) {
consumed = ctxt->input->consumed +
(ctxt->input->cur - ctxt->input->base);
}
consumed += ctxt->sizeentities;
/*
* Check the density of entities for the amount of data
* knowing an entity reference will take at least 3 bytes
*/
if (size * 3 < consumed * XML_PARSER_NON_LINEAR)
return (0);
} else {
/*
* strange we got no data for checking
*/
if (((ctxt->lastError.code != XML_ERR_UNDECLARED_ENTITY) &&
(ctxt->lastError.code != XML_WAR_UNDECLARED_ENTITY)) ||
(ctxt->nbentities <= 10000))
return (0);
}
xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
return (1);
}
/**
* xmlParserMaxDepth:
*
* arbitrary depth limit for the XML documents that we allow to
* process. This is not a limitation of the parser but a safety
* boundary feature. It can be disabled with the XML_PARSE_HUGE
* parser option.
*/
unsigned int xmlParserMaxDepth = 256;
#define SAX2 1
#define XML_PARSER_BIG_BUFFER_SIZE 300
#define XML_PARSER_BUFFER_SIZE 100
#define SAX_COMPAT_MODE BAD_CAST "SAX compatibility mode document"
/**
* XML_PARSER_CHUNK_SIZE
*
* When calling GROW that's the minimal amount of data
* the parser expected to have received. It is not a hard
* limit but an optimization when reading strings like Names
* It is not strictly needed as long as inputs available characters
* are followed by 0, which should be provided by the I/O level
*/
#define XML_PARSER_CHUNK_SIZE 100
/*
* List of XML prefixed PI allowed by W3C specs
*/
static const char *xmlW3CPIs[] = {
"xml-stylesheet",
"xml-model",
NULL
};
/* DEPR void xmlParserHandleReference(xmlParserCtxtPtr ctxt); */
static xmlEntityPtr xmlParseStringPEReference(xmlParserCtxtPtr ctxt,
const xmlChar **str);
static xmlParserErrors
xmlParseExternalEntityPrivate(xmlDocPtr doc, xmlParserCtxtPtr oldctxt,
xmlSAXHandlerPtr sax,
void *user_data, int depth, const xmlChar *URL,
const xmlChar *ID, xmlNodePtr *list);
static int
xmlCtxtUseOptionsInternal(xmlParserCtxtPtr ctxt, int options,
const char *encoding);
#ifdef LIBXML_LEGACY_ENABLED
static void
xmlAddEntityReference(xmlEntityPtr ent, xmlNodePtr firstNode,
xmlNodePtr lastNode);
#endif /* LIBXML_LEGACY_ENABLED */
static xmlParserErrors
xmlParseBalancedChunkMemoryInternal(xmlParserCtxtPtr oldctxt,
const xmlChar *string, void *user_data, xmlNodePtr *lst);
static int
xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity);
/************************************************************************
* *
* Some factorized error routines *
* *
************************************************************************/
/**
* xmlErrAttributeDup:
* @ctxt: an XML parser context
* @prefix: the attribute prefix
* @localname: the attribute localname
*
* Handle a redefinition of attribute error
*/
static void
xmlErrAttributeDup(xmlParserCtxtPtr ctxt, const xmlChar * prefix,
const xmlChar * localname)
{
if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
(ctxt->instate == XML_PARSER_EOF))
return;
if (ctxt != NULL)
ctxt->errNo = XML_ERR_ATTRIBUTE_REDEFINED;
if (prefix == NULL)
__xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER,
XML_ERR_ATTRIBUTE_REDEFINED, XML_ERR_FATAL, NULL, 0,
(const char *) localname, NULL, NULL, 0, 0,
"Attribute %s redefined\n", localname);
else
__xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER,
XML_ERR_ATTRIBUTE_REDEFINED, XML_ERR_FATAL, NULL, 0,
(const char *) prefix, (const char *) localname,
NULL, 0, 0, "Attribute %s:%s redefined\n", prefix,
localname);
if (ctxt != NULL) {
ctxt->wellFormed = 0;
if (ctxt->recovery == 0)
ctxt->disableSAX = 1;
}
}
/**
* xmlFatalErr:
* @ctxt: an XML parser context
* @error: the error number
* @extra: extra information string
*
* Handle a fatal parser error, i.e. violating Well-Formedness constraints
*/
static void
xmlFatalErr(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *info)
{
const char *errmsg;
if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
(ctxt->instate == XML_PARSER_EOF))
return;
switch (error) {
case XML_ERR_INVALID_HEX_CHARREF:
errmsg = "CharRef: invalid hexadecimal value";
break;
case XML_ERR_INVALID_DEC_CHARREF:
errmsg = "CharRef: invalid decimal value";
break;
case XML_ERR_INVALID_CHARREF:
errmsg = "CharRef: invalid value";
break;
case XML_ERR_INTERNAL_ERROR:
errmsg = "internal error";
break;
case XML_ERR_PEREF_AT_EOF:
errmsg = "PEReference at end of document";
break;
case XML_ERR_PEREF_IN_PROLOG:
errmsg = "PEReference in prolog";
break;
case XML_ERR_PEREF_IN_EPILOG:
errmsg = "PEReference in epilog";
break;
case XML_ERR_PEREF_NO_NAME:
errmsg = "PEReference: no name";
break;
case XML_ERR_PEREF_SEMICOL_MISSING:
errmsg = "PEReference: expecting ';'";
break;
case XML_ERR_ENTITY_LOOP:
errmsg = "Detected an entity reference loop";
break;
case XML_ERR_ENTITY_NOT_STARTED:
errmsg = "EntityValue: \" or ' expected";
break;
case XML_ERR_ENTITY_PE_INTERNAL:
errmsg = "PEReferences forbidden in internal subset";
break;
case XML_ERR_ENTITY_NOT_FINISHED:
errmsg = "EntityValue: \" or ' expected";
break;
case XML_ERR_ATTRIBUTE_NOT_STARTED:
errmsg = "AttValue: \" or ' expected";
break;
case XML_ERR_LT_IN_ATTRIBUTE:
errmsg = "Unescaped '<' not allowed in attributes values";
break;
case XML_ERR_LITERAL_NOT_STARTED:
errmsg = "SystemLiteral \" or ' expected";
break;
case XML_ERR_LITERAL_NOT_FINISHED:
errmsg = "Unfinished System or Public ID \" or ' expected";
break;
case XML_ERR_MISPLACED_CDATA_END:
errmsg = "Sequence ']]>' not allowed in content";
break;
case XML_ERR_URI_REQUIRED:
errmsg = "SYSTEM or PUBLIC, the URI is missing";
break;
case XML_ERR_PUBID_REQUIRED:
errmsg = "PUBLIC, the Public Identifier is missing";
break;
case XML_ERR_HYPHEN_IN_COMMENT:
errmsg = "Comment must not contain '--' (double-hyphen)";
break;
case XML_ERR_PI_NOT_STARTED:
errmsg = "xmlParsePI : no target name";
break;
case XML_ERR_RESERVED_XML_NAME:
errmsg = "Invalid PI name";
break;
case XML_ERR_NOTATION_NOT_STARTED:
errmsg = "NOTATION: Name expected here";
break;
case XML_ERR_NOTATION_NOT_FINISHED:
errmsg = "'>' required to close NOTATION declaration";
break;
case XML_ERR_VALUE_REQUIRED:
errmsg = "Entity value required";
break;
case XML_ERR_URI_FRAGMENT:
errmsg = "Fragment not allowed";
break;
case XML_ERR_ATTLIST_NOT_STARTED:
errmsg = "'(' required to start ATTLIST enumeration";
break;
case XML_ERR_NMTOKEN_REQUIRED:
errmsg = "NmToken expected in ATTLIST enumeration";
break;
case XML_ERR_ATTLIST_NOT_FINISHED:
errmsg = "')' required to finish ATTLIST enumeration";
break;
case XML_ERR_MIXED_NOT_STARTED:
errmsg = "MixedContentDecl : '|' or ')*' expected";
break;
case XML_ERR_PCDATA_REQUIRED:
errmsg = "MixedContentDecl : '#PCDATA' expected";
break;
case XML_ERR_ELEMCONTENT_NOT_STARTED:
errmsg = "ContentDecl : Name or '(' expected";
break;
case XML_ERR_ELEMCONTENT_NOT_FINISHED:
errmsg = "ContentDecl : ',' '|' or ')' expected";
break;
case XML_ERR_PEREF_IN_INT_SUBSET:
errmsg =
"PEReference: forbidden within markup decl in internal subset";
break;
case XML_ERR_GT_REQUIRED:
errmsg = "expected '>'";
break;
case XML_ERR_CONDSEC_INVALID:
errmsg = "XML conditional section '[' expected";
break;
case XML_ERR_EXT_SUBSET_NOT_FINISHED:
errmsg = "Content error in the external subset";
break;
case XML_ERR_CONDSEC_INVALID_KEYWORD:
errmsg =
"conditional section INCLUDE or IGNORE keyword expected";
break;
case XML_ERR_CONDSEC_NOT_FINISHED:
errmsg = "XML conditional section not closed";
break;
case XML_ERR_XMLDECL_NOT_STARTED:
errmsg = "Text declaration '<?xml' required";
break;
case XML_ERR_XMLDECL_NOT_FINISHED:
errmsg = "parsing XML declaration: '?>' expected";
break;
case XML_ERR_EXT_ENTITY_STANDALONE:
errmsg = "external parsed entities cannot be standalone";
break;
case XML_ERR_ENTITYREF_SEMICOL_MISSING:
errmsg = "EntityRef: expecting ';'";
break;
case XML_ERR_DOCTYPE_NOT_FINISHED:
errmsg = "DOCTYPE improperly terminated";
break;
case XML_ERR_LTSLASH_REQUIRED:
errmsg = "EndTag: '</' not found";
break;
case XML_ERR_EQUAL_REQUIRED:
errmsg = "expected '='";
break;
case XML_ERR_STRING_NOT_CLOSED:
errmsg = "String not closed expecting \" or '";
break;
case XML_ERR_STRING_NOT_STARTED:
errmsg = "String not started expecting ' or \"";
break;
case XML_ERR_ENCODING_NAME:
errmsg = "Invalid XML encoding name";
break;
case XML_ERR_STANDALONE_VALUE:
errmsg = "standalone accepts only 'yes' or 'no'";
break;
case XML_ERR_DOCUMENT_EMPTY:
errmsg = "Document is empty";
break;
case XML_ERR_DOCUMENT_END:
errmsg = "Extra content at the end of the document";
break;
case XML_ERR_NOT_WELL_BALANCED:
errmsg = "chunk is not well balanced";
break;
case XML_ERR_EXTRA_CONTENT:
errmsg = "extra content at the end of well balanced chunk";
break;
case XML_ERR_VERSION_MISSING:
errmsg = "Malformed declaration expecting version";
break;
case XML_ERR_NAME_TOO_LONG:
errmsg = "Name too long use XML_PARSE_HUGE option";
break;
#if 0
case:
errmsg = "";
break;
#endif
default:
errmsg = "Unregistered error message";
}
if (ctxt != NULL)
ctxt->errNo = error;
if (info == NULL) {
__xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error,
XML_ERR_FATAL, NULL, 0, info, NULL, NULL, 0, 0, "%s\n",
errmsg);
} else {
__xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error,
XML_ERR_FATAL, NULL, 0, info, NULL, NULL, 0, 0, "%s: %s\n",
errmsg, info);
}
if (ctxt != NULL) {
ctxt->wellFormed = 0;
if (ctxt->recovery == 0)
ctxt->disableSAX = 1;
}
}
/**
* xmlFatalErrMsg:
* @ctxt: an XML parser context
* @error: the error number
* @msg: the error message
*
* Handle a fatal parser error, i.e. violating Well-Formedness constraints
*/
static void LIBXML_ATTR_FORMAT(3,0)
xmlFatalErrMsg(xmlParserCtxtPtr ctxt, xmlParserErrors error,
const char *msg)
{
if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
(ctxt->instate == XML_PARSER_EOF))
return;
if (ctxt != NULL)
ctxt->errNo = error;
__xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error,
XML_ERR_FATAL, NULL, 0, NULL, NULL, NULL, 0, 0, "%s", msg);
if (ctxt != NULL) {
ctxt->wellFormed = 0;
if (ctxt->recovery == 0)
ctxt->disableSAX = 1;
}
}
/**
* xmlWarningMsg:
* @ctxt: an XML parser context
* @error: the error number
* @msg: the error message
* @str1: extra data
* @str2: extra data
*
* Handle a warning.
*/
static void LIBXML_ATTR_FORMAT(3,0)
xmlWarningMsg(xmlParserCtxtPtr ctxt, xmlParserErrors error,
const char *msg, const xmlChar *str1, const xmlChar *str2)
{
xmlStructuredErrorFunc schannel = NULL;
if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
(ctxt->instate == XML_PARSER_EOF))
return;
if ((ctxt != NULL) && (ctxt->sax != NULL) &&
(ctxt->sax->initialized == XML_SAX2_MAGIC))
schannel = ctxt->sax->serror;
if (ctxt != NULL) {
__xmlRaiseError(schannel,
(ctxt->sax) ? ctxt->sax->warning : NULL,
ctxt->userData,
ctxt, NULL, XML_FROM_PARSER, error,
XML_ERR_WARNING, NULL, 0,
(const char *) str1, (const char *) str2, NULL, 0, 0,
msg, (const char *) str1, (const char *) str2);
} else {
__xmlRaiseError(schannel, NULL, NULL,
ctxt, NULL, XML_FROM_PARSER, error,
XML_ERR_WARNING, NULL, 0,
(const char *) str1, (const char *) str2, NULL, 0, 0,
msg, (const char *) str1, (const char *) str2);
}
}
/**
* xmlValidityError:
* @ctxt: an XML parser context
* @error: the error number
* @msg: the error message
* @str1: extra data
*
* Handle a validity error.
*/
static void LIBXML_ATTR_FORMAT(3,0)
xmlValidityError(xmlParserCtxtPtr ctxt, xmlParserErrors error,
const char *msg, const xmlChar *str1, const xmlChar *str2)
{
xmlStructuredErrorFunc schannel = NULL;
if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
(ctxt->instate == XML_PARSER_EOF))
return;
if (ctxt != NULL) {
ctxt->errNo = error;
if ((ctxt->sax != NULL) && (ctxt->sax->initialized == XML_SAX2_MAGIC))
schannel = ctxt->sax->serror;
}
if (ctxt != NULL) {
__xmlRaiseError(schannel,
ctxt->vctxt.error, ctxt->vctxt.userData,
ctxt, NULL, XML_FROM_DTD, error,
XML_ERR_ERROR, NULL, 0, (const char *) str1,
(const char *) str2, NULL, 0, 0,
msg, (const char *) str1, (const char *) str2);
ctxt->valid = 0;
} else {
__xmlRaiseError(schannel, NULL, NULL,
ctxt, NULL, XML_FROM_DTD, error,
XML_ERR_ERROR, NULL, 0, (const char *) str1,
(const char *) str2, NULL, 0, 0,
msg, (const char *) str1, (const char *) str2);
}
}
/**
* xmlFatalErrMsgInt:
* @ctxt: an XML parser context
* @error: the error number
* @msg: the error message
* @val: an integer value
*
* Handle a fatal parser error, i.e. violating Well-Formedness constraints
*/
static void LIBXML_ATTR_FORMAT(3,0)
xmlFatalErrMsgInt(xmlParserCtxtPtr ctxt, xmlParserErrors error,
const char *msg, int val)
{
if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
(ctxt->instate == XML_PARSER_EOF))
return;
if (ctxt != NULL)
ctxt->errNo = error;
__xmlRaiseError(NULL, NULL, NULL,
ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL,
NULL, 0, NULL, NULL, NULL, val, 0, msg, val);
if (ctxt != NULL) {
ctxt->wellFormed = 0;
if (ctxt->recovery == 0)
ctxt->disableSAX = 1;
}
}
/**
* xmlFatalErrMsgStrIntStr:
* @ctxt: an XML parser context
* @error: the error number
* @msg: the error message
* @str1: an string info
* @val: an integer value
* @str2: an string info
*
* Handle a fatal parser error, i.e. violating Well-Formedness constraints
*/
static void LIBXML_ATTR_FORMAT(3,0)
xmlFatalErrMsgStrIntStr(xmlParserCtxtPtr ctxt, xmlParserErrors error,
const char *msg, const xmlChar *str1, int val,
const xmlChar *str2)
{
if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
(ctxt->instate == XML_PARSER_EOF))
return;
if (ctxt != NULL)
ctxt->errNo = error;
__xmlRaiseError(NULL, NULL, NULL,
ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL,
NULL, 0, (const char *) str1, (const char *) str2,
NULL, val, 0, msg, str1, val, str2);
if (ctxt != NULL) {
ctxt->wellFormed = 0;
if (ctxt->recovery == 0)
ctxt->disableSAX = 1;
}
}
/**
* xmlFatalErrMsgStr:
* @ctxt: an XML parser context
* @error: the error number
* @msg: the error message
* @val: a string value
*
* Handle a fatal parser error, i.e. violating Well-Formedness constraints
*/
static void LIBXML_ATTR_FORMAT(3,0)
xmlFatalErrMsgStr(xmlParserCtxtPtr ctxt, xmlParserErrors error,
const char *msg, const xmlChar * val)
{
if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
(ctxt->instate == XML_PARSER_EOF))
return;
if (ctxt != NULL)
ctxt->errNo = error;
__xmlRaiseError(NULL, NULL, NULL, ctxt, NULL,
XML_FROM_PARSER, error, XML_ERR_FATAL,
NULL, 0, (const char *) val, NULL, NULL, 0, 0, msg,
val);
if (ctxt != NULL) {
ctxt->wellFormed = 0;
if (ctxt->recovery == 0)
ctxt->disableSAX = 1;
}
}
/**
* xmlErrMsgStr:
* @ctxt: an XML parser context
* @error: the error number
* @msg: the error message
* @val: a string value
*
* Handle a non fatal parser error
*/
static void LIBXML_ATTR_FORMAT(3,0)
xmlErrMsgStr(xmlParserCtxtPtr ctxt, xmlParserErrors error,
const char *msg, const xmlChar * val)
{
if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
(ctxt->instate == XML_PARSER_EOF))
return;
if (ctxt != NULL)
ctxt->errNo = error;
__xmlRaiseError(NULL, NULL, NULL, ctxt, NULL,
XML_FROM_PARSER, error, XML_ERR_ERROR,
NULL, 0, (const char *) val, NULL, NULL, 0, 0, msg,
val);
}
/**
* xmlNsErr:
* @ctxt: an XML parser context
* @error: the error number
* @msg: the message
* @info1: extra information string
* @info2: extra information string
*
* Handle a fatal parser error, i.e. violating Well-Formedness constraints
*/
static void LIBXML_ATTR_FORMAT(3,0)
xmlNsErr(xmlParserCtxtPtr ctxt, xmlParserErrors error,
const char *msg,
const xmlChar * info1, const xmlChar * info2,
const xmlChar * info3)
{
if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
(ctxt->instate == XML_PARSER_EOF))
return;
if (ctxt != NULL)
ctxt->errNo = error;
__xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_NAMESPACE, error,
XML_ERR_ERROR, NULL, 0, (const char *) info1,
(const char *) info2, (const char *) info3, 0, 0, msg,
info1, info2, info3);
if (ctxt != NULL)
ctxt->nsWellFormed = 0;
}
/**
* xmlNsWarn
* @ctxt: an XML parser context
* @error: the error number
* @msg: the message
* @info1: extra information string
* @info2: extra information string
*
* Handle a namespace warning error
*/
static void LIBXML_ATTR_FORMAT(3,0)
xmlNsWarn(xmlParserCtxtPtr ctxt, xmlParserErrors error,
const char *msg,
const xmlChar * info1, const xmlChar * info2,
const xmlChar * info3)
{
if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
(ctxt->instate == XML_PARSER_EOF))
return;
__xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_NAMESPACE, error,
XML_ERR_WARNING, NULL, 0, (const char *) info1,
(const char *) info2, (const char *) info3, 0, 0, msg,
info1, info2, info3);
}
/************************************************************************
* *
* Library wide options *
* *
************************************************************************/
/**
* xmlHasFeature:
* @feature: the feature to be examined
*
* Examines if the library has been compiled with a given feature.
*
* Returns a non-zero value if the feature exist, otherwise zero.
* Returns zero (0) if the feature does not exist or an unknown
* unknown feature is requested, non-zero otherwise.
*/
int
xmlHasFeature(xmlFeature feature)
{
switch (feature) {
case XML_WITH_THREAD:
#ifdef LIBXML_THREAD_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_TREE:
#ifdef LIBXML_TREE_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_OUTPUT:
#ifdef LIBXML_OUTPUT_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_PUSH:
#ifdef LIBXML_PUSH_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_READER:
#ifdef LIBXML_READER_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_PATTERN:
#ifdef LIBXML_PATTERN_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_WRITER:
#ifdef LIBXML_WRITER_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_SAX1:
#ifdef LIBXML_SAX1_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_FTP:
#ifdef LIBXML_FTP_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_HTTP:
#ifdef LIBXML_HTTP_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_VALID:
#ifdef LIBXML_VALID_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_HTML:
#ifdef LIBXML_HTML_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_LEGACY:
#ifdef LIBXML_LEGACY_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_C14N:
#ifdef LIBXML_C14N_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_CATALOG:
#ifdef LIBXML_CATALOG_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_XPATH:
#ifdef LIBXML_XPATH_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_XPTR:
#ifdef LIBXML_XPTR_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_XINCLUDE:
#ifdef LIBXML_XINCLUDE_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_ICONV:
#ifdef LIBXML_ICONV_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_ISO8859X:
#ifdef LIBXML_ISO8859X_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_UNICODE:
#ifdef LIBXML_UNICODE_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_REGEXP:
#ifdef LIBXML_REGEXP_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_AUTOMATA:
#ifdef LIBXML_AUTOMATA_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_EXPR:
#ifdef LIBXML_EXPR_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_SCHEMAS:
#ifdef LIBXML_SCHEMAS_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_SCHEMATRON:
#ifdef LIBXML_SCHEMATRON_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_MODULES:
#ifdef LIBXML_MODULES_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_DEBUG:
#ifdef LIBXML_DEBUG_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_DEBUG_MEM:
#ifdef DEBUG_MEMORY_LOCATION
return(1);
#else
return(0);
#endif
case XML_WITH_DEBUG_RUN:
#ifdef LIBXML_DEBUG_RUNTIME
return(1);
#else
return(0);
#endif
case XML_WITH_ZLIB:
#ifdef LIBXML_ZLIB_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_LZMA:
#ifdef LIBXML_LZMA_ENABLED
return(1);
#else
return(0);
#endif
case XML_WITH_ICU:
#ifdef LIBXML_ICU_ENABLED
return(1);
#else
return(0);
#endif
default:
break;
}
return(0);
}
/************************************************************************
* *
* SAX2 defaulted attributes handling *
* *
************************************************************************/
/**
* xmlDetectSAX2:
* @ctxt: an XML parser context
*
* Do the SAX2 detection and specific intialization
*/
static void
xmlDetectSAX2(xmlParserCtxtPtr ctxt) {
if (ctxt == NULL) return;
#ifdef LIBXML_SAX1_ENABLED
if ((ctxt->sax) && (ctxt->sax->initialized == XML_SAX2_MAGIC) &&
((ctxt->sax->startElementNs != NULL) ||
(ctxt->sax->endElementNs != NULL))) ctxt->sax2 = 1;
#else
ctxt->sax2 = 1;
#endif /* LIBXML_SAX1_ENABLED */
ctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST "xml", 3);
ctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST "xmlns", 5);
ctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36);
if ((ctxt->str_xml==NULL) || (ctxt->str_xmlns==NULL) ||
(ctxt->str_xml_ns == NULL)) {
xmlErrMemory(ctxt, NULL);
}
}
typedef struct _xmlDefAttrs xmlDefAttrs;
typedef xmlDefAttrs *xmlDefAttrsPtr;
struct _xmlDefAttrs {
int nbAttrs; /* number of defaulted attributes on that element */
int maxAttrs; /* the size of the array */
#if __STDC_VERSION__ >= 199901L
/* Using a C99 flexible array member avoids UBSan errors. */
const xmlChar *values[]; /* array of localname/prefix/values/external */
#else
const xmlChar *values[5];
#endif
};
/**
* xmlAttrNormalizeSpace:
* @src: the source string
* @dst: the target string
*
* Normalize the space in non CDATA attribute values:
* If the attribute type is not CDATA, then the XML processor MUST further
* process the normalized attribute value by discarding any leading and
* trailing space (#x20) characters, and by replacing sequences of space
* (#x20) characters by a single space (#x20) character.
* Note that the size of dst need to be at least src, and if one doesn't need
* to preserve dst (and it doesn't come from a dictionary or read-only) then
* passing src as dst is just fine.
*
* Returns a pointer to the normalized value (dst) or NULL if no conversion
* is needed.
*/
static xmlChar *
xmlAttrNormalizeSpace(const xmlChar *src, xmlChar *dst)
{
if ((src == NULL) || (dst == NULL))
return(NULL);
while (*src == 0x20) src++;
while (*src != 0) {
if (*src == 0x20) {
while (*src == 0x20) src++;
if (*src != 0)
*dst++ = 0x20;
} else {
*dst++ = *src++;
}
}
*dst = 0;
if (dst == src)
return(NULL);
return(dst);
}
/**
* xmlAttrNormalizeSpace2:
* @src: the source string
*
* Normalize the space in non CDATA attribute values, a slightly more complex
* front end to avoid allocation problems when running on attribute values
* coming from the input.
*
* Returns a pointer to the normalized value (dst) or NULL if no conversion
* is needed.
*/
static const xmlChar *
xmlAttrNormalizeSpace2(xmlParserCtxtPtr ctxt, xmlChar *src, int *len)
{
int i;
int remove_head = 0;
int need_realloc = 0;
const xmlChar *cur;
if ((ctxt == NULL) || (src == NULL) || (len == NULL))
return(NULL);
i = *len;
if (i <= 0)
return(NULL);
cur = src;
while (*cur == 0x20) {
cur++;
remove_head++;
}
while (*cur != 0) {
if (*cur == 0x20) {
cur++;
if ((*cur == 0x20) || (*cur == 0)) {
need_realloc = 1;
break;
}
} else
cur++;
}
if (need_realloc) {
xmlChar *ret;
ret = xmlStrndup(src + remove_head, i - remove_head + 1);
if (ret == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
xmlAttrNormalizeSpace(ret, ret);
*len = (int) strlen((const char *)ret);
return(ret);
} else if (remove_head) {
*len -= remove_head;
memmove(src, src + remove_head, 1 + *len);
return(src);
}
return(NULL);
}
/**
* xmlAddDefAttrs:
* @ctxt: an XML parser context
* @fullname: the element fullname
* @fullattr: the attribute fullname
* @value: the attribute value
*
* Add a defaulted attribute for an element
*/
static void
xmlAddDefAttrs(xmlParserCtxtPtr ctxt,
const xmlChar *fullname,
const xmlChar *fullattr,
const xmlChar *value) {
xmlDefAttrsPtr defaults;
int len;
const xmlChar *name;
const xmlChar *prefix;
/*
* Allows to detect attribute redefinitions
*/
if (ctxt->attsSpecial != NULL) {
if (xmlHashLookup2(ctxt->attsSpecial, fullname, fullattr) != NULL)
return;
}
if (ctxt->attsDefault == NULL) {
ctxt->attsDefault = xmlHashCreateDict(10, ctxt->dict);
if (ctxt->attsDefault == NULL)
goto mem_error;
}
/*
* split the element name into prefix:localname , the string found
* are within the DTD and then not associated to namespace names.
*/
name = xmlSplitQName3(fullname, &len);
if (name == NULL) {
name = xmlDictLookup(ctxt->dict, fullname, -1);
prefix = NULL;
} else {
name = xmlDictLookup(ctxt->dict, name, -1);
prefix = xmlDictLookup(ctxt->dict, fullname, len);
}
/*
* make sure there is some storage
*/
defaults = xmlHashLookup2(ctxt->attsDefault, name, prefix);
if (defaults == NULL) {
defaults = (xmlDefAttrsPtr) xmlMalloc(sizeof(xmlDefAttrs) +
(4 * 5) * sizeof(const xmlChar *));
if (defaults == NULL)
goto mem_error;
defaults->nbAttrs = 0;
defaults->maxAttrs = 4;
if (xmlHashUpdateEntry2(ctxt->attsDefault, name, prefix,
defaults, NULL) < 0) {
xmlFree(defaults);
goto mem_error;
}
} else if (defaults->nbAttrs >= defaults->maxAttrs) {
xmlDefAttrsPtr temp;
temp = (xmlDefAttrsPtr) xmlRealloc(defaults, sizeof(xmlDefAttrs) +
(2 * defaults->maxAttrs * 5) * sizeof(const xmlChar *));
if (temp == NULL)
goto mem_error;
defaults = temp;
defaults->maxAttrs *= 2;
if (xmlHashUpdateEntry2(ctxt->attsDefault, name, prefix,
defaults, NULL) < 0) {
xmlFree(defaults);
goto mem_error;
}
}
/*
* Split the element name into prefix:localname , the string found
* are within the DTD and hen not associated to namespace names.
*/
name = xmlSplitQName3(fullattr, &len);
if (name == NULL) {
name = xmlDictLookup(ctxt->dict, fullattr, -1);
prefix = NULL;
} else {
name = xmlDictLookup(ctxt->dict, name, -1);
prefix = xmlDictLookup(ctxt->dict, fullattr, len);
}
defaults->values[5 * defaults->nbAttrs] = name;
defaults->values[5 * defaults->nbAttrs + 1] = prefix;
/* intern the string and precompute the end */
len = xmlStrlen(value);
value = xmlDictLookup(ctxt->dict, value, len);
defaults->values[5 * defaults->nbAttrs + 2] = value;
defaults->values[5 * defaults->nbAttrs + 3] = value + len;
if (ctxt->external)
defaults->values[5 * defaults->nbAttrs + 4] = BAD_CAST "external";
else
defaults->values[5 * defaults->nbAttrs + 4] = NULL;
defaults->nbAttrs++;
return;
mem_error:
xmlErrMemory(ctxt, NULL);
return;
}
/**
* xmlAddSpecialAttr:
* @ctxt: an XML parser context
* @fullname: the element fullname
* @fullattr: the attribute fullname
* @type: the attribute type
*
* Register this attribute type
*/
static void
xmlAddSpecialAttr(xmlParserCtxtPtr ctxt,
const xmlChar *fullname,
const xmlChar *fullattr,
int type)
{
if (ctxt->attsSpecial == NULL) {
ctxt->attsSpecial = xmlHashCreateDict(10, ctxt->dict);
if (ctxt->attsSpecial == NULL)
goto mem_error;
}
if (xmlHashLookup2(ctxt->attsSpecial, fullname, fullattr) != NULL)
return;
xmlHashAddEntry2(ctxt->attsSpecial, fullname, fullattr,
(void *) (long) type);
return;
mem_error:
xmlErrMemory(ctxt, NULL);
return;
}
/**
* xmlCleanSpecialAttrCallback:
*
* Removes CDATA attributes from the special attribute table
*/
static void
xmlCleanSpecialAttrCallback(void *payload, void *data,
const xmlChar *fullname, const xmlChar *fullattr,
const xmlChar *unused ATTRIBUTE_UNUSED) {
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) data;
if (((long) payload) == XML_ATTRIBUTE_CDATA) {
xmlHashRemoveEntry2(ctxt->attsSpecial, fullname, fullattr, NULL);
}
}
/**
* xmlCleanSpecialAttr:
* @ctxt: an XML parser context
*
* Trim the list of attributes defined to remove all those of type
* CDATA as they are not special. This call should be done when finishing
* to parse the DTD and before starting to parse the document root.
*/
static void
xmlCleanSpecialAttr(xmlParserCtxtPtr ctxt)
{
if (ctxt->attsSpecial == NULL)
return;
xmlHashScanFull(ctxt->attsSpecial, xmlCleanSpecialAttrCallback, ctxt);
if (xmlHashSize(ctxt->attsSpecial) == 0) {
xmlHashFree(ctxt->attsSpecial, NULL);
ctxt->attsSpecial = NULL;
}
return;
}
/**
* xmlCheckLanguageID:
* @lang: pointer to the string value
*
* Checks that the value conforms to the LanguageID production:
*
* NOTE: this is somewhat deprecated, those productions were removed from
* the XML Second edition.
*
* [33] LanguageID ::= Langcode ('-' Subcode)*
* [34] Langcode ::= ISO639Code | IanaCode | UserCode
* [35] ISO639Code ::= ([a-z] | [A-Z]) ([a-z] | [A-Z])
* [36] IanaCode ::= ('i' | 'I') '-' ([a-z] | [A-Z])+
* [37] UserCode ::= ('x' | 'X') '-' ([a-z] | [A-Z])+
* [38] Subcode ::= ([a-z] | [A-Z])+
*
* The current REC reference the sucessors of RFC 1766, currently 5646
*
* http://www.rfc-editor.org/rfc/rfc5646.txt
* langtag = language
* ["-" script]
* ["-" region]
* *("-" variant)
* *("-" extension)
* ["-" privateuse]
* language = 2*3ALPHA ; shortest ISO 639 code
* ["-" extlang] ; sometimes followed by
* ; extended language subtags
* / 4ALPHA ; or reserved for future use
* / 5*8ALPHA ; or registered language subtag
*
* extlang = 3ALPHA ; selected ISO 639 codes
* *2("-" 3ALPHA) ; permanently reserved
*
* script = 4ALPHA ; ISO 15924 code
*
* region = 2ALPHA ; ISO 3166-1 code
* / 3DIGIT ; UN M.49 code
*
* variant = 5*8alphanum ; registered variants
* / (DIGIT 3alphanum)
*
* extension = singleton 1*("-" (2*8alphanum))
*
* ; Single alphanumerics
* ; "x" reserved for private use
* singleton = DIGIT ; 0 - 9
* / %x41-57 ; A - W
* / %x59-5A ; Y - Z
* / %x61-77 ; a - w
* / %x79-7A ; y - z
*
* it sounds right to still allow Irregular i-xxx IANA and user codes too
* The parser below doesn't try to cope with extension or privateuse
* that could be added but that's not interoperable anyway
*
* Returns 1 if correct 0 otherwise
**/
int
xmlCheckLanguageID(const xmlChar * lang)
{
const xmlChar *cur = lang, *nxt;
if (cur == NULL)
return (0);
if (((cur[0] == 'i') && (cur[1] == '-')) ||
((cur[0] == 'I') && (cur[1] == '-')) ||
((cur[0] == 'x') && (cur[1] == '-')) ||
((cur[0] == 'X') && (cur[1] == '-'))) {
/*
* Still allow IANA code and user code which were coming
* from the previous version of the XML-1.0 specification
* it's deprecated but we should not fail
*/
cur += 2;
while (((cur[0] >= 'A') && (cur[0] <= 'Z')) ||
((cur[0] >= 'a') && (cur[0] <= 'z')))
cur++;
return(cur[0] == 0);
}
nxt = cur;
while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) ||
((nxt[0] >= 'a') && (nxt[0] <= 'z')))
nxt++;
if (nxt - cur >= 4) {
/*
* Reserved
*/
if ((nxt - cur > 8) || (nxt[0] != 0))
return(0);
return(1);
}
if (nxt - cur < 2)
return(0);
/* we got an ISO 639 code */
if (nxt[0] == 0)
return(1);
if (nxt[0] != '-')
return(0);
nxt++;
cur = nxt;
/* now we can have extlang or script or region or variant */
if ((nxt[0] >= '0') && (nxt[0] <= '9'))
goto region_m49;
while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) ||
((nxt[0] >= 'a') && (nxt[0] <= 'z')))
nxt++;
if (nxt - cur == 4)
goto script;
if (nxt - cur == 2)
goto region;
if ((nxt - cur >= 5) && (nxt - cur <= 8))
goto variant;
if (nxt - cur != 3)
return(0);
/* we parsed an extlang */
if (nxt[0] == 0)
return(1);
if (nxt[0] != '-')
return(0);
nxt++;
cur = nxt;
/* now we can have script or region or variant */
if ((nxt[0] >= '0') && (nxt[0] <= '9'))
goto region_m49;
while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) ||
((nxt[0] >= 'a') && (nxt[0] <= 'z')))
nxt++;
if (nxt - cur == 2)
goto region;
if ((nxt - cur >= 5) && (nxt - cur <= 8))
goto variant;
if (nxt - cur != 4)
return(0);
/* we parsed a script */
script:
if (nxt[0] == 0)
return(1);
if (nxt[0] != '-')
return(0);
nxt++;
cur = nxt;
/* now we can have region or variant */
if ((nxt[0] >= '0') && (nxt[0] <= '9'))
goto region_m49;
while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) ||
((nxt[0] >= 'a') && (nxt[0] <= 'z')))
nxt++;
if ((nxt - cur >= 5) && (nxt - cur <= 8))
goto variant;
if (nxt - cur != 2)
return(0);
/* we parsed a region */
region:
if (nxt[0] == 0)
return(1);
if (nxt[0] != '-')
return(0);
nxt++;
cur = nxt;
/* now we can just have a variant */
while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) ||
((nxt[0] >= 'a') && (nxt[0] <= 'z')))
nxt++;
if ((nxt - cur < 5) || (nxt - cur > 8))
return(0);
/* we parsed a variant */
variant:
if (nxt[0] == 0)
return(1);
if (nxt[0] != '-')
return(0);
/* extensions and private use subtags not checked */
return (1);
region_m49:
if (((nxt[1] >= '0') && (nxt[1] <= '9')) &&
((nxt[2] >= '0') && (nxt[2] <= '9'))) {
nxt += 3;
goto region;
}
return(0);
}
/************************************************************************
* *
* Parser stacks related functions and macros *
* *
************************************************************************/
static xmlEntityPtr xmlParseStringEntityRef(xmlParserCtxtPtr ctxt,
const xmlChar ** str);
#ifdef SAX2
/**
* nsPush:
* @ctxt: an XML parser context
* @prefix: the namespace prefix or NULL
* @URL: the namespace name
*
* Pushes a new parser namespace on top of the ns stack
*
* Returns -1 in case of error, -2 if the namespace should be discarded
* and the index in the stack otherwise.
*/
static int
nsPush(xmlParserCtxtPtr ctxt, const xmlChar *prefix, const xmlChar *URL)
{
if (ctxt->options & XML_PARSE_NSCLEAN) {
int i;
for (i = ctxt->nsNr - 2;i >= 0;i -= 2) {
if (ctxt->nsTab[i] == prefix) {
/* in scope */
if (ctxt->nsTab[i + 1] == URL)
return(-2);
/* out of scope keep it */
break;
}
}
}
if ((ctxt->nsMax == 0) || (ctxt->nsTab == NULL)) {
ctxt->nsMax = 10;
ctxt->nsNr = 0;
ctxt->nsTab = (const xmlChar **)
xmlMalloc(ctxt->nsMax * sizeof(xmlChar *));
if (ctxt->nsTab == NULL) {
xmlErrMemory(ctxt, NULL);
ctxt->nsMax = 0;
return (-1);
}
} else if (ctxt->nsNr >= ctxt->nsMax) {
const xmlChar ** tmp;
ctxt->nsMax *= 2;
tmp = (const xmlChar **) xmlRealloc((char *) ctxt->nsTab,
ctxt->nsMax * sizeof(ctxt->nsTab[0]));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
ctxt->nsMax /= 2;
return (-1);
}
ctxt->nsTab = tmp;
}
ctxt->nsTab[ctxt->nsNr++] = prefix;
ctxt->nsTab[ctxt->nsNr++] = URL;
return (ctxt->nsNr);
}
/**
* nsPop:
* @ctxt: an XML parser context
* @nr: the number to pop
*
* Pops the top @nr parser prefix/namespace from the ns stack
*
* Returns the number of namespaces removed
*/
static int
nsPop(xmlParserCtxtPtr ctxt, int nr)
{
int i;
if (ctxt->nsTab == NULL) return(0);
if (ctxt->nsNr < nr) {
xmlGenericError(xmlGenericErrorContext, "Pbm popping %d NS\n", nr);
nr = ctxt->nsNr;
}
if (ctxt->nsNr <= 0)
return (0);
for (i = 0;i < nr;i++) {
ctxt->nsNr--;
ctxt->nsTab[ctxt->nsNr] = NULL;
}
return(nr);
}
#endif
static int
xmlCtxtGrowAttrs(xmlParserCtxtPtr ctxt, int nr) {
const xmlChar **atts;
int *attallocs;
int maxatts;
if (ctxt->atts == NULL) {
maxatts = 55; /* allow for 10 attrs by default */
atts = (const xmlChar **)
xmlMalloc(maxatts * sizeof(xmlChar *));
if (atts == NULL) goto mem_error;
ctxt->atts = atts;
attallocs = (int *) xmlMalloc((maxatts / 5) * sizeof(int));
if (attallocs == NULL) goto mem_error;
ctxt->attallocs = attallocs;
ctxt->maxatts = maxatts;
} else if (nr + 5 > ctxt->maxatts) {
maxatts = (nr + 5) * 2;
atts = (const xmlChar **) xmlRealloc((void *) ctxt->atts,
maxatts * sizeof(const xmlChar *));
if (atts == NULL) goto mem_error;
ctxt->atts = atts;
attallocs = (int *) xmlRealloc((void *) ctxt->attallocs,
(maxatts / 5) * sizeof(int));
if (attallocs == NULL) goto mem_error;
ctxt->attallocs = attallocs;
ctxt->maxatts = maxatts;
}
return(ctxt->maxatts);
mem_error:
xmlErrMemory(ctxt, NULL);
return(-1);
}
/**
* inputPush:
* @ctxt: an XML parser context
* @value: the parser input
*
* Pushes a new parser input on top of the input stack
*
* Returns -1 in case of error, the index in the stack otherwise
*/
int
inputPush(xmlParserCtxtPtr ctxt, xmlParserInputPtr value)
{
if ((ctxt == NULL) || (value == NULL))
return(-1);
if (ctxt->inputNr >= ctxt->inputMax) {
ctxt->inputMax *= 2;
ctxt->inputTab =
(xmlParserInputPtr *) xmlRealloc(ctxt->inputTab,
ctxt->inputMax *
sizeof(ctxt->inputTab[0]));
if (ctxt->inputTab == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFreeInputStream(value);
ctxt->inputMax /= 2;
value = NULL;
return (-1);
}
}
ctxt->inputTab[ctxt->inputNr] = value;
ctxt->input = value;
return (ctxt->inputNr++);
}
/**
* inputPop:
* @ctxt: an XML parser context
*
* Pops the top parser input from the input stack
*
* Returns the input just removed
*/
xmlParserInputPtr
inputPop(xmlParserCtxtPtr ctxt)
{
xmlParserInputPtr ret;
if (ctxt == NULL)
return(NULL);
if (ctxt->inputNr <= 0)
return (NULL);
ctxt->inputNr--;
if (ctxt->inputNr > 0)
ctxt->input = ctxt->inputTab[ctxt->inputNr - 1];
else
ctxt->input = NULL;
ret = ctxt->inputTab[ctxt->inputNr];
ctxt->inputTab[ctxt->inputNr] = NULL;
return (ret);
}
/**
* nodePush:
* @ctxt: an XML parser context
* @value: the element node
*
* Pushes a new element node on top of the node stack
*
* Returns -1 in case of error, the index in the stack otherwise
*/
int
nodePush(xmlParserCtxtPtr ctxt, xmlNodePtr value)
{
if (ctxt == NULL) return(0);
if (ctxt->nodeNr >= ctxt->nodeMax) {
xmlNodePtr *tmp;
tmp = (xmlNodePtr *) xmlRealloc(ctxt->nodeTab,
ctxt->nodeMax * 2 *
sizeof(ctxt->nodeTab[0]));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
return (-1);
}
ctxt->nodeTab = tmp;
ctxt->nodeMax *= 2;
}
if ((((unsigned int) ctxt->nodeNr) > xmlParserMaxDepth) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INTERNAL_ERROR,
"Excessive depth in document: %d use XML_PARSE_HUGE option\n",
xmlParserMaxDepth);
xmlHaltParser(ctxt);
return(-1);
}
ctxt->nodeTab[ctxt->nodeNr] = value;
ctxt->node = value;
return (ctxt->nodeNr++);
}
/**
* nodePop:
* @ctxt: an XML parser context
*
* Pops the top element node from the node stack
*
* Returns the node just removed
*/
xmlNodePtr
nodePop(xmlParserCtxtPtr ctxt)
{
xmlNodePtr ret;
if (ctxt == NULL) return(NULL);
if (ctxt->nodeNr <= 0)
return (NULL);
ctxt->nodeNr--;
if (ctxt->nodeNr > 0)
ctxt->node = ctxt->nodeTab[ctxt->nodeNr - 1];
else
ctxt->node = NULL;
ret = ctxt->nodeTab[ctxt->nodeNr];
ctxt->nodeTab[ctxt->nodeNr] = NULL;
return (ret);
}
#ifdef LIBXML_PUSH_ENABLED
/**
* nameNsPush:
* @ctxt: an XML parser context
* @value: the element name
* @prefix: the element prefix
* @URI: the element namespace name
*
* Pushes a new element name/prefix/URL on top of the name stack
*
* Returns -1 in case of error, the index in the stack otherwise
*/
static int
nameNsPush(xmlParserCtxtPtr ctxt, const xmlChar * value,
const xmlChar *prefix, const xmlChar *URI, int nsNr)
{
if (ctxt->nameNr >= ctxt->nameMax) {
const xmlChar * *tmp;
void **tmp2;
ctxt->nameMax *= 2;
tmp = (const xmlChar * *) xmlRealloc((xmlChar * *)ctxt->nameTab,
ctxt->nameMax *
sizeof(ctxt->nameTab[0]));
if (tmp == NULL) {
ctxt->nameMax /= 2;
goto mem_error;
}
ctxt->nameTab = tmp;
tmp2 = (void **) xmlRealloc((void * *)ctxt->pushTab,
ctxt->nameMax * 3 *
sizeof(ctxt->pushTab[0]));
if (tmp2 == NULL) {
ctxt->nameMax /= 2;
goto mem_error;
}
ctxt->pushTab = tmp2;
}
ctxt->nameTab[ctxt->nameNr] = value;
ctxt->name = value;
ctxt->pushTab[ctxt->nameNr * 3] = (void *) prefix;
ctxt->pushTab[ctxt->nameNr * 3 + 1] = (void *) URI;
ctxt->pushTab[ctxt->nameNr * 3 + 2] = (void *) (long) nsNr;
return (ctxt->nameNr++);
mem_error:
xmlErrMemory(ctxt, NULL);
return (-1);
}
/**
* nameNsPop:
* @ctxt: an XML parser context
*
* Pops the top element/prefix/URI name from the name stack
*
* Returns the name just removed
*/
static const xmlChar *
nameNsPop(xmlParserCtxtPtr ctxt)
{
const xmlChar *ret;
if (ctxt->nameNr <= 0)
return (NULL);
ctxt->nameNr--;
if (ctxt->nameNr > 0)
ctxt->name = ctxt->nameTab[ctxt->nameNr - 1];
else
ctxt->name = NULL;
ret = ctxt->nameTab[ctxt->nameNr];
ctxt->nameTab[ctxt->nameNr] = NULL;
return (ret);
}
#endif /* LIBXML_PUSH_ENABLED */
/**
* namePush:
* @ctxt: an XML parser context
* @value: the element name
*
* Pushes a new element name on top of the name stack
*
* Returns -1 in case of error, the index in the stack otherwise
*/
int
namePush(xmlParserCtxtPtr ctxt, const xmlChar * value)
{
if (ctxt == NULL) return (-1);
if (ctxt->nameNr >= ctxt->nameMax) {
const xmlChar * *tmp;
tmp = (const xmlChar * *) xmlRealloc((xmlChar * *)ctxt->nameTab,
ctxt->nameMax * 2 *
sizeof(ctxt->nameTab[0]));
if (tmp == NULL) {
goto mem_error;
}
ctxt->nameTab = tmp;
ctxt->nameMax *= 2;
}
ctxt->nameTab[ctxt->nameNr] = value;
ctxt->name = value;
return (ctxt->nameNr++);
mem_error:
xmlErrMemory(ctxt, NULL);
return (-1);
}
/**
* namePop:
* @ctxt: an XML parser context
*
* Pops the top element name from the name stack
*
* Returns the name just removed
*/
const xmlChar *
namePop(xmlParserCtxtPtr ctxt)
{
const xmlChar *ret;
if ((ctxt == NULL) || (ctxt->nameNr <= 0))
return (NULL);
ctxt->nameNr--;
if (ctxt->nameNr > 0)
ctxt->name = ctxt->nameTab[ctxt->nameNr - 1];
else
ctxt->name = NULL;
ret = ctxt->nameTab[ctxt->nameNr];
ctxt->nameTab[ctxt->nameNr] = NULL;
return (ret);
}
static int spacePush(xmlParserCtxtPtr ctxt, int val) {
if (ctxt->spaceNr >= ctxt->spaceMax) {
int *tmp;
ctxt->spaceMax *= 2;
tmp = (int *) xmlRealloc(ctxt->spaceTab,
ctxt->spaceMax * sizeof(ctxt->spaceTab[0]));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
ctxt->spaceMax /=2;
return(-1);
}
ctxt->spaceTab = tmp;
}
ctxt->spaceTab[ctxt->spaceNr] = val;
ctxt->space = &ctxt->spaceTab[ctxt->spaceNr];
return(ctxt->spaceNr++);
}
static int spacePop(xmlParserCtxtPtr ctxt) {
int ret;
if (ctxt->spaceNr <= 0) return(0);
ctxt->spaceNr--;
if (ctxt->spaceNr > 0)
ctxt->space = &ctxt->spaceTab[ctxt->spaceNr - 1];
else
ctxt->space = &ctxt->spaceTab[0];
ret = ctxt->spaceTab[ctxt->spaceNr];
ctxt->spaceTab[ctxt->spaceNr] = -1;
return(ret);
}
/*
* Macros for accessing the content. Those should be used only by the parser,
* and not exported.
*
* Dirty macros, i.e. one often need to make assumption on the context to
* use them
*
* CUR_PTR return the current pointer to the xmlChar to be parsed.
* To be used with extreme caution since operations consuming
* characters may move the input buffer to a different location !
* CUR returns the current xmlChar value, i.e. a 8 bit value if compiled
* This should be used internally by the parser
* only to compare to ASCII values otherwise it would break when
* running with UTF-8 encoding.
* RAW same as CUR but in the input buffer, bypass any token
* extraction that may have been done
* NXT(n) returns the n'th next xmlChar. Same as CUR is should be used only
* to compare on ASCII based substring.
* SKIP(n) Skip n xmlChar, and must also be used only to skip ASCII defined
* strings without newlines within the parser.
* NEXT1(l) Skip 1 xmlChar, and must also be used only to skip 1 non-newline ASCII
* defined char within the parser.
* Clean macros, not dependent of an ASCII context, expect UTF-8 encoding
*
* NEXT Skip to the next character, this does the proper decoding
* in UTF-8 mode. It also pop-up unfinished entities on the fly.
* NEXTL(l) Skip the current unicode character of l xmlChars long.
* CUR_CHAR(l) returns the current unicode character (int), set l
* to the number of xmlChars used for the encoding [0-5].
* CUR_SCHAR same but operate on a string instead of the context
* COPY_BUF copy the current unicode char to the target buffer, increment
* the index
* GROW, SHRINK handling of input buffers
*/
#define RAW (*ctxt->input->cur)
#define CUR (*ctxt->input->cur)
#define NXT(val) ctxt->input->cur[(val)]
#define CUR_PTR ctxt->input->cur
#define BASE_PTR ctxt->input->base
#define CMP4( s, c1, c2, c3, c4 ) \
( ((unsigned char *) s)[ 0 ] == c1 && ((unsigned char *) s)[ 1 ] == c2 && \
((unsigned char *) s)[ 2 ] == c3 && ((unsigned char *) s)[ 3 ] == c4 )
#define CMP5( s, c1, c2, c3, c4, c5 ) \
( CMP4( s, c1, c2, c3, c4 ) && ((unsigned char *) s)[ 4 ] == c5 )
#define CMP6( s, c1, c2, c3, c4, c5, c6 ) \
( CMP5( s, c1, c2, c3, c4, c5 ) && ((unsigned char *) s)[ 5 ] == c6 )
#define CMP7( s, c1, c2, c3, c4, c5, c6, c7 ) \
( CMP6( s, c1, c2, c3, c4, c5, c6 ) && ((unsigned char *) s)[ 6 ] == c7 )
#define CMP8( s, c1, c2, c3, c4, c5, c6, c7, c8 ) \
( CMP7( s, c1, c2, c3, c4, c5, c6, c7 ) && ((unsigned char *) s)[ 7 ] == c8 )
#define CMP9( s, c1, c2, c3, c4, c5, c6, c7, c8, c9 ) \
( CMP8( s, c1, c2, c3, c4, c5, c6, c7, c8 ) && \
((unsigned char *) s)[ 8 ] == c9 )
#define CMP10( s, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10 ) \
( CMP9( s, c1, c2, c3, c4, c5, c6, c7, c8, c9 ) && \
((unsigned char *) s)[ 9 ] == c10 )
#define SKIP(val) do { \
ctxt->nbChars += (val),ctxt->input->cur += (val),ctxt->input->col+=(val); \
if (*ctxt->input->cur == '%') xmlParserHandlePEReference(ctxt); \
if ((*ctxt->input->cur == 0) && \
(xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0)) \
xmlPopInput(ctxt); \
} while (0)
#define SKIPL(val) do { \
int skipl; \
for(skipl=0; skipl<val; skipl++) { \
if (*(ctxt->input->cur) == '\n') { \
ctxt->input->line++; ctxt->input->col = 1; \
} else ctxt->input->col++; \
ctxt->nbChars++; \
ctxt->input->cur++; \
} \
if (*ctxt->input->cur == '%') xmlParserHandlePEReference(ctxt); \
if ((*ctxt->input->cur == 0) && \
(xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0)) \
xmlPopInput(ctxt); \
} while (0)
#define SHRINK if ((ctxt->progressive == 0) && \
(ctxt->input->cur - ctxt->input->base > 2 * INPUT_CHUNK) && \
(ctxt->input->end - ctxt->input->cur < 2 * INPUT_CHUNK)) \
xmlSHRINK (ctxt);
static void xmlSHRINK (xmlParserCtxtPtr ctxt) {
xmlParserInputShrink(ctxt->input);
if ((*ctxt->input->cur == 0) &&
(xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0))
xmlPopInput(ctxt);
}
#define GROW if ((ctxt->progressive == 0) && \
(ctxt->input->end - ctxt->input->cur < INPUT_CHUNK)) \
xmlGROW (ctxt);
static void xmlGROW (xmlParserCtxtPtr ctxt) {
unsigned long curEnd = ctxt->input->end - ctxt->input->cur;
unsigned long curBase = ctxt->input->cur - ctxt->input->base;
if (((curEnd > (unsigned long) XML_MAX_LOOKUP_LIMIT) ||
(curBase > (unsigned long) XML_MAX_LOOKUP_LIMIT)) &&
((ctxt->input->buf) && (ctxt->input->buf->readcallback != (xmlInputReadCallback) xmlNop)) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "Huge input lookup");
xmlHaltParser(ctxt);
return;
}
xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
if ((ctxt->input->cur > ctxt->input->end) ||
(ctxt->input->cur < ctxt->input->base)) {
xmlHaltParser(ctxt);
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "cur index out of bound");
return;
}
if ((ctxt->input->cur != NULL) && (*ctxt->input->cur == 0) &&
(xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0))
xmlPopInput(ctxt);
}
#define SKIP_BLANKS xmlSkipBlankChars(ctxt)
#define NEXT xmlNextChar(ctxt)
#define NEXT1 { \
ctxt->input->col++; \
ctxt->input->cur++; \
ctxt->nbChars++; \
if (*ctxt->input->cur == 0) \
xmlParserInputGrow(ctxt->input, INPUT_CHUNK); \
}
#define NEXTL(l) do { \
if (*(ctxt->input->cur) == '\n') { \
ctxt->input->line++; ctxt->input->col = 1; \
} else ctxt->input->col++; \
ctxt->input->cur += l; \
} while (0)
#define CUR_CHAR(l) xmlCurrentChar(ctxt, &l)
#define CUR_SCHAR(s, l) xmlStringCurrentChar(ctxt, s, &l)
#define COPY_BUF(l,b,i,v) \
if (l == 1) b[i++] = (xmlChar) v; \
else i += xmlCopyCharMultiByte(&b[i],v)
/**
* xmlSkipBlankChars:
* @ctxt: the XML parser context
*
* skip all blanks character found at that point in the input streams.
* It pops up finished entities in the process if allowable at that point.
*
* Returns the number of space chars skipped
*/
int
xmlSkipBlankChars(xmlParserCtxtPtr ctxt) {
int res = 0;
/*
* It's Okay to use CUR/NEXT here since all the blanks are on
* the ASCII range.
*/
if ((ctxt->inputNr == 1) && (ctxt->instate != XML_PARSER_DTD)) {
const xmlChar *cur;
/*
* if we are in the document content, go really fast
*/
cur = ctxt->input->cur;
while (IS_BLANK_CH(*cur)) {
if (*cur == '\n') {
ctxt->input->line++; ctxt->input->col = 1;
} else {
ctxt->input->col++;
}
cur++;
res++;
if (*cur == 0) {
ctxt->input->cur = cur;
xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
cur = ctxt->input->cur;
}
}
ctxt->input->cur = cur;
} else {
int cur;
do {
cur = CUR;
while ((IS_BLANK_CH(cur) && /* CHECKED tstblanks.xml */
(ctxt->instate != XML_PARSER_EOF))) {
NEXT;
cur = CUR;
res++;
}
while ((cur == 0) && (ctxt->inputNr > 1) &&
(ctxt->instate != XML_PARSER_COMMENT)) {
xmlPopInput(ctxt);
cur = CUR;
}
/*
* Need to handle support of entities branching here
*/
if (*ctxt->input->cur == '%') xmlParserHandlePEReference(ctxt);
} while ((IS_BLANK(cur)) && /* CHECKED tstblanks.xml */
(ctxt->instate != XML_PARSER_EOF));
}
return(res);
}
/************************************************************************
* *
* Commodity functions to handle entities *
* *
************************************************************************/
/**
* xmlPopInput:
* @ctxt: an XML parser context
*
* xmlPopInput: the current input pointed by ctxt->input came to an end
* pop it and return the next char.
*
* Returns the current xmlChar in the parser context
*/
xmlChar
xmlPopInput(xmlParserCtxtPtr ctxt) {
if ((ctxt == NULL) || (ctxt->inputNr <= 1)) return(0);
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"Popping input %d\n", ctxt->inputNr);
xmlFreeInputStream(inputPop(ctxt));
if ((*ctxt->input->cur == 0) &&
(xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0))
return(xmlPopInput(ctxt));
return(CUR);
}
/**
* xmlPushInput:
* @ctxt: an XML parser context
* @input: an XML parser input fragment (entity, XML fragment ...).
*
* xmlPushInput: switch to a new input stream which is stacked on top
* of the previous one(s).
* Returns -1 in case of error or the index in the input stack
*/
int
xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) {
int ret;
if (input == NULL) return(-1);
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur);
}
ret = inputPush(ctxt, input);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
GROW;
return(ret);
}
/**
* xmlParseCharRef:
* @ctxt: an XML parser context
*
* parse Reference declarations
*
* [66] CharRef ::= '&#' [0-9]+ ';' |
* '&#x' [0-9a-fA-F]+ ';'
*
* [ WFC: Legal Character ]
* Characters referred to using character references must match the
* production for Char.
*
* Returns the value parsed (as an int), 0 in case of error
*/
int
xmlParseCharRef(xmlParserCtxtPtr ctxt) {
unsigned int val = 0;
int count = 0;
unsigned int outofrange = 0;
/*
* Using RAW/CUR/NEXT is okay since we are working on ASCII range here
*/
if ((RAW == '&') && (NXT(1) == '#') &&
(NXT(2) == 'x')) {
SKIP(3);
GROW;
while (RAW != ';') { /* loop blocked by count */
if (count++ > 20) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(0);
}
if ((RAW >= '0') && (RAW <= '9'))
val = val * 16 + (CUR - '0');
else if ((RAW >= 'a') && (RAW <= 'f') && (count < 20))
val = val * 16 + (CUR - 'a') + 10;
else if ((RAW >= 'A') && (RAW <= 'F') && (count < 20))
val = val * 16 + (CUR - 'A') + 10;
else {
xmlFatalErr(ctxt, XML_ERR_INVALID_HEX_CHARREF, NULL);
val = 0;
break;
}
if (val > 0x10FFFF)
outofrange = val;
NEXT;
count++;
}
if (RAW == ';') {
/* on purpose to avoid reentrancy problems with NEXT and SKIP */
ctxt->input->col++;
ctxt->nbChars ++;
ctxt->input->cur++;
}
} else if ((RAW == '&') && (NXT(1) == '#')) {
SKIP(2);
GROW;
while (RAW != ';') { /* loop blocked by count */
if (count++ > 20) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(0);
}
if ((RAW >= '0') && (RAW <= '9'))
val = val * 10 + (CUR - '0');
else {
xmlFatalErr(ctxt, XML_ERR_INVALID_DEC_CHARREF, NULL);
val = 0;
break;
}
if (val > 0x10FFFF)
outofrange = val;
NEXT;
count++;
}
if (RAW == ';') {
/* on purpose to avoid reentrancy problems with NEXT and SKIP */
ctxt->input->col++;
ctxt->nbChars ++;
ctxt->input->cur++;
}
} else {
xmlFatalErr(ctxt, XML_ERR_INVALID_CHARREF, NULL);
}
/*
* [ WFC: Legal Character ]
* Characters referred to using character references must match the
* production for Char.
*/
if ((IS_CHAR(val) && (outofrange == 0))) {
return(val);
} else {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlParseCharRef: invalid xmlChar value %d\n",
val);
}
return(0);
}
/**
* xmlParseStringCharRef:
* @ctxt: an XML parser context
* @str: a pointer to an index in the string
*
* parse Reference declarations, variant parsing from a string rather
* than an an input flow.
*
* [66] CharRef ::= '&#' [0-9]+ ';' |
* '&#x' [0-9a-fA-F]+ ';'
*
* [ WFC: Legal Character ]
* Characters referred to using character references must match the
* production for Char.
*
* Returns the value parsed (as an int), 0 in case of error, str will be
* updated to the current value of the index
*/
static int
xmlParseStringCharRef(xmlParserCtxtPtr ctxt, const xmlChar **str) {
const xmlChar *ptr;
xmlChar cur;
unsigned int val = 0;
unsigned int outofrange = 0;
if ((str == NULL) || (*str == NULL)) return(0);
ptr = *str;
cur = *ptr;
if ((cur == '&') && (ptr[1] == '#') && (ptr[2] == 'x')) {
ptr += 3;
cur = *ptr;
while (cur != ';') { /* Non input consuming loop */
if ((cur >= '0') && (cur <= '9'))
val = val * 16 + (cur - '0');
else if ((cur >= 'a') && (cur <= 'f'))
val = val * 16 + (cur - 'a') + 10;
else if ((cur >= 'A') && (cur <= 'F'))
val = val * 16 + (cur - 'A') + 10;
else {
xmlFatalErr(ctxt, XML_ERR_INVALID_HEX_CHARREF, NULL);
val = 0;
break;
}
if (val > 0x10FFFF)
outofrange = val;
ptr++;
cur = *ptr;
}
if (cur == ';')
ptr++;
} else if ((cur == '&') && (ptr[1] == '#')){
ptr += 2;
cur = *ptr;
while (cur != ';') { /* Non input consuming loops */
if ((cur >= '0') && (cur <= '9'))
val = val * 10 + (cur - '0');
else {
xmlFatalErr(ctxt, XML_ERR_INVALID_DEC_CHARREF, NULL);
val = 0;
break;
}
if (val > 0x10FFFF)
outofrange = val;
ptr++;
cur = *ptr;
}
if (cur == ';')
ptr++;
} else {
xmlFatalErr(ctxt, XML_ERR_INVALID_CHARREF, NULL);
return(0);
}
*str = ptr;
/*
* [ WFC: Legal Character ]
* Characters referred to using character references must match the
* production for Char.
*/
if ((IS_CHAR(val) && (outofrange == 0))) {
return(val);
} else {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlParseStringCharRef: invalid xmlChar value %d\n",
val);
}
return(0);
}
/**
* xmlNewBlanksWrapperInputStream:
* @ctxt: an XML parser context
* @entity: an Entity pointer
*
* Create a new input stream for wrapping
* blanks around a PEReference
*
* Returns the new input stream or NULL
*/
static void deallocblankswrapper (xmlChar *str) {xmlFree(str);}
static xmlParserInputPtr
xmlNewBlanksWrapperInputStream(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) {
xmlParserInputPtr input;
xmlChar *buffer;
size_t length;
if (entity == NULL) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlNewBlanksWrapperInputStream entity\n");
return(NULL);
}
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"new blanks wrapper for entity: %s\n", entity->name);
input = xmlNewInputStream(ctxt);
if (input == NULL) {
return(NULL);
}
length = xmlStrlen(entity->name) + 5;
buffer = xmlMallocAtomic(length);
if (buffer == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(input);
return(NULL);
}
buffer [0] = ' ';
buffer [1] = '%';
buffer [length-3] = ';';
buffer [length-2] = ' ';
buffer [length-1] = 0;
memcpy(buffer + 2, entity->name, length - 5);
input->free = deallocblankswrapper;
input->base = buffer;
input->cur = buffer;
input->length = length;
input->end = &buffer[length];
return(input);
}
/**
* xmlParserHandlePEReference:
* @ctxt: the parser context
*
* [69] PEReference ::= '%' Name ';'
*
* [ WFC: No Recursion ]
* A parsed entity must not contain a recursive
* reference to itself, either directly or indirectly.
*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an internal DTD
* subset which contains no parameter entity references, or a document
* with "standalone='yes'", ... ... The declaration of a parameter
* entity must precede any reference to it...
*
* [ VC: Entity Declared ]
* In a document with an external subset or external parameter entities
* with "standalone='no'", ... ... The declaration of a parameter entity
* must precede any reference to it...
*
* [ WFC: In DTD ]
* Parameter-entity references may only appear in the DTD.
* NOTE: misleading but this is handled.
*
* A PEReference may have been detected in the current input stream
* the handling is done accordingly to
* http://www.w3.org/TR/REC-xml#entproc
* i.e.
* - Included in literal in entity values
* - Included as Parameter Entity reference within DTDs
*/
void
xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%') return;
switch(ctxt->instate) {
case XML_PARSER_CDATA_SECTION:
return;
case XML_PARSER_COMMENT:
return;
case XML_PARSER_START_TAG:
return;
case XML_PARSER_END_TAG:
return;
case XML_PARSER_EOF:
xmlFatalErr(ctxt, XML_ERR_PEREF_AT_EOF, NULL);
return;
case XML_PARSER_PROLOG:
case XML_PARSER_START:
case XML_PARSER_MISC:
xmlFatalErr(ctxt, XML_ERR_PEREF_IN_PROLOG, NULL);
return;
case XML_PARSER_ENTITY_DECL:
case XML_PARSER_CONTENT:
case XML_PARSER_ATTRIBUTE_VALUE:
case XML_PARSER_PI:
case XML_PARSER_SYSTEM_LITERAL:
case XML_PARSER_PUBLIC_LITERAL:
/* we just ignore it there */
return;
case XML_PARSER_EPILOG:
xmlFatalErr(ctxt, XML_ERR_PEREF_IN_EPILOG, NULL);
return;
case XML_PARSER_ENTITY_VALUE:
/*
* NOTE: in the case of entity values, we don't do the
* substitution here since we need the literal
* entity value to be able to save the internal
* subset of the document.
* This will be handled by xmlStringDecodeEntities
*/
return;
case XML_PARSER_DTD:
/*
* [WFC: Well-Formedness Constraint: PEs in Internal Subset]
* In the internal DTD subset, parameter-entity references
* can occur only where markup declarations can occur, not
* within markup declarations.
* In that case this is handled in xmlParseMarkupDecl
*/
if ((ctxt->external == 0) && (ctxt->inputNr == 1))
return;
if (IS_BLANK_CH(NXT(1)) || NXT(1) == 0)
return;
break;
case XML_PARSER_IGNORE:
return;
}
NEXT;
name = xmlParseName(ctxt);
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"PEReference: %s\n", name);
if (name == NULL) {
xmlFatalErr(ctxt, XML_ERR_PEREF_NO_NAME, NULL);
} else {
if (RAW == ';') {
NEXT;
if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (ctxt->instate == XML_PARSER_EOF)
return;
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n", name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) {
xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
} else
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
xmlParserEntityCheck(ctxt, 0, NULL, 0);
} else if (ctxt->input->free != deallocblankswrapper) {
input = xmlNewBlanksWrapperInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
} else {
if ((entity->etype == XML_INTERNAL_PARAMETER_ENTITY) ||
(entity->etype == XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlChar start[4];
xmlCharEncoding enc;
/*
* Note: external parameter entities will not be loaded, it
* is not required for a non-validating parser, unless the
* option of validating, or substituting entities were
* given. Doing so is far more secure as the parser will
* only process data coming from the document entity by
* default.
*/
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
((ctxt->options & XML_PARSE_NOENT) == 0) &&
((ctxt->options & XML_PARSE_DTDVALID) == 0) &&
((ctxt->options & XML_PARSE_DTDLOAD) == 0) &&
((ctxt->options & XML_PARSE_DTDATTR) == 0) &&
(ctxt->replaceEntities == 0) &&
(ctxt->validate == 0))
return;
/*
* handle the extra spaces added before and after
* c.f. http://www.w3.org/TR/REC-xml#as-PE
* this is done independently.
*/
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
* Note that, since we may have some non-UTF8
* encoding (like UTF16, bug 135229), the 'length'
* is not known, but we can calculate based upon
* the amount of data in the buffer.
*/
GROW
if (ctxt->instate == XML_PARSER_EOF)
return;
if ((ctxt->input->end - ctxt->input->cur)>=4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l' )) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
}
} else {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
"PEReference: %s is not a parameter entity\n",
name);
}
}
} else {
xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL);
}
}
}
/*
* Macro used to grow the current buffer.
* buffer##_size is expected to be a size_t
* mem_error: is expected to handle memory allocation failures
*/
#define growBuffer(buffer, n) { \
xmlChar *tmp; \
size_t new_size = buffer##_size * 2 + n; \
if (new_size < buffer##_size) goto mem_error; \
tmp = (xmlChar *) xmlRealloc(buffer, new_size); \
if (tmp == NULL) goto mem_error; \
buffer = tmp; \
buffer##_size = new_size; \
}
/**
* xmlStringLenDecodeEntities:
* @ctxt: the parser context
* @str: the input string
* @len: the string length
* @what: combination of XML_SUBSTITUTE_REF and XML_SUBSTITUTE_PEREF
* @end: an end marker xmlChar, 0 if none
* @end2: an end marker xmlChar, 0 if none
* @end3: an end marker xmlChar, 0 if none
*
* Takes a entity string content and process to do the adequate substitutions.
*
* [67] Reference ::= EntityRef | CharRef
*
* [69] PEReference ::= '%' Name ';'
*
* Returns A newly allocated string with the substitution done. The caller
* must deallocate it !
*/
xmlChar *
xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len,
int what, xmlChar end, xmlChar end2, xmlChar end3) {
xmlChar *buffer = NULL;
size_t buffer_size = 0;
size_t nbchars = 0;
xmlChar *current = NULL;
xmlChar *rep = NULL;
const xmlChar *last;
xmlEntityPtr ent;
int c,l;
if ((ctxt == NULL) || (str == NULL) || (len < 0))
return(NULL);
last = str + len;
if (((ctxt->depth > 40) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) ||
(ctxt->depth > 1024)) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
return(NULL);
}
/*
* allocate a translation buffer.
*/
buffer_size = XML_PARSER_BIG_BUFFER_SIZE;
buffer = (xmlChar *) xmlMallocAtomic(buffer_size);
if (buffer == NULL) goto mem_error;
/*
* OK loop until we reach one of the ending char or a size limit.
* we are operating on already parsed values.
*/
if (str < last)
c = CUR_SCHAR(str, l);
else
c = 0;
while ((c != 0) && (c != end) && /* non input consuming loop */
(c != end2) && (c != end3)) {
if (c == 0) break;
if ((c == '&') && (str[1] == '#')) {
int val = xmlParseStringCharRef(ctxt, &str);
if (val != 0) {
COPY_BUF(0,buffer,nbchars,val);
}
if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
} else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) {
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"String decoding Entity Reference: %.30s\n",
str);
ent = xmlParseStringEntityRef(ctxt, &str);
if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) ||
(ctxt->lastError.code == XML_ERR_INTERNAL_ERROR))
goto int_error;
xmlParserEntityCheck(ctxt, 0, ent, 0);
if (ent != NULL)
ctxt->nbentities += ent->checked / 2;
if ((ent != NULL) &&
(ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
if (ent->content != NULL) {
COPY_BUF(0,buffer,nbchars,ent->content[0]);
if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
} else {
xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR,
"predefined entity has no content\n");
}
} else if ((ent != NULL) && (ent->content != NULL)) {
ctxt->depth++;
rep = xmlStringDecodeEntities(ctxt, ent->content, what,
0, 0, 0);
ctxt->depth--;
if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) ||
(ctxt->lastError.code == XML_ERR_INTERNAL_ERROR))
goto int_error;
if (rep != NULL) {
current = rep;
while (*current != 0) { /* non input consuming loop */
buffer[nbchars++] = *current++;
if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {
if (xmlParserEntityCheck(ctxt, nbchars, ent, 0))
goto int_error;
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
}
xmlFree(rep);
rep = NULL;
}
} else if (ent != NULL) {
int i = xmlStrlen(ent->name);
const xmlChar *cur = ent->name;
buffer[nbchars++] = '&';
if (nbchars + i + XML_PARSER_BUFFER_SIZE > buffer_size) {
growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE);
}
for (;i > 0;i--)
buffer[nbchars++] = *cur++;
buffer[nbchars++] = ';';
}
} else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) {
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"String decoding PE Reference: %.30s\n", str);
ent = xmlParseStringPEReference(ctxt, &str);
if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP)
goto int_error;
xmlParserEntityCheck(ctxt, 0, ent, 0);
if (ent != NULL)
ctxt->nbentities += ent->checked / 2;
if (ent != NULL) {
if (ent->content == NULL) {
/*
* Note: external parsed entities will not be loaded,
* it is not required for a non-validating parser to
* complete external PEreferences coming from the
* internal subset
*/
if (((ctxt->options & XML_PARSE_NOENT) != 0) ||
((ctxt->options & XML_PARSE_DTDVALID) != 0) ||
(ctxt->validate != 0)) {
xmlLoadEntityContent(ctxt, ent);
} else {
xmlWarningMsg(ctxt, XML_ERR_ENTITY_PROCESSING,
"not validating will not read content for PE entity %s\n",
ent->name, NULL);
}
}
ctxt->depth++;
rep = xmlStringDecodeEntities(ctxt, ent->content, what,
0, 0, 0);
ctxt->depth--;
if (rep != NULL) {
current = rep;
while (*current != 0) { /* non input consuming loop */
buffer[nbchars++] = *current++;
if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {
if (xmlParserEntityCheck(ctxt, nbchars, ent, 0))
goto int_error;
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
}
xmlFree(rep);
rep = NULL;
}
}
} else {
COPY_BUF(l,buffer,nbchars,c);
str += l;
if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
}
if (str < last)
c = CUR_SCHAR(str, l);
else
c = 0;
}
buffer[nbchars] = 0;
return(buffer);
mem_error:
xmlErrMemory(ctxt, NULL);
int_error:
if (rep != NULL)
xmlFree(rep);
if (buffer != NULL)
xmlFree(buffer);
return(NULL);
}
/**
* xmlStringDecodeEntities:
* @ctxt: the parser context
* @str: the input string
* @what: combination of XML_SUBSTITUTE_REF and XML_SUBSTITUTE_PEREF
* @end: an end marker xmlChar, 0 if none
* @end2: an end marker xmlChar, 0 if none
* @end3: an end marker xmlChar, 0 if none
*
* Takes a entity string content and process to do the adequate substitutions.
*
* [67] Reference ::= EntityRef | CharRef
*
* [69] PEReference ::= '%' Name ';'
*
* Returns A newly allocated string with the substitution done. The caller
* must deallocate it !
*/
xmlChar *
xmlStringDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int what,
xmlChar end, xmlChar end2, xmlChar end3) {
if ((ctxt == NULL) || (str == NULL)) return(NULL);
return(xmlStringLenDecodeEntities(ctxt, str, xmlStrlen(str), what,
end, end2, end3));
}
/************************************************************************
* *
* Commodity functions, cleanup needed ? *
* *
************************************************************************/
/**
* areBlanks:
* @ctxt: an XML parser context
* @str: a xmlChar *
* @len: the size of @str
* @blank_chars: we know the chars are blanks
*
* Is this a sequence of blank chars that one can ignore ?
*
* Returns 1 if ignorable 0 otherwise.
*/
static int areBlanks(xmlParserCtxtPtr ctxt, const xmlChar *str, int len,
int blank_chars) {
int i, ret;
xmlNodePtr lastChild;
/*
* Don't spend time trying to differentiate them, the same callback is
* used !
*/
if (ctxt->sax->ignorableWhitespace == ctxt->sax->characters)
return(0);
/*
* Check for xml:space value.
*/
if ((ctxt->space == NULL) || (*(ctxt->space) == 1) ||
(*(ctxt->space) == -2))
return(0);
/*
* Check that the string is made of blanks
*/
if (blank_chars == 0) {
for (i = 0;i < len;i++)
if (!(IS_BLANK_CH(str[i]))) return(0);
}
/*
* Look if the element is mixed content in the DTD if available
*/
if (ctxt->node == NULL) return(0);
if (ctxt->myDoc != NULL) {
ret = xmlIsMixedElement(ctxt->myDoc, ctxt->node->name);
if (ret == 0) return(1);
if (ret == 1) return(0);
}
/*
* Otherwise, heuristic :-\
*/
if ((RAW != '<') && (RAW != 0xD)) return(0);
if ((ctxt->node->children == NULL) &&
(RAW == '<') && (NXT(1) == '/')) return(0);
lastChild = xmlGetLastChild(ctxt->node);
if (lastChild == NULL) {
if ((ctxt->node->type != XML_ELEMENT_NODE) &&
(ctxt->node->content != NULL)) return(0);
} else if (xmlNodeIsText(lastChild))
return(0);
else if ((ctxt->node->children != NULL) &&
(xmlNodeIsText(ctxt->node->children)))
return(0);
return(1);
}
/************************************************************************
* *
* Extra stuff for namespace support *
* Relates to http://www.w3.org/TR/WD-xml-names *
* *
************************************************************************/
/**
* xmlSplitQName:
* @ctxt: an XML parser context
* @name: an XML parser context
* @prefix: a xmlChar **
*
* parse an UTF8 encoded XML qualified name string
*
* [NS 5] QName ::= (Prefix ':')? LocalPart
*
* [NS 6] Prefix ::= NCName
*
* [NS 7] LocalPart ::= NCName
*
* Returns the local part, and prefix is updated
* to get the Prefix if any.
*/
xmlChar *
xmlSplitQName(xmlParserCtxtPtr ctxt, const xmlChar *name, xmlChar **prefix) {
xmlChar buf[XML_MAX_NAMELEN + 5];
xmlChar *buffer = NULL;
int len = 0;
int max = XML_MAX_NAMELEN;
xmlChar *ret = NULL;
const xmlChar *cur = name;
int c;
if (prefix == NULL) return(NULL);
*prefix = NULL;
if (cur == NULL) return(NULL);
#ifndef XML_XML_NAMESPACE
/* xml: prefix is not really a namespace */
if ((cur[0] == 'x') && (cur[1] == 'm') &&
(cur[2] == 'l') && (cur[3] == ':'))
return(xmlStrdup(name));
#endif
/* nasty but well=formed */
if (cur[0] == ':')
return(xmlStrdup(name));
c = *cur++;
while ((c != 0) && (c != ':') && (len < max)) { /* tested bigname.xml */
buf[len++] = c;
c = *cur++;
}
if (len >= max) {
/*
* Okay someone managed to make a huge name, so he's ready to pay
* for the processing speed.
*/
max = len * 2;
buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar));
if (buffer == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
memcpy(buffer, buf, len);
while ((c != 0) && (c != ':')) { /* tested bigname.xml */
if (len + 10 > max) {
xmlChar *tmp;
max *= 2;
tmp = (xmlChar *) xmlRealloc(buffer,
max * sizeof(xmlChar));
if (tmp == NULL) {
xmlFree(buffer);
xmlErrMemory(ctxt, NULL);
return(NULL);
}
buffer = tmp;
}
buffer[len++] = c;
c = *cur++;
}
buffer[len] = 0;
}
if ((c == ':') && (*cur == 0)) {
if (buffer != NULL)
xmlFree(buffer);
*prefix = NULL;
return(xmlStrdup(name));
}
if (buffer == NULL)
ret = xmlStrndup(buf, len);
else {
ret = buffer;
buffer = NULL;
max = XML_MAX_NAMELEN;
}
if (c == ':') {
c = *cur;
*prefix = ret;
if (c == 0) {
return(xmlStrndup(BAD_CAST "", 0));
}
len = 0;
/*
* Check that the first character is proper to start
* a new name
*/
if (!(((c >= 0x61) && (c <= 0x7A)) ||
((c >= 0x41) && (c <= 0x5A)) ||
(c == '_') || (c == ':'))) {
int l;
int first = CUR_SCHAR(cur, l);
if (!IS_LETTER(first) && (first != '_')) {
xmlFatalErrMsgStr(ctxt, XML_NS_ERR_QNAME,
"Name %s is not XML Namespace compliant\n",
name);
}
}
cur++;
while ((c != 0) && (len < max)) { /* tested bigname2.xml */
buf[len++] = c;
c = *cur++;
}
if (len >= max) {
/*
* Okay someone managed to make a huge name, so he's ready to pay
* for the processing speed.
*/
max = len * 2;
buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar));
if (buffer == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
memcpy(buffer, buf, len);
while (c != 0) { /* tested bigname2.xml */
if (len + 10 > max) {
xmlChar *tmp;
max *= 2;
tmp = (xmlChar *) xmlRealloc(buffer,
max * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buffer);
return(NULL);
}
buffer = tmp;
}
buffer[len++] = c;
c = *cur++;
}
buffer[len] = 0;
}
if (buffer == NULL)
ret = xmlStrndup(buf, len);
else {
ret = buffer;
}
}
return(ret);
}
/************************************************************************
* *
* The parser itself *
* Relates to http://www.w3.org/TR/REC-xml *
* *
************************************************************************/
/************************************************************************
* *
* Routines to parse Name, NCName and NmToken *
* *
************************************************************************/
#ifdef DEBUG
static unsigned long nbParseName = 0;
static unsigned long nbParseNmToken = 0;
static unsigned long nbParseNCName = 0;
static unsigned long nbParseNCNameComplex = 0;
static unsigned long nbParseNameComplex = 0;
static unsigned long nbParseStringName = 0;
#endif
/*
* The two following functions are related to the change of accepted
* characters for Name and NmToken in the Revision 5 of XML-1.0
* They correspond to the modified production [4] and the new production [4a]
* changes in that revision. Also note that the macros used for the
* productions Letter, Digit, CombiningChar and Extender are not needed
* anymore.
* We still keep compatibility to pre-revision5 parsing semantic if the
* new XML_PARSE_OLD10 option is given to the parser.
*/
static int
xmlIsNameStartChar(xmlParserCtxtPtr ctxt, int c) {
if ((ctxt->options & XML_PARSE_OLD10) == 0) {
/*
* Use the new checks of production [4] [4a] amd [5] of the
* Update 5 of XML-1.0
*/
if ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
(((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
(c == '_') || (c == ':') ||
((c >= 0xC0) && (c <= 0xD6)) ||
((c >= 0xD8) && (c <= 0xF6)) ||
((c >= 0xF8) && (c <= 0x2FF)) ||
((c >= 0x370) && (c <= 0x37D)) ||
((c >= 0x37F) && (c <= 0x1FFF)) ||
((c >= 0x200C) && (c <= 0x200D)) ||
((c >= 0x2070) && (c <= 0x218F)) ||
((c >= 0x2C00) && (c <= 0x2FEF)) ||
((c >= 0x3001) && (c <= 0xD7FF)) ||
((c >= 0xF900) && (c <= 0xFDCF)) ||
((c >= 0xFDF0) && (c <= 0xFFFD)) ||
((c >= 0x10000) && (c <= 0xEFFFF))))
return(1);
} else {
if (IS_LETTER(c) || (c == '_') || (c == ':'))
return(1);
}
return(0);
}
static int
xmlIsNameChar(xmlParserCtxtPtr ctxt, int c) {
if ((ctxt->options & XML_PARSE_OLD10) == 0) {
/*
* Use the new checks of production [4] [4a] amd [5] of the
* Update 5 of XML-1.0
*/
if ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
(((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
((c >= '0') && (c <= '9')) || /* !start */
(c == '_') || (c == ':') ||
(c == '-') || (c == '.') || (c == 0xB7) || /* !start */
((c >= 0xC0) && (c <= 0xD6)) ||
((c >= 0xD8) && (c <= 0xF6)) ||
((c >= 0xF8) && (c <= 0x2FF)) ||
((c >= 0x300) && (c <= 0x36F)) || /* !start */
((c >= 0x370) && (c <= 0x37D)) ||
((c >= 0x37F) && (c <= 0x1FFF)) ||
((c >= 0x200C) && (c <= 0x200D)) ||
((c >= 0x203F) && (c <= 0x2040)) || /* !start */
((c >= 0x2070) && (c <= 0x218F)) ||
((c >= 0x2C00) && (c <= 0x2FEF)) ||
((c >= 0x3001) && (c <= 0xD7FF)) ||
((c >= 0xF900) && (c <= 0xFDCF)) ||
((c >= 0xFDF0) && (c <= 0xFFFD)) ||
((c >= 0x10000) && (c <= 0xEFFFF))))
return(1);
} else {
if ((IS_LETTER(c)) || (IS_DIGIT(c)) ||
(c == '.') || (c == '-') ||
(c == '_') || (c == ':') ||
(IS_COMBINING(c)) ||
(IS_EXTENDER(c)))
return(1);
}
return(0);
}
static xmlChar * xmlParseAttValueInternal(xmlParserCtxtPtr ctxt,
int *len, int *alloc, int normalize);
static const xmlChar *
xmlParseNameComplex(xmlParserCtxtPtr ctxt) {
int len = 0, l;
int c;
int count = 0;
#ifdef DEBUG
nbParseNameComplex++;
#endif
/*
* Handler for more complex cases
*/
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
c = CUR_CHAR(l);
if ((ctxt->options & XML_PARSE_OLD10) == 0) {
/*
* Use the new checks of production [4] [4a] amd [5] of the
* Update 5 of XML-1.0
*/
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!(((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
(c == '_') || (c == ':') ||
((c >= 0xC0) && (c <= 0xD6)) ||
((c >= 0xD8) && (c <= 0xF6)) ||
((c >= 0xF8) && (c <= 0x2FF)) ||
((c >= 0x370) && (c <= 0x37D)) ||
((c >= 0x37F) && (c <= 0x1FFF)) ||
((c >= 0x200C) && (c <= 0x200D)) ||
((c >= 0x2070) && (c <= 0x218F)) ||
((c >= 0x2C00) && (c <= 0x2FEF)) ||
((c >= 0x3001) && (c <= 0xD7FF)) ||
((c >= 0xF900) && (c <= 0xFDCF)) ||
((c >= 0xFDF0) && (c <= 0xFFFD)) ||
((c >= 0x10000) && (c <= 0xEFFFF))))) {
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
while ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
(((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
((c >= '0') && (c <= '9')) || /* !start */
(c == '_') || (c == ':') ||
(c == '-') || (c == '.') || (c == 0xB7) || /* !start */
((c >= 0xC0) && (c <= 0xD6)) ||
((c >= 0xD8) && (c <= 0xF6)) ||
((c >= 0xF8) && (c <= 0x2FF)) ||
((c >= 0x300) && (c <= 0x36F)) || /* !start */
((c >= 0x370) && (c <= 0x37D)) ||
((c >= 0x37F) && (c <= 0x1FFF)) ||
((c >= 0x200C) && (c <= 0x200D)) ||
((c >= 0x203F) && (c <= 0x2040)) || /* !start */
((c >= 0x2070) && (c <= 0x218F)) ||
((c >= 0x2C00) && (c <= 0x2FEF)) ||
((c >= 0x3001) && (c <= 0xD7FF)) ||
((c >= 0xF900) && (c <= 0xFDCF)) ||
((c >= 0xFDF0) && (c <= 0xFFFD)) ||
((c >= 0x10000) && (c <= 0xEFFFF))
)) {
if (count++ > XML_PARSER_CHUNK_SIZE) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
} else {
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!IS_LETTER(c) && (c != '_') &&
(c != ':'))) {
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
((IS_LETTER(c)) || (IS_DIGIT(c)) ||
(c == '.') || (c == '-') ||
(c == '_') || (c == ':') ||
(IS_COMBINING(c)) ||
(IS_EXTENDER(c)))) {
if (count++ > XML_PARSER_CHUNK_SIZE) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
}
if ((len > XML_MAX_NAME_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "Name");
return(NULL);
}
if (ctxt->input->cur - ctxt->input->base < len) {
/*
* There were a couple of bugs where PERefs lead to to a change
* of the buffer. Check the buffer size to avoid passing an invalid
* pointer to xmlDictLookup.
*/
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"unexpected change of input buffer");
return (NULL);
}
if ((*ctxt->input->cur == '\n') && (ctxt->input->cur[-1] == '\r'))
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - (len + 1), len));
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
}
/**
* xmlParseName:
* @ctxt: an XML parser context
*
* parse an XML name.
*
* [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' |
* CombiningChar | Extender
*
* [5] Name ::= (Letter | '_' | ':') (NameChar)*
*
* [6] Names ::= Name (#x20 Name)*
*
* Returns the Name parsed or NULL
*/
const xmlChar *
xmlParseName(xmlParserCtxtPtr ctxt) {
const xmlChar *in;
const xmlChar *ret;
int count = 0;
GROW;
#ifdef DEBUG
nbParseName++;
#endif
/*
* Accelerator for simple ASCII names
*/
in = ctxt->input->cur;
if (((*in >= 0x61) && (*in <= 0x7A)) ||
((*in >= 0x41) && (*in <= 0x5A)) ||
(*in == '_') || (*in == ':')) {
in++;
while (((*in >= 0x61) && (*in <= 0x7A)) ||
((*in >= 0x41) && (*in <= 0x5A)) ||
((*in >= 0x30) && (*in <= 0x39)) ||
(*in == '_') || (*in == '-') ||
(*in == ':') || (*in == '.'))
in++;
if ((*in > 0) && (*in < 0x80)) {
count = in - ctxt->input->cur;
if ((count > XML_MAX_NAME_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "Name");
return(NULL);
}
ret = xmlDictLookup(ctxt->dict, ctxt->input->cur, count);
ctxt->input->cur = in;
ctxt->nbChars += count;
ctxt->input->col += count;
if (ret == NULL)
xmlErrMemory(ctxt, NULL);
return(ret);
}
}
/* accelerator for special cases */
return(xmlParseNameComplex(ctxt));
}
static const xmlChar *
xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) {
int len = 0, l;
int c;
int count = 0;
size_t startPosition = 0;
#ifdef DEBUG
nbParseNCNameComplex++;
#endif
/*
* Handler for more complex cases
*/
GROW;
startPosition = CUR_PTR - BASE_PTR;
c = CUR_CHAR(l);
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!xmlIsNameStartChar(ctxt, c) || (c == ':'))) {
return(NULL);
}
while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
(xmlIsNameChar(ctxt, c) && (c != ':'))) {
if (count++ > XML_PARSER_CHUNK_SIZE) {
if ((len > XML_MAX_NAME_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName");
return(NULL);
}
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
if (c == 0) {
count = 0;
/*
* when shrinking to extend the buffer we really need to preserve
* the part of the name we already parsed. Hence rolling back
* by current lenght.
*/
ctxt->input->cur -= l;
GROW;
ctxt->input->cur += l;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
c = CUR_CHAR(l);
}
}
if ((len > XML_MAX_NAME_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName");
return(NULL);
}
return(xmlDictLookup(ctxt->dict, (BASE_PTR + startPosition), len));
}
/**
* xmlParseNCName:
* @ctxt: an XML parser context
* @len: length of the string parsed
*
* parse an XML name.
*
* [4NS] NCNameChar ::= Letter | Digit | '.' | '-' | '_' |
* CombiningChar | Extender
*
* [5NS] NCName ::= (Letter | '_') (NCNameChar)*
*
* Returns the Name parsed or NULL
*/
static const xmlChar *
xmlParseNCName(xmlParserCtxtPtr ctxt) {
const xmlChar *in, *e;
const xmlChar *ret;
int count = 0;
#ifdef DEBUG
nbParseNCName++;
#endif
/*
* Accelerator for simple ASCII names
*/
in = ctxt->input->cur;
e = ctxt->input->end;
if ((((*in >= 0x61) && (*in <= 0x7A)) ||
((*in >= 0x41) && (*in <= 0x5A)) ||
(*in == '_')) && (in < e)) {
in++;
while ((((*in >= 0x61) && (*in <= 0x7A)) ||
((*in >= 0x41) && (*in <= 0x5A)) ||
((*in >= 0x30) && (*in <= 0x39)) ||
(*in == '_') || (*in == '-') ||
(*in == '.')) && (in < e))
in++;
if (in >= e)
goto complex;
if ((*in > 0) && (*in < 0x80)) {
count = in - ctxt->input->cur;
if ((count > XML_MAX_NAME_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName");
return(NULL);
}
ret = xmlDictLookup(ctxt->dict, ctxt->input->cur, count);
ctxt->input->cur = in;
ctxt->nbChars += count;
ctxt->input->col += count;
if (ret == NULL) {
xmlErrMemory(ctxt, NULL);
}
return(ret);
}
}
complex:
return(xmlParseNCNameComplex(ctxt));
}
/**
* xmlParseNameAndCompare:
* @ctxt: an XML parser context
*
* parse an XML name and compares for match
* (specialized for endtag parsing)
*
* Returns NULL for an illegal name, (xmlChar*) 1 for success
* and the name for mismatch
*/
static const xmlChar *
xmlParseNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *other) {
register const xmlChar *cmp = other;
register const xmlChar *in;
const xmlChar *ret;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
in = ctxt->input->cur;
while (*in != 0 && *in == *cmp) {
++in;
++cmp;
ctxt->input->col++;
}
if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) {
/* success */
ctxt->input->cur = in;
return (const xmlChar*) 1;
}
/* failure (or end of input buffer), check with full function */
ret = xmlParseName (ctxt);
/* strings coming from the dictionary direct compare possible */
if (ret == other) {
return (const xmlChar*) 1;
}
return ret;
}
/**
* xmlParseStringName:
* @ctxt: an XML parser context
* @str: a pointer to the string pointer (IN/OUT)
*
* parse an XML name.
*
* [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' |
* CombiningChar | Extender
*
* [5] Name ::= (Letter | '_' | ':') (NameChar)*
*
* [6] Names ::= Name (#x20 Name)*
*
* Returns the Name parsed or NULL. The @str pointer
* is updated to the current location in the string.
*/
static xmlChar *
xmlParseStringName(xmlParserCtxtPtr ctxt, const xmlChar** str) {
xmlChar buf[XML_MAX_NAMELEN + 5];
const xmlChar *cur = *str;
int len = 0, l;
int c;
#ifdef DEBUG
nbParseStringName++;
#endif
c = CUR_SCHAR(cur, l);
if (!xmlIsNameStartChar(ctxt, c)) {
return(NULL);
}
COPY_BUF(l,buf,len,c);
cur += l;
c = CUR_SCHAR(cur, l);
while (xmlIsNameChar(ctxt, c)) {
COPY_BUF(l,buf,len,c);
cur += l;
c = CUR_SCHAR(cur, l);
if (len >= XML_MAX_NAMELEN) { /* test bigentname.xml */
/*
* Okay someone managed to make a huge name, so he's ready to pay
* for the processing speed.
*/
xmlChar *buffer;
int max = len * 2;
buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar));
if (buffer == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
memcpy(buffer, buf, len);
while (xmlIsNameChar(ctxt, c)) {
if (len + 10 > max) {
xmlChar *tmp;
if ((len > XML_MAX_NAME_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName");
xmlFree(buffer);
return(NULL);
}
max *= 2;
tmp = (xmlChar *) xmlRealloc(buffer,
max * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buffer);
return(NULL);
}
buffer = tmp;
}
COPY_BUF(l,buffer,len,c);
cur += l;
c = CUR_SCHAR(cur, l);
}
buffer[len] = 0;
*str = cur;
return(buffer);
}
}
if ((len > XML_MAX_NAME_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName");
return(NULL);
}
*str = cur;
return(xmlStrndup(buf, len));
}
/**
* xmlParseNmtoken:
* @ctxt: an XML parser context
*
* parse an XML Nmtoken.
*
* [7] Nmtoken ::= (NameChar)+
*
* [8] Nmtokens ::= Nmtoken (#x20 Nmtoken)*
*
* Returns the Nmtoken parsed or NULL
*/
xmlChar *
xmlParseNmtoken(xmlParserCtxtPtr ctxt) {
xmlChar buf[XML_MAX_NAMELEN + 5];
int len = 0, l;
int c;
int count = 0;
#ifdef DEBUG
nbParseNmToken++;
#endif
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
c = CUR_CHAR(l);
while (xmlIsNameChar(ctxt, c)) {
if (count++ > XML_PARSER_CHUNK_SIZE) {
count = 0;
GROW;
}
COPY_BUF(l,buf,len,c);
NEXTL(l);
c = CUR_CHAR(l);
if (c == 0) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
c = CUR_CHAR(l);
}
if (len >= XML_MAX_NAMELEN) {
/*
* Okay someone managed to make a huge token, so he's ready to pay
* for the processing speed.
*/
xmlChar *buffer;
int max = len * 2;
buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar));
if (buffer == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
memcpy(buffer, buf, len);
while (xmlIsNameChar(ctxt, c)) {
if (count++ > XML_PARSER_CHUNK_SIZE) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buffer);
return(NULL);
}
}
if (len + 10 > max) {
xmlChar *tmp;
if ((max > XML_MAX_NAME_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NmToken");
xmlFree(buffer);
return(NULL);
}
max *= 2;
tmp = (xmlChar *) xmlRealloc(buffer,
max * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buffer);
return(NULL);
}
buffer = tmp;
}
COPY_BUF(l,buffer,len,c);
NEXTL(l);
c = CUR_CHAR(l);
}
buffer[len] = 0;
return(buffer);
}
}
if (len == 0)
return(NULL);
if ((len > XML_MAX_NAME_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NmToken");
return(NULL);
}
return(xmlStrndup(buf, len));
}
/**
* xmlParseEntityValue:
* @ctxt: an XML parser context
* @orig: if non-NULL store a copy of the original entity value
*
* parse a value for ENTITY declarations
*
* [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"' |
* "'" ([^%&'] | PEReference | Reference)* "'"
*
* Returns the EntityValue parsed with reference substituted or NULL
*/
xmlChar *
xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
int c, l;
xmlChar stop;
xmlChar *ret = NULL;
const xmlChar *cur = NULL;
xmlParserInputPtr input;
if (RAW == '"') stop = '"';
else if (RAW == '\'') stop = '\'';
else {
xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_STARTED, NULL);
return(NULL);
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
/*
* The content of the entity definition is copied in a buffer.
*/
ctxt->instate = XML_PARSER_ENTITY_VALUE;
input = ctxt->input;
GROW;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return(NULL);
}
NEXT;
c = CUR_CHAR(l);
/*
* NOTE: 4.4.5 Included in Literal
* When a parameter entity reference appears in a literal entity
* value, ... a single or double quote character in the replacement
* text is always treated as a normal data character and will not
* terminate the literal.
* In practice it means we stop the loop only when back at parsing
* the initial entity and the quote is found
*/
while (((IS_CHAR(c)) && ((c != stop) || /* checked */
(ctxt->input != input))) && (ctxt->instate != XML_PARSER_EOF)) {
if (len + 5 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buf);
return(NULL);
}
buf = tmp;
}
COPY_BUF(l,buf,len,c);
NEXTL(l);
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1)) /* non input consuming */
xmlPopInput(ctxt);
GROW;
c = CUR_CHAR(l);
if (c == 0) {
GROW;
c = CUR_CHAR(l);
}
}
buf[len] = 0;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return(NULL);
}
/*
* Raise problem w.r.t. '&' and '%' being used in non-entities
* reference constructs. Note Charref will be handled in
* xmlStringDecodeEntities()
*/
cur = buf;
while (*cur != 0) { /* non input consuming */
if ((*cur == '%') || ((*cur == '&') && (cur[1] != '#'))) {
xmlChar *name;
xmlChar tmp = *cur;
cur++;
name = xmlParseStringName(ctxt, &cur);
if ((name == NULL) || (*cur != ';')) {
xmlFatalErrMsgInt(ctxt, XML_ERR_ENTITY_CHAR_ERROR,
"EntityValue: '%c' forbidden except for entities references\n",
tmp);
}
if ((tmp == '%') && (ctxt->inSubset == 1) &&
(ctxt->inputNr == 1)) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_PE_INTERNAL, NULL);
}
if (name != NULL)
xmlFree(name);
if (*cur == 0)
break;
}
cur++;
}
/*
* Then PEReference entities are substituted.
*/
if (c != stop) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, NULL);
xmlFree(buf);
} else {
NEXT;
/*
* NOTE: 4.4.7 Bypassed
* When a general entity reference appears in the EntityValue in
* an entity declaration, it is bypassed and left as is.
* so XML_SUBSTITUTE_REF is not set here.
*/
++ctxt->depth;
ret = xmlStringDecodeEntities(ctxt, buf, XML_SUBSTITUTE_PEREF,
0, 0, 0);
--ctxt->depth;
if (orig != NULL)
*orig = buf;
else
xmlFree(buf);
}
return(ret);
}
/**
* xmlParseAttValueComplex:
* @ctxt: an XML parser context
* @len: the resulting attribute len
* @normalize: wether to apply the inner normalization
*
* parse a value for an attribute, this is the fallback function
* of xmlParseAttValue() when the attribute parsing requires handling
* of non-ASCII characters, or normalization compaction.
*
* Returns the AttValue parsed or NULL. The value has to be freed by the caller.
*/
static xmlChar *
xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) {
xmlChar limit = 0;
xmlChar *buf = NULL;
xmlChar *rep = NULL;
size_t len = 0;
size_t buf_size = 0;
int c, l, in_space = 0;
xmlChar *current = NULL;
xmlEntityPtr ent;
if (NXT(0) == '"') {
ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE;
limit = '"';
NEXT;
} else if (NXT(0) == '\'') {
limit = '\'';
ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE;
NEXT;
} else {
xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL);
return(NULL);
}
/*
* allocate a translation buffer.
*/
buf_size = XML_PARSER_BUFFER_SIZE;
buf = (xmlChar *) xmlMallocAtomic(buf_size);
if (buf == NULL) goto mem_error;
/*
* OK loop until we reach one of the ending char or a size limit.
*/
c = CUR_CHAR(l);
while (((NXT(0) != limit) && /* checked */
(IS_CHAR(c)) && (c != '<')) &&
(ctxt->instate != XML_PARSER_EOF)) {
/*
* Impose a reasonable limit on attribute size, unless XML_PARSE_HUGE
* special option is given
*/
if ((len > XML_MAX_TEXT_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
"AttValue length too long\n");
goto mem_error;
}
if (c == 0) break;
if (c == '&') {
in_space = 0;
if (NXT(1) == '#') {
int val = xmlParseCharRef(ctxt);
if (val == '&') {
if (ctxt->replaceEntities) {
if (len + 10 > buf_size) {
growBuffer(buf, 10);
}
buf[len++] = '&';
} else {
/*
* The reparsing will be done in xmlStringGetNodeList()
* called by the attribute() function in SAX.c
*/
if (len + 10 > buf_size) {
growBuffer(buf, 10);
}
buf[len++] = '&';
buf[len++] = '#';
buf[len++] = '3';
buf[len++] = '8';
buf[len++] = ';';
}
} else if (val != 0) {
if (len + 10 > buf_size) {
growBuffer(buf, 10);
}
len += xmlCopyChar(0, &buf[len], val);
}
} else {
ent = xmlParseEntityRef(ctxt);
ctxt->nbentities++;
if (ent != NULL)
ctxt->nbentities += ent->owner;
if ((ent != NULL) &&
(ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
if (len + 10 > buf_size) {
growBuffer(buf, 10);
}
if ((ctxt->replaceEntities == 0) &&
(ent->content[0] == '&')) {
buf[len++] = '&';
buf[len++] = '#';
buf[len++] = '3';
buf[len++] = '8';
buf[len++] = ';';
} else {
buf[len++] = ent->content[0];
}
} else if ((ent != NULL) &&
(ctxt->replaceEntities != 0)) {
if (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) {
++ctxt->depth;
rep = xmlStringDecodeEntities(ctxt, ent->content,
XML_SUBSTITUTE_REF,
0, 0, 0);
--ctxt->depth;
if (rep != NULL) {
current = rep;
while (*current != 0) { /* non input consuming */
if ((*current == 0xD) || (*current == 0xA) ||
(*current == 0x9)) {
buf[len++] = 0x20;
current++;
} else
buf[len++] = *current++;
if (len + 10 > buf_size) {
growBuffer(buf, 10);
}
}
xmlFree(rep);
rep = NULL;
}
} else {
if (len + 10 > buf_size) {
growBuffer(buf, 10);
}
if (ent->content != NULL)
buf[len++] = ent->content[0];
}
} else if (ent != NULL) {
int i = xmlStrlen(ent->name);
const xmlChar *cur = ent->name;
/*
* This may look absurd but is needed to detect
* entities problems
*/
if ((ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) &&
(ent->content != NULL) && (ent->checked == 0)) {
unsigned long oldnbent = ctxt->nbentities;
++ctxt->depth;
rep = xmlStringDecodeEntities(ctxt, ent->content,
XML_SUBSTITUTE_REF, 0, 0, 0);
--ctxt->depth;
ent->checked = (ctxt->nbentities - oldnbent + 1) * 2;
if (rep != NULL) {
if (xmlStrchr(rep, '<'))
ent->checked |= 1;
xmlFree(rep);
rep = NULL;
}
}
/*
* Just output the reference
*/
buf[len++] = '&';
while (len + i + 10 > buf_size) {
growBuffer(buf, i + 10);
}
for (;i > 0;i--)
buf[len++] = *cur++;
buf[len++] = ';';
}
}
} else {
if ((c == 0x20) || (c == 0xD) || (c == 0xA) || (c == 0x9)) {
if ((len != 0) || (!normalize)) {
if ((!normalize) || (!in_space)) {
COPY_BUF(l,buf,len,0x20);
while (len + 10 > buf_size) {
growBuffer(buf, 10);
}
}
in_space = 1;
}
} else {
in_space = 0;
COPY_BUF(l,buf,len,c);
if (len + 10 > buf_size) {
growBuffer(buf, 10);
}
}
NEXTL(l);
}
GROW;
c = CUR_CHAR(l);
}
if (ctxt->instate == XML_PARSER_EOF)
goto error;
if ((in_space) && (normalize)) {
while ((len > 0) && (buf[len - 1] == 0x20)) len--;
}
buf[len] = 0;
if (RAW == '<') {
xmlFatalErr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, NULL);
} else if (RAW != limit) {
if ((c != 0) && (!IS_CHAR(c))) {
xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR,
"invalid character in attribute value\n");
} else {
xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
"AttValue: ' expected\n");
}
} else
NEXT;
/*
* There we potentially risk an overflow, don't allow attribute value of
* length more than INT_MAX it is a very reasonnable assumption !
*/
if (len >= INT_MAX) {
xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
"AttValue length too long\n");
goto mem_error;
}
if (attlen != NULL) *attlen = (int) len;
return(buf);
mem_error:
xmlErrMemory(ctxt, NULL);
error:
if (buf != NULL)
xmlFree(buf);
if (rep != NULL)
xmlFree(rep);
return(NULL);
}
/**
* xmlParseAttValue:
* @ctxt: an XML parser context
*
* parse a value for an attribute
* Note: the parser won't do substitution of entities here, this
* will be handled later in xmlStringGetNodeList
*
* [10] AttValue ::= '"' ([^<&"] | Reference)* '"' |
* "'" ([^<&'] | Reference)* "'"
*
* 3.3.3 Attribute-Value Normalization:
* Before the value of an attribute is passed to the application or
* checked for validity, the XML processor must normalize it as follows:
* - a character reference is processed by appending the referenced
* character to the attribute value
* - an entity reference is processed by recursively processing the
* replacement text of the entity
* - a whitespace character (#x20, #xD, #xA, #x9) is processed by
* appending #x20 to the normalized value, except that only a single
* #x20 is appended for a "#xD#xA" sequence that is part of an external
* parsed entity or the literal entity value of an internal parsed entity
* - other characters are processed by appending them to the normalized value
* If the declared value is not CDATA, then the XML processor must further
* process the normalized attribute value by discarding any leading and
* trailing space (#x20) characters, and by replacing sequences of space
* (#x20) characters by a single space (#x20) character.
* All attributes for which no declaration has been read should be treated
* by a non-validating parser as if declared CDATA.
*
* Returns the AttValue parsed or NULL. The value has to be freed by the caller.
*/
xmlChar *
xmlParseAttValue(xmlParserCtxtPtr ctxt) {
if ((ctxt == NULL) || (ctxt->input == NULL)) return(NULL);
return(xmlParseAttValueInternal(ctxt, NULL, NULL, 0));
}
/**
* xmlParseSystemLiteral:
* @ctxt: an XML parser context
*
* parse an XML Literal
*
* [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
*
* Returns the SystemLiteral parsed or NULL
*/
xmlChar *
xmlParseSystemLiteral(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
int cur, l;
xmlChar stop;
int state = ctxt->instate;
int count = 0;
SHRINK;
if (RAW == '"') {
NEXT;
stop = '"';
} else if (RAW == '\'') {
NEXT;
stop = '\'';
} else {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL);
return(NULL);
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
ctxt->instate = XML_PARSER_SYSTEM_LITERAL;
cur = CUR_CHAR(l);
while ((IS_CHAR(cur)) && (cur != stop)) { /* checked */
if (len + 5 >= size) {
xmlChar *tmp;
if ((size > XML_MAX_NAME_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "SystemLiteral");
xmlFree(buf);
ctxt->instate = (xmlParserInputState) state;
return(NULL);
}
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlFree(buf);
xmlErrMemory(ctxt, NULL);
ctxt->instate = (xmlParserInputState) state;
return(NULL);
}
buf = tmp;
}
count++;
if (count > 50) {
GROW;
count = 0;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return(NULL);
}
}
COPY_BUF(l,buf,len,cur);
NEXTL(l);
cur = CUR_CHAR(l);
if (cur == 0) {
GROW;
SHRINK;
cur = CUR_CHAR(l);
}
}
buf[len] = 0;
ctxt->instate = (xmlParserInputState) state;
if (!IS_CHAR(cur)) {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL);
} else {
NEXT;
}
return(buf);
}
/**
* xmlParsePubidLiteral:
* @ctxt: an XML parser context
*
* parse an XML public literal
*
* [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
*
* Returns the PubidLiteral parsed or NULL.
*/
xmlChar *
xmlParsePubidLiteral(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
xmlChar cur;
xmlChar stop;
int count = 0;
xmlParserInputState oldstate = ctxt->instate;
SHRINK;
if (RAW == '"') {
NEXT;
stop = '"';
} else if (RAW == '\'') {
NEXT;
stop = '\'';
} else {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL);
return(NULL);
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
ctxt->instate = XML_PARSER_PUBLIC_LITERAL;
cur = CUR;
while ((IS_PUBIDCHAR_CH(cur)) && (cur != stop)) { /* checked */
if (len + 1 >= size) {
xmlChar *tmp;
if ((size > XML_MAX_NAME_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "Public ID");
xmlFree(buf);
return(NULL);
}
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buf);
return(NULL);
}
buf = tmp;
}
buf[len++] = cur;
count++;
if (count > 50) {
GROW;
count = 0;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return(NULL);
}
}
NEXT;
cur = CUR;
if (cur == 0) {
GROW;
SHRINK;
cur = CUR;
}
}
buf[len] = 0;
if (cur != stop) {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL);
} else {
NEXT;
}
ctxt->instate = oldstate;
return(buf);
}
static void xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int cdata);
/*
* used for the test in the inner loop of the char data testing
*/
static const unsigned char test_char_data[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x9, CR/LF separated */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x00, 0x27, /* & */
0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x3A, 0x3B, 0x00, 0x3D, 0x3E, 0x3F, /* < */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x00, 0x5E, 0x5F, /* ] */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* non-ascii */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
/**
* xmlParseCharData:
* @ctxt: an XML parser context
* @cdata: int indicating whether we are within a CDATA section
*
* parse a CharData section.
* if we are within a CDATA section ']]>' marks an end of section.
*
* The right angle bracket (>) may be represented using the string ">",
* and must, for compatibility, be escaped using ">" or a character
* reference when it appears in the string "]]>" in content, when that
* string is not marking the end of a CDATA section.
*
* [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
*/
void
xmlParseCharData(xmlParserCtxtPtr ctxt, int cdata) {
const xmlChar *in;
int nbchar = 0;
int line = ctxt->input->line;
int col = ctxt->input->col;
int ccol;
SHRINK;
GROW;
/*
* Accelerated common case where input don't need to be
* modified before passing it to the handler.
*/
if (!cdata) {
in = ctxt->input->cur;
do {
get_more_space:
while (*in == 0x20) { in++; ctxt->input->col++; }
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
goto get_more_space;
}
if (*in == '<') {
nbchar = in - ctxt->input->cur;
if (nbchar > 0) {
const xmlChar *tmp = ctxt->input->cur;
ctxt->input->cur = in;
if ((ctxt->sax != NULL) &&
(ctxt->sax->ignorableWhitespace !=
ctxt->sax->characters)) {
if (areBlanks(ctxt, tmp, nbchar, 1)) {
if (ctxt->sax->ignorableWhitespace != NULL)
ctxt->sax->ignorableWhitespace(ctxt->userData,
tmp, nbchar);
} else {
if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData,
tmp, nbchar);
if (*ctxt->space == -1)
*ctxt->space = -2;
}
} else if ((ctxt->sax != NULL) &&
(ctxt->sax->characters != NULL)) {
ctxt->sax->characters(ctxt->userData,
tmp, nbchar);
}
}
return;
}
get_more:
ccol = ctxt->input->col;
while (test_char_data[*in]) {
in++;
ccol++;
}
ctxt->input->col = ccol;
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
goto get_more;
}
if (*in == ']') {
if ((in[1] == ']') && (in[2] == '>')) {
xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL);
ctxt->input->cur = in;
return;
}
in++;
ctxt->input->col++;
goto get_more;
}
nbchar = in - ctxt->input->cur;
if (nbchar > 0) {
if ((ctxt->sax != NULL) &&
(ctxt->sax->ignorableWhitespace !=
ctxt->sax->characters) &&
(IS_BLANK_CH(*ctxt->input->cur))) {
const xmlChar *tmp = ctxt->input->cur;
ctxt->input->cur = in;
if (areBlanks(ctxt, tmp, nbchar, 0)) {
if (ctxt->sax->ignorableWhitespace != NULL)
ctxt->sax->ignorableWhitespace(ctxt->userData,
tmp, nbchar);
} else {
if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData,
tmp, nbchar);
if (*ctxt->space == -1)
*ctxt->space = -2;
}
line = ctxt->input->line;
col = ctxt->input->col;
} else if (ctxt->sax != NULL) {
if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData,
ctxt->input->cur, nbchar);
line = ctxt->input->line;
col = ctxt->input->col;
}
/* something really bad happened in the SAX callback */
if (ctxt->instate != XML_PARSER_CONTENT)
return;
}
ctxt->input->cur = in;
if (*in == 0xD) {
in++;
if (*in == 0xA) {
ctxt->input->cur = in;
in++;
ctxt->input->line++; ctxt->input->col = 1;
continue; /* while */
}
in--;
}
if (*in == '<') {
return;
}
if (*in == '&') {
return;
}
SHRINK;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return;
in = ctxt->input->cur;
} while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09));
nbchar = 0;
}
ctxt->input->line = line;
ctxt->input->col = col;
xmlParseCharDataComplex(ctxt, cdata);
}
/**
* xmlParseCharDataComplex:
* @ctxt: an XML parser context
* @cdata: int indicating whether we are within a CDATA section
*
* parse a CharData section.this is the fallback function
* of xmlParseCharData() when the parsing requires handling
* of non-ASCII characters.
*/
static void
xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int cdata) {
xmlChar buf[XML_PARSER_BIG_BUFFER_SIZE + 5];
int nbchar = 0;
int cur, l;
int count = 0;
SHRINK;
GROW;
cur = CUR_CHAR(l);
while ((cur != '<') && /* checked */
(cur != '&') &&
(IS_CHAR(cur))) /* test also done in xmlCurrentChar() */ {
if ((cur == ']') && (NXT(1) == ']') &&
(NXT(2) == '>')) {
if (cdata) break;
else {
xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL);
}
}
COPY_BUF(l,buf,nbchar,cur);
if (nbchar >= XML_PARSER_BIG_BUFFER_SIZE) {
buf[nbchar] = 0;
/*
* OK the segment is to be consumed as chars.
*/
if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) {
if (areBlanks(ctxt, buf, nbchar, 0)) {
if (ctxt->sax->ignorableWhitespace != NULL)
ctxt->sax->ignorableWhitespace(ctxt->userData,
buf, nbchar);
} else {
if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData, buf, nbchar);
if ((ctxt->sax->characters !=
ctxt->sax->ignorableWhitespace) &&
(*ctxt->space == -1))
*ctxt->space = -2;
}
}
nbchar = 0;
/* something really bad happened in the SAX callback */
if (ctxt->instate != XML_PARSER_CONTENT)
return;
}
count++;
if (count > 50) {
GROW;
count = 0;
if (ctxt->instate == XML_PARSER_EOF)
return;
}
NEXTL(l);
cur = CUR_CHAR(l);
}
if (nbchar != 0) {
buf[nbchar] = 0;
/*
* OK the segment is to be consumed as chars.
*/
if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) {
if (areBlanks(ctxt, buf, nbchar, 0)) {
if (ctxt->sax->ignorableWhitespace != NULL)
ctxt->sax->ignorableWhitespace(ctxt->userData, buf, nbchar);
} else {
if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData, buf, nbchar);
if ((ctxt->sax->characters != ctxt->sax->ignorableWhitespace) &&
(*ctxt->space == -1))
*ctxt->space = -2;
}
}
}
if ((cur != 0) && (!IS_CHAR(cur))) {
/* Generate the error and skip the offending character */
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"PCDATA invalid Char value %d\n",
cur);
NEXTL(l);
}
}
/**
* xmlParseExternalID:
* @ctxt: an XML parser context
* @publicID: a xmlChar** receiving PubidLiteral
* @strict: indicate whether we should restrict parsing to only
* production [75], see NOTE below
*
* Parse an External ID or a Public ID
*
* NOTE: Productions [75] and [83] interact badly since [75] can generate
* 'PUBLIC' S PubidLiteral S SystemLiteral
*
* [75] ExternalID ::= 'SYSTEM' S SystemLiteral
* | 'PUBLIC' S PubidLiteral S SystemLiteral
*
* [83] PublicID ::= 'PUBLIC' S PubidLiteral
*
* Returns the function returns SystemLiteral and in the second
* case publicID receives PubidLiteral, is strict is off
* it is possible to return NULL and have publicID set.
*/
xmlChar *
xmlParseExternalID(xmlParserCtxtPtr ctxt, xmlChar **publicID, int strict) {
xmlChar *URI = NULL;
SHRINK;
*publicID = NULL;
if (CMP6(CUR_PTR, 'S', 'Y', 'S', 'T', 'E', 'M')) {
SKIP(6);
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'SYSTEM'\n");
}
SKIP_BLANKS;
URI = xmlParseSystemLiteral(ctxt);
if (URI == NULL) {
xmlFatalErr(ctxt, XML_ERR_URI_REQUIRED, NULL);
}
} else if (CMP6(CUR_PTR, 'P', 'U', 'B', 'L', 'I', 'C')) {
SKIP(6);
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'PUBLIC'\n");
}
SKIP_BLANKS;
*publicID = xmlParsePubidLiteral(ctxt);
if (*publicID == NULL) {
xmlFatalErr(ctxt, XML_ERR_PUBID_REQUIRED, NULL);
}
if (strict) {
/*
* We don't handle [83] so "S SystemLiteral" is required.
*/
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the Public Identifier\n");
}
} else {
/*
* We handle [83] so we return immediately, if
* "S SystemLiteral" is not detected. From a purely parsing
* point of view that's a nice mess.
*/
const xmlChar *ptr;
GROW;
ptr = CUR_PTR;
if (!IS_BLANK_CH(*ptr)) return(NULL);
while (IS_BLANK_CH(*ptr)) ptr++; /* TODO: dangerous, fix ! */
if ((*ptr != '\'') && (*ptr != '"')) return(NULL);
}
SKIP_BLANKS;
URI = xmlParseSystemLiteral(ctxt);
if (URI == NULL) {
xmlFatalErr(ctxt, XML_ERR_URI_REQUIRED, NULL);
}
}
return(URI);
}
/**
* xmlParseCommentComplex:
* @ctxt: an XML parser context
* @buf: the already parsed part of the buffer
* @len: number of bytes filles in the buffer
* @size: allocated size of the buffer
*
* Skip an XML (SGML) comment <!-- .... -->
* The spec says that "For compatibility, the string "--" (double-hyphen)
* must not occur within comments. "
* This is the slow routine in case the accelerator for ascii didn't work
*
* [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
*/
static void
xmlParseCommentComplex(xmlParserCtxtPtr ctxt, xmlChar *buf,
size_t len, size_t size) {
int q, ql;
int r, rl;
int cur, l;
size_t count = 0;
int inputid;
inputid = ctxt->input->id;
if (buf == NULL) {
len = 0;
size = XML_PARSER_BUFFER_SIZE;
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return;
}
}
GROW; /* Assure there's enough input data */
q = CUR_CHAR(ql);
if (q == 0)
goto not_terminated;
if (!IS_CHAR(q)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlParseComment: invalid xmlChar value %d\n",
q);
xmlFree (buf);
return;
}
NEXTL(ql);
r = CUR_CHAR(rl);
if (r == 0)
goto not_terminated;
if (!IS_CHAR(r)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlParseComment: invalid xmlChar value %d\n",
q);
xmlFree (buf);
return;
}
NEXTL(rl);
cur = CUR_CHAR(l);
if (cur == 0)
goto not_terminated;
while (IS_CHAR(cur) && /* checked */
((cur != '>') ||
(r != '-') || (q != '-'))) {
if ((r == '-') && (q == '-')) {
xmlFatalErr(ctxt, XML_ERR_HYPHEN_IN_COMMENT, NULL);
}
if ((len > XML_MAX_TEXT_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment too big found", NULL);
xmlFree (buf);
return;
}
if (len + 5 >= size) {
xmlChar *new_buf;
size_t new_size;
new_size = size * 2;
new_buf = (xmlChar *) xmlRealloc(buf, new_size);
if (new_buf == NULL) {
xmlFree (buf);
xmlErrMemory(ctxt, NULL);
return;
}
buf = new_buf;
size = new_size;
}
COPY_BUF(ql,buf,len,q);
q = r;
ql = rl;
r = cur;
rl = l;
count++;
if (count > 50) {
GROW;
count = 0;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return;
}
}
NEXTL(l);
cur = CUR_CHAR(l);
if (cur == 0) {
SHRINK;
GROW;
cur = CUR_CHAR(l);
}
}
buf[len] = 0;
if (cur == 0) {
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment not terminated \n<!--%.50s\n", buf);
} else if (!IS_CHAR(cur)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlParseComment: invalid xmlChar value %d\n",
cur);
} else {
if (inputid != ctxt->input->id) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Comment doesn't start and stop in the same entity\n");
}
NEXT;
if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->comment(ctxt->userData, buf);
}
xmlFree(buf);
return;
not_terminated:
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment not terminated\n", NULL);
xmlFree(buf);
return;
}
/**
* xmlParseComment:
* @ctxt: an XML parser context
*
* Skip an XML (SGML) comment <!-- .... -->
* The spec says that "For compatibility, the string "--" (double-hyphen)
* must not occur within comments. "
*
* [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
*/
void
xmlParseComment(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
size_t size = XML_PARSER_BUFFER_SIZE;
size_t len = 0;
xmlParserInputState state;
const xmlChar *in;
size_t nbchar = 0;
int ccol;
int inputid;
/*
* Check that there is a comment right here.
*/
if ((RAW != '<') || (NXT(1) != '!') ||
(NXT(2) != '-') || (NXT(3) != '-')) return;
state = ctxt->instate;
ctxt->instate = XML_PARSER_COMMENT;
inputid = ctxt->input->id;
SKIP(4);
SHRINK;
GROW;
/*
* Accelerated common case where input don't need to be
* modified before passing it to the handler.
*/
in = ctxt->input->cur;
do {
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
}
get_more:
ccol = ctxt->input->col;
while (((*in > '-') && (*in <= 0x7F)) ||
((*in >= 0x20) && (*in < '-')) ||
(*in == 0x09)) {
in++;
ccol++;
}
ctxt->input->col = ccol;
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
goto get_more;
}
nbchar = in - ctxt->input->cur;
/*
* save current set of data
*/
if (nbchar > 0) {
if ((ctxt->sax != NULL) &&
(ctxt->sax->comment != NULL)) {
if (buf == NULL) {
if ((*in == '-') && (in[1] == '-'))
size = nbchar + 1;
else
size = XML_PARSER_BUFFER_SIZE + nbchar;
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
ctxt->instate = state;
return;
}
len = 0;
} else if (len + nbchar + 1 >= size) {
xmlChar *new_buf;
size += len + nbchar + XML_PARSER_BUFFER_SIZE;
new_buf = (xmlChar *) xmlRealloc(buf,
size * sizeof(xmlChar));
if (new_buf == NULL) {
xmlFree (buf);
xmlErrMemory(ctxt, NULL);
ctxt->instate = state;
return;
}
buf = new_buf;
}
memcpy(&buf[len], ctxt->input->cur, nbchar);
len += nbchar;
buf[len] = 0;
}
}
if ((len > XML_MAX_TEXT_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment too big found", NULL);
xmlFree (buf);
return;
}
ctxt->input->cur = in;
if (*in == 0xA) {
in++;
ctxt->input->line++; ctxt->input->col = 1;
}
if (*in == 0xD) {
in++;
if (*in == 0xA) {
ctxt->input->cur = in;
in++;
ctxt->input->line++; ctxt->input->col = 1;
continue; /* while */
}
in--;
}
SHRINK;
GROW;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return;
}
in = ctxt->input->cur;
if (*in == '-') {
if (in[1] == '-') {
if (in[2] == '>') {
if (ctxt->input->id != inputid) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"comment doesn't start and stop in the same entity\n");
}
SKIP(3);
if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) &&
(!ctxt->disableSAX)) {
if (buf != NULL)
ctxt->sax->comment(ctxt->userData, buf);
else
ctxt->sax->comment(ctxt->userData, BAD_CAST "");
}
if (buf != NULL)
xmlFree(buf);
if (ctxt->instate != XML_PARSER_EOF)
ctxt->instate = state;
return;
}
if (buf != NULL) {
xmlFatalErrMsgStr(ctxt, XML_ERR_HYPHEN_IN_COMMENT,
"Double hyphen within comment: "
"<!--%.50s\n",
buf);
} else
xmlFatalErrMsgStr(ctxt, XML_ERR_HYPHEN_IN_COMMENT,
"Double hyphen within comment\n", NULL);
in++;
ctxt->input->col++;
}
in++;
ctxt->input->col++;
goto get_more;
}
} while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09));
xmlParseCommentComplex(ctxt, buf, len, size);
ctxt->instate = state;
return;
}
/**
* xmlParsePITarget:
* @ctxt: an XML parser context
*
* parse the name of a PI
*
* [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
*
* Returns the PITarget name or NULL
*/
const xmlChar *
xmlParsePITarget(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
name = xmlParseName(ctxt);
if ((name != NULL) &&
((name[0] == 'x') || (name[0] == 'X')) &&
((name[1] == 'm') || (name[1] == 'M')) &&
((name[2] == 'l') || (name[2] == 'L'))) {
int i;
if ((name[0] == 'x') && (name[1] == 'm') &&
(name[2] == 'l') && (name[3] == 0)) {
xmlFatalErrMsg(ctxt, XML_ERR_RESERVED_XML_NAME,
"XML declaration allowed only at the start of the document\n");
return(name);
} else if (name[3] == 0) {
xmlFatalErr(ctxt, XML_ERR_RESERVED_XML_NAME, NULL);
return(name);
}
for (i = 0;;i++) {
if (xmlW3CPIs[i] == NULL) break;
if (xmlStrEqual(name, (const xmlChar *)xmlW3CPIs[i]))
return(name);
}
xmlWarningMsg(ctxt, XML_ERR_RESERVED_XML_NAME,
"xmlParsePITarget: invalid name prefix 'xml'\n",
NULL, NULL);
}
if ((name != NULL) && (xmlStrchr(name, ':') != NULL)) {
xmlNsErr(ctxt, XML_NS_ERR_COLON,
"colons are forbidden from PI names '%s'\n", name, NULL, NULL);
}
return(name);
}
#ifdef LIBXML_CATALOG_ENABLED
/**
* xmlParseCatalogPI:
* @ctxt: an XML parser context
* @catalog: the PI value string
*
* parse an XML Catalog Processing Instruction.
*
* <?oasis-xml-catalog catalog="http://example.com/catalog.xml"?>
*
* Occurs only if allowed by the user and if happening in the Misc
* part of the document before any doctype informations
* This will add the given catalog to the parsing context in order
* to be used if there is a resolution need further down in the document
*/
static void
xmlParseCatalogPI(xmlParserCtxtPtr ctxt, const xmlChar *catalog) {
xmlChar *URL = NULL;
const xmlChar *tmp, *base;
xmlChar marker;
tmp = catalog;
while (IS_BLANK_CH(*tmp)) tmp++;
if (xmlStrncmp(tmp, BAD_CAST"catalog", 7))
goto error;
tmp += 7;
while (IS_BLANK_CH(*tmp)) tmp++;
if (*tmp != '=') {
return;
}
tmp++;
while (IS_BLANK_CH(*tmp)) tmp++;
marker = *tmp;
if ((marker != '\'') && (marker != '"'))
goto error;
tmp++;
base = tmp;
while ((*tmp != 0) && (*tmp != marker)) tmp++;
if (*tmp == 0)
goto error;
URL = xmlStrndup(base, tmp - base);
tmp++;
while (IS_BLANK_CH(*tmp)) tmp++;
if (*tmp != 0)
goto error;
if (URL != NULL) {
ctxt->catalogs = xmlCatalogAddLocal(ctxt->catalogs, URL);
xmlFree(URL);
}
return;
error:
xmlWarningMsg(ctxt, XML_WAR_CATALOG_PI,
"Catalog PI syntax error: %s\n",
catalog, NULL);
if (URL != NULL)
xmlFree(URL);
}
#endif
/**
* xmlParsePI:
* @ctxt: an XML parser context
*
* parse an XML Processing Instruction.
*
* [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
*
* The processing is transfered to SAX once parsed.
*/
void
xmlParsePI(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
size_t len = 0;
size_t size = XML_PARSER_BUFFER_SIZE;
int cur, l;
const xmlChar *target;
xmlParserInputState state;
int count = 0;
if ((RAW == '<') && (NXT(1) == '?')) {
xmlParserInputPtr input = ctxt->input;
state = ctxt->instate;
ctxt->instate = XML_PARSER_PI;
/*
* this is a Processing Instruction.
*/
SKIP(2);
SHRINK;
/*
* Parse the target name and check for special support like
* namespace.
*/
target = xmlParsePITarget(ctxt);
if (target != NULL) {
if ((RAW == '?') && (NXT(1) == '>')) {
if (input != ctxt->input) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"PI declaration doesn't start and stop in the same entity\n");
}
SKIP(2);
/*
* SAX: PI detected.
*/
if ((ctxt->sax) && (!ctxt->disableSAX) &&
(ctxt->sax->processingInstruction != NULL))
ctxt->sax->processingInstruction(ctxt->userData,
target, NULL);
if (ctxt->instate != XML_PARSER_EOF)
ctxt->instate = state;
return;
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
ctxt->instate = state;
return;
}
cur = CUR;
if (!IS_BLANK(cur)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED,
"ParsePI: PI %s space expected\n", target);
}
SKIP_BLANKS;
cur = CUR_CHAR(l);
while (IS_CHAR(cur) && /* checked */
((cur != '?') || (NXT(1) != '>'))) {
if (len + 5 >= size) {
xmlChar *tmp;
size_t new_size = size * 2;
tmp = (xmlChar *) xmlRealloc(buf, new_size);
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buf);
ctxt->instate = state;
return;
}
buf = tmp;
size = new_size;
}
count++;
if (count > 50) {
GROW;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return;
}
count = 0;
if ((len > XML_MAX_TEXT_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED,
"PI %s too big found", target);
xmlFree(buf);
ctxt->instate = state;
return;
}
}
COPY_BUF(l,buf,len,cur);
NEXTL(l);
cur = CUR_CHAR(l);
if (cur == 0) {
SHRINK;
GROW;
cur = CUR_CHAR(l);
}
}
if ((len > XML_MAX_TEXT_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED,
"PI %s too big found", target);
xmlFree(buf);
ctxt->instate = state;
return;
}
buf[len] = 0;
if (cur != '?') {
xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED,
"ParsePI: PI %s never end ...\n", target);
} else {
if (input != ctxt->input) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"PI declaration doesn't start and stop in the same entity\n");
}
SKIP(2);
#ifdef LIBXML_CATALOG_ENABLED
if (((state == XML_PARSER_MISC) ||
(state == XML_PARSER_START)) &&
(xmlStrEqual(target, XML_CATALOG_PI))) {
xmlCatalogAllow allow = xmlCatalogGetDefaults();
if ((allow == XML_CATA_ALLOW_DOCUMENT) ||
(allow == XML_CATA_ALLOW_ALL))
xmlParseCatalogPI(ctxt, buf);
}
#endif
/*
* SAX: PI detected.
*/
if ((ctxt->sax) && (!ctxt->disableSAX) &&
(ctxt->sax->processingInstruction != NULL))
ctxt->sax->processingInstruction(ctxt->userData,
target, buf);
}
xmlFree(buf);
} else {
xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL);
}
if (ctxt->instate != XML_PARSER_EOF)
ctxt->instate = state;
}
}
/**
* xmlParseNotationDecl:
* @ctxt: an XML parser context
*
* parse a notation declaration
*
* [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>'
*
* Hence there is actually 3 choices:
* 'PUBLIC' S PubidLiteral
* 'PUBLIC' S PubidLiteral S SystemLiteral
* and 'SYSTEM' S SystemLiteral
*
* See the NOTE on xmlParseExternalID().
*/
void
xmlParseNotationDecl(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
xmlChar *Pubid;
xmlChar *Systemid;
if (CMP10(CUR_PTR, '<', '!', 'N', 'O', 'T', 'A', 'T', 'I', 'O', 'N')) {
xmlParserInputPtr input = ctxt->input;
SHRINK;
SKIP(10);
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '<!NOTATION'\n");
return;
}
SKIP_BLANKS;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_STARTED, NULL);
return;
}
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the NOTATION name'\n");
return;
}
if (xmlStrchr(name, ':') != NULL) {
xmlNsErr(ctxt, XML_NS_ERR_COLON,
"colons are forbidden from notation names '%s'\n",
name, NULL, NULL);
}
SKIP_BLANKS;
/*
* Parse the IDs.
*/
Systemid = xmlParseExternalID(ctxt, &Pubid, 0);
SKIP_BLANKS;
if (RAW == '>') {
if (input != ctxt->input) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Notation declaration doesn't start and stop in the same entity\n");
}
NEXT;
if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
(ctxt->sax->notationDecl != NULL))
ctxt->sax->notationDecl(ctxt->userData, name, Pubid, Systemid);
} else {
xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_FINISHED, NULL);
}
if (Systemid != NULL) xmlFree(Systemid);
if (Pubid != NULL) xmlFree(Pubid);
}
}
/**
* xmlParseEntityDecl:
* @ctxt: an XML parser context
*
* parse <!ENTITY declarations
*
* [70] EntityDecl ::= GEDecl | PEDecl
*
* [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
*
* [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
*
* [73] EntityDef ::= EntityValue | (ExternalID NDataDecl?)
*
* [74] PEDef ::= EntityValue | ExternalID
*
* [76] NDataDecl ::= S 'NDATA' S Name
*
* [ VC: Notation Declared ]
* The Name must match the declared name of a notation.
*/
void
xmlParseEntityDecl(xmlParserCtxtPtr ctxt) {
const xmlChar *name = NULL;
xmlChar *value = NULL;
xmlChar *URI = NULL, *literal = NULL;
const xmlChar *ndata = NULL;
int isParameter = 0;
xmlChar *orig = NULL;
int skipped;
/* GROW; done in the caller */
if (CMP8(CUR_PTR, '<', '!', 'E', 'N', 'T', 'I', 'T', 'Y')) {
xmlParserInputPtr input = ctxt->input;
SHRINK;
SKIP(8);
skipped = SKIP_BLANKS;
if (skipped == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '<!ENTITY'\n");
}
if (RAW == '%') {
NEXT;
skipped = SKIP_BLANKS;
if (skipped == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '%%'\n");
}
isParameter = 1;
}
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseEntityDecl: no name\n");
return;
}
if (xmlStrchr(name, ':') != NULL) {
xmlNsErr(ctxt, XML_NS_ERR_COLON,
"colons are forbidden from entities names '%s'\n",
name, NULL, NULL);
}
skipped = SKIP_BLANKS;
if (skipped == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the entity name\n");
}
ctxt->instate = XML_PARSER_ENTITY_DECL;
/*
* handle the various case of definitions...
*/
if (isParameter) {
if ((RAW == '"') || (RAW == '\'')) {
value = xmlParseEntityValue(ctxt, &orig);
if (value) {
if ((ctxt->sax != NULL) &&
(!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL))
ctxt->sax->entityDecl(ctxt->userData, name,
XML_INTERNAL_PARAMETER_ENTITY,
NULL, NULL, value);
}
} else {
URI = xmlParseExternalID(ctxt, &literal, 1);
if ((URI == NULL) && (literal == NULL)) {
xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL);
}
if (URI) {
xmlURIPtr uri;
uri = xmlParseURI((const char *) URI);
if (uri == NULL) {
xmlErrMsgStr(ctxt, XML_ERR_INVALID_URI,
"Invalid URI: %s\n", URI);
/*
* This really ought to be a well formedness error
* but the XML Core WG decided otherwise c.f. issue
* E26 of the XML erratas.
*/
} else {
if (uri->fragment != NULL) {
/*
* Okay this is foolish to block those but not
* invalid URIs.
*/
xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL);
} else {
if ((ctxt->sax != NULL) &&
(!ctxt->disableSAX) &&
(ctxt->sax->entityDecl != NULL))
ctxt->sax->entityDecl(ctxt->userData, name,
XML_EXTERNAL_PARAMETER_ENTITY,
literal, URI, NULL);
}
xmlFreeURI(uri);
}
}
}
} else {
if ((RAW == '"') || (RAW == '\'')) {
value = xmlParseEntityValue(ctxt, &orig);
if ((ctxt->sax != NULL) &&
(!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL))
ctxt->sax->entityDecl(ctxt->userData, name,
XML_INTERNAL_GENERAL_ENTITY,
NULL, NULL, value);
/*
* For expat compatibility in SAX mode.
*/
if ((ctxt->myDoc == NULL) ||
(xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) {
if (ctxt->myDoc == NULL) {
ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE);
if (ctxt->myDoc == NULL) {
xmlErrMemory(ctxt, "New Doc failed");
return;
}
ctxt->myDoc->properties = XML_DOC_INTERNAL;
}
if (ctxt->myDoc->intSubset == NULL)
ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc,
BAD_CAST "fake", NULL, NULL);
xmlSAX2EntityDecl(ctxt, name, XML_INTERNAL_GENERAL_ENTITY,
NULL, NULL, value);
}
} else {
URI = xmlParseExternalID(ctxt, &literal, 1);
if ((URI == NULL) && (literal == NULL)) {
xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL);
}
if (URI) {
xmlURIPtr uri;
uri = xmlParseURI((const char *)URI);
if (uri == NULL) {
xmlErrMsgStr(ctxt, XML_ERR_INVALID_URI,
"Invalid URI: %s\n", URI);
/*
* This really ought to be a well formedness error
* but the XML Core WG decided otherwise c.f. issue
* E26 of the XML erratas.
*/
} else {
if (uri->fragment != NULL) {
/*
* Okay this is foolish to block those but not
* invalid URIs.
*/
xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL);
}
xmlFreeURI(uri);
}
}
if ((RAW != '>') && (!IS_BLANK_CH(CUR))) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required before 'NDATA'\n");
}
SKIP_BLANKS;
if (CMP5(CUR_PTR, 'N', 'D', 'A', 'T', 'A')) {
SKIP(5);
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'NDATA'\n");
}
SKIP_BLANKS;
ndata = xmlParseName(ctxt);
if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
(ctxt->sax->unparsedEntityDecl != NULL))
ctxt->sax->unparsedEntityDecl(ctxt->userData, name,
literal, URI, ndata);
} else {
if ((ctxt->sax != NULL) &&
(!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL))
ctxt->sax->entityDecl(ctxt->userData, name,
XML_EXTERNAL_GENERAL_PARSED_ENTITY,
literal, URI, NULL);
/*
* For expat compatibility in SAX mode.
* assuming the entity repalcement was asked for
*/
if ((ctxt->replaceEntities != 0) &&
((ctxt->myDoc == NULL) ||
(xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE)))) {
if (ctxt->myDoc == NULL) {
ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE);
if (ctxt->myDoc == NULL) {
xmlErrMemory(ctxt, "New Doc failed");
return;
}
ctxt->myDoc->properties = XML_DOC_INTERNAL;
}
if (ctxt->myDoc->intSubset == NULL)
ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc,
BAD_CAST "fake", NULL, NULL);
xmlSAX2EntityDecl(ctxt, name,
XML_EXTERNAL_GENERAL_PARSED_ENTITY,
literal, URI, NULL);
}
}
}
}
if (ctxt->instate == XML_PARSER_EOF)
return;
SKIP_BLANKS;
if (RAW != '>') {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_NOT_FINISHED,
"xmlParseEntityDecl: entity %s not terminated\n", name);
xmlHaltParser(ctxt);
} else {
if (input != ctxt->input) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Entity declaration doesn't start and stop in the same entity\n");
}
NEXT;
}
if (orig != NULL) {
/*
* Ugly mechanism to save the raw entity value.
*/
xmlEntityPtr cur = NULL;
if (isParameter) {
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
cur = ctxt->sax->getParameterEntity(ctxt->userData, name);
} else {
if ((ctxt->sax != NULL) &&
(ctxt->sax->getEntity != NULL))
cur = ctxt->sax->getEntity(ctxt->userData, name);
if ((cur == NULL) && (ctxt->userData==ctxt)) {
cur = xmlSAX2GetEntity(ctxt, name);
}
}
if (cur != NULL) {
if (cur->orig != NULL)
xmlFree(orig);
else
cur->orig = orig;
} else
xmlFree(orig);
}
if (value != NULL) xmlFree(value);
if (URI != NULL) xmlFree(URI);
if (literal != NULL) xmlFree(literal);
}
}
/**
* xmlParseDefaultDecl:
* @ctxt: an XML parser context
* @value: Receive a possible fixed default value for the attribute
*
* Parse an attribute default declaration
*
* [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)
*
* [ VC: Required Attribute ]
* if the default declaration is the keyword #REQUIRED, then the
* attribute must be specified for all elements of the type in the
* attribute-list declaration.
*
* [ VC: Attribute Default Legal ]
* The declared default value must meet the lexical constraints of
* the declared attribute type c.f. xmlValidateAttributeDecl()
*
* [ VC: Fixed Attribute Default ]
* if an attribute has a default value declared with the #FIXED
* keyword, instances of that attribute must match the default value.
*
* [ WFC: No < in Attribute Values ]
* handled in xmlParseAttValue()
*
* returns: XML_ATTRIBUTE_NONE, XML_ATTRIBUTE_REQUIRED, XML_ATTRIBUTE_IMPLIED
* or XML_ATTRIBUTE_FIXED.
*/
int
xmlParseDefaultDecl(xmlParserCtxtPtr ctxt, xmlChar **value) {
int val;
xmlChar *ret;
*value = NULL;
if (CMP9(CUR_PTR, '#', 'R', 'E', 'Q', 'U', 'I', 'R', 'E', 'D')) {
SKIP(9);
return(XML_ATTRIBUTE_REQUIRED);
}
if (CMP8(CUR_PTR, '#', 'I', 'M', 'P', 'L', 'I', 'E', 'D')) {
SKIP(8);
return(XML_ATTRIBUTE_IMPLIED);
}
val = XML_ATTRIBUTE_NONE;
if (CMP6(CUR_PTR, '#', 'F', 'I', 'X', 'E', 'D')) {
SKIP(6);
val = XML_ATTRIBUTE_FIXED;
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '#FIXED'\n");
}
SKIP_BLANKS;
}
ret = xmlParseAttValue(ctxt);
ctxt->instate = XML_PARSER_DTD;
if (ret == NULL) {
xmlFatalErrMsg(ctxt, (xmlParserErrors)ctxt->errNo,
"Attribute default value declaration error\n");
} else
*value = ret;
return(val);
}
/**
* xmlParseNotationType:
* @ctxt: an XML parser context
*
* parse an Notation attribute type.
*
* Note: the leading 'NOTATION' S part has already being parsed...
*
* [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
*
* [ VC: Notation Attributes ]
* Values of this type must match one of the notation names included
* in the declaration; all notation names in the declaration must be declared.
*
* Returns: the notation attribute tree built while parsing
*/
xmlEnumerationPtr
xmlParseNotationType(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
xmlEnumerationPtr ret = NULL, last = NULL, cur, tmp;
if (RAW != '(') {
xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_STARTED, NULL);
return(NULL);
}
SHRINK;
do {
NEXT;
SKIP_BLANKS;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"Name expected in NOTATION declaration\n");
xmlFreeEnumeration(ret);
return(NULL);
}
tmp = ret;
while (tmp != NULL) {
if (xmlStrEqual(name, tmp->name)) {
xmlValidityError(ctxt, XML_DTD_DUP_TOKEN,
"standalone: attribute notation value token %s duplicated\n",
name, NULL);
if (!xmlDictOwns(ctxt->dict, name))
xmlFree((xmlChar *) name);
break;
}
tmp = tmp->next;
}
if (tmp == NULL) {
cur = xmlCreateEnumeration(name);
if (cur == NULL) {
xmlFreeEnumeration(ret);
return(NULL);
}
if (last == NULL) ret = last = cur;
else {
last->next = cur;
last = cur;
}
}
SKIP_BLANKS;
} while (RAW == '|');
if (RAW != ')') {
xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_FINISHED, NULL);
xmlFreeEnumeration(ret);
return(NULL);
}
NEXT;
return(ret);
}
/**
* xmlParseEnumerationType:
* @ctxt: an XML parser context
*
* parse an Enumeration attribute type.
*
* [59] Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')'
*
* [ VC: Enumeration ]
* Values of this type must match one of the Nmtoken tokens in
* the declaration
*
* Returns: the enumeration attribute tree built while parsing
*/
xmlEnumerationPtr
xmlParseEnumerationType(xmlParserCtxtPtr ctxt) {
xmlChar *name;
xmlEnumerationPtr ret = NULL, last = NULL, cur, tmp;
if (RAW != '(') {
xmlFatalErr(ctxt, XML_ERR_ATTLIST_NOT_STARTED, NULL);
return(NULL);
}
SHRINK;
do {
NEXT;
SKIP_BLANKS;
name = xmlParseNmtoken(ctxt);
if (name == NULL) {
xmlFatalErr(ctxt, XML_ERR_NMTOKEN_REQUIRED, NULL);
return(ret);
}
tmp = ret;
while (tmp != NULL) {
if (xmlStrEqual(name, tmp->name)) {
xmlValidityError(ctxt, XML_DTD_DUP_TOKEN,
"standalone: attribute enumeration value token %s duplicated\n",
name, NULL);
if (!xmlDictOwns(ctxt->dict, name))
xmlFree(name);
break;
}
tmp = tmp->next;
}
if (tmp == NULL) {
cur = xmlCreateEnumeration(name);
if (!xmlDictOwns(ctxt->dict, name))
xmlFree(name);
if (cur == NULL) {
xmlFreeEnumeration(ret);
return(NULL);
}
if (last == NULL) ret = last = cur;
else {
last->next = cur;
last = cur;
}
}
SKIP_BLANKS;
} while (RAW == '|');
if (RAW != ')') {
xmlFatalErr(ctxt, XML_ERR_ATTLIST_NOT_FINISHED, NULL);
return(ret);
}
NEXT;
return(ret);
}
/**
* xmlParseEnumeratedType:
* @ctxt: an XML parser context
* @tree: the enumeration tree built while parsing
*
* parse an Enumerated attribute type.
*
* [57] EnumeratedType ::= NotationType | Enumeration
*
* [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
*
*
* Returns: XML_ATTRIBUTE_ENUMERATION or XML_ATTRIBUTE_NOTATION
*/
int
xmlParseEnumeratedType(xmlParserCtxtPtr ctxt, xmlEnumerationPtr *tree) {
if (CMP8(CUR_PTR, 'N', 'O', 'T', 'A', 'T', 'I', 'O', 'N')) {
SKIP(8);
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'NOTATION'\n");
return(0);
}
SKIP_BLANKS;
*tree = xmlParseNotationType(ctxt);
if (*tree == NULL) return(0);
return(XML_ATTRIBUTE_NOTATION);
}
*tree = xmlParseEnumerationType(ctxt);
if (*tree == NULL) return(0);
return(XML_ATTRIBUTE_ENUMERATION);
}
/**
* xmlParseAttributeType:
* @ctxt: an XML parser context
* @tree: the enumeration tree built while parsing
*
* parse the Attribute list def for an element
*
* [54] AttType ::= StringType | TokenizedType | EnumeratedType
*
* [55] StringType ::= 'CDATA'
*
* [56] TokenizedType ::= 'ID' | 'IDREF' | 'IDREFS' | 'ENTITY' |
* 'ENTITIES' | 'NMTOKEN' | 'NMTOKENS'
*
* Validity constraints for attribute values syntax are checked in
* xmlValidateAttributeValue()
*
* [ VC: ID ]
* Values of type ID must match the Name production. A name must not
* appear more than once in an XML document as a value of this type;
* i.e., ID values must uniquely identify the elements which bear them.
*
* [ VC: One ID per Element Type ]
* No element type may have more than one ID attribute specified.
*
* [ VC: ID Attribute Default ]
* An ID attribute must have a declared default of #IMPLIED or #REQUIRED.
*
* [ VC: IDREF ]
* Values of type IDREF must match the Name production, and values
* of type IDREFS must match Names; each IDREF Name must match the value
* of an ID attribute on some element in the XML document; i.e. IDREF
* values must match the value of some ID attribute.
*
* [ VC: Entity Name ]
* Values of type ENTITY must match the Name production, values
* of type ENTITIES must match Names; each Entity Name must match the
* name of an unparsed entity declared in the DTD.
*
* [ VC: Name Token ]
* Values of type NMTOKEN must match the Nmtoken production; values
* of type NMTOKENS must match Nmtokens.
*
* Returns the attribute type
*/
int
xmlParseAttributeType(xmlParserCtxtPtr ctxt, xmlEnumerationPtr *tree) {
SHRINK;
if (CMP5(CUR_PTR, 'C', 'D', 'A', 'T', 'A')) {
SKIP(5);
return(XML_ATTRIBUTE_CDATA);
} else if (CMP6(CUR_PTR, 'I', 'D', 'R', 'E', 'F', 'S')) {
SKIP(6);
return(XML_ATTRIBUTE_IDREFS);
} else if (CMP5(CUR_PTR, 'I', 'D', 'R', 'E', 'F')) {
SKIP(5);
return(XML_ATTRIBUTE_IDREF);
} else if ((RAW == 'I') && (NXT(1) == 'D')) {
SKIP(2);
return(XML_ATTRIBUTE_ID);
} else if (CMP6(CUR_PTR, 'E', 'N', 'T', 'I', 'T', 'Y')) {
SKIP(6);
return(XML_ATTRIBUTE_ENTITY);
} else if (CMP8(CUR_PTR, 'E', 'N', 'T', 'I', 'T', 'I', 'E', 'S')) {
SKIP(8);
return(XML_ATTRIBUTE_ENTITIES);
} else if (CMP8(CUR_PTR, 'N', 'M', 'T', 'O', 'K', 'E', 'N', 'S')) {
SKIP(8);
return(XML_ATTRIBUTE_NMTOKENS);
} else if (CMP7(CUR_PTR, 'N', 'M', 'T', 'O', 'K', 'E', 'N')) {
SKIP(7);
return(XML_ATTRIBUTE_NMTOKEN);
}
return(xmlParseEnumeratedType(ctxt, tree));
}
/**
* xmlParseAttributeListDecl:
* @ctxt: an XML parser context
*
* : parse the Attribute list def for an element
*
* [52] AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>'
*
* [53] AttDef ::= S Name S AttType S DefaultDecl
*
*/
void
xmlParseAttributeListDecl(xmlParserCtxtPtr ctxt) {
const xmlChar *elemName;
const xmlChar *attrName;
xmlEnumerationPtr tree;
if (CMP9(CUR_PTR, '<', '!', 'A', 'T', 'T', 'L', 'I', 'S', 'T')) {
xmlParserInputPtr input = ctxt->input;
SKIP(9);
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '<!ATTLIST'\n");
}
SKIP_BLANKS;
elemName = xmlParseName(ctxt);
if (elemName == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"ATTLIST: no name for Element\n");
return;
}
SKIP_BLANKS;
GROW;
while ((RAW != '>') && (ctxt->instate != XML_PARSER_EOF)) {
const xmlChar *check = CUR_PTR;
int type;
int def;
xmlChar *defaultValue = NULL;
GROW;
tree = NULL;
attrName = xmlParseName(ctxt);
if (attrName == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"ATTLIST: no name for Attribute\n");
break;
}
GROW;
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute name\n");
break;
}
SKIP_BLANKS;
type = xmlParseAttributeType(ctxt, &tree);
if (type <= 0) {
break;
}
GROW;
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute type\n");
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
SKIP_BLANKS;
def = xmlParseDefaultDecl(ctxt, &defaultValue);
if (def <= 0) {
if (defaultValue != NULL)
xmlFree(defaultValue);
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
if ((type != XML_ATTRIBUTE_CDATA) && (defaultValue != NULL))
xmlAttrNormalizeSpace(defaultValue, defaultValue);
GROW;
if (RAW != '>') {
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute default value\n");
if (defaultValue != NULL)
xmlFree(defaultValue);
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
SKIP_BLANKS;
}
if (check == CUR_PTR) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"in xmlParseAttributeListDecl\n");
if (defaultValue != NULL)
xmlFree(defaultValue);
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
(ctxt->sax->attributeDecl != NULL))
ctxt->sax->attributeDecl(ctxt->userData, elemName, attrName,
type, def, defaultValue, tree);
else if (tree != NULL)
xmlFreeEnumeration(tree);
if ((ctxt->sax2) && (defaultValue != NULL) &&
(def != XML_ATTRIBUTE_IMPLIED) &&
(def != XML_ATTRIBUTE_REQUIRED)) {
xmlAddDefAttrs(ctxt, elemName, attrName, defaultValue);
}
if (ctxt->sax2) {
xmlAddSpecialAttr(ctxt, elemName, attrName, type);
}
if (defaultValue != NULL)
xmlFree(defaultValue);
GROW;
}
if (RAW == '>') {
if (input != ctxt->input) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Attribute list declaration doesn't start and stop in the same entity\n",
NULL, NULL);
}
NEXT;
}
}
}
/**
* xmlParseElementMixedContentDecl:
* @ctxt: an XML parser context
* @inputchk: the input used for the current entity, needed for boundary checks
*
* parse the declaration for a Mixed Element content
* The leading '(' and spaces have been skipped in xmlParseElementContentDecl
*
* [51] Mixed ::= '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' |
* '(' S? '#PCDATA' S? ')'
*
* [ VC: Proper Group/PE Nesting ] applies to [51] too (see [49])
*
* [ VC: No Duplicate Types ]
* The same name must not appear more than once in a single
* mixed-content declaration.
*
* returns: the list of the xmlElementContentPtr describing the element choices
*/
xmlElementContentPtr
xmlParseElementMixedContentDecl(xmlParserCtxtPtr ctxt, int inputchk) {
xmlElementContentPtr ret = NULL, cur = NULL, n;
const xmlChar *elem = NULL;
GROW;
if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) {
SKIP(7);
SKIP_BLANKS;
SHRINK;
if (RAW == ')') {
if ((ctxt->validate) && (ctxt->input->id != inputchk)) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Element content declaration doesn't start and stop in the same entity\n",
NULL, NULL);
}
NEXT;
ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA);
if (ret == NULL)
return(NULL);
if (RAW == '*') {
ret->ocur = XML_ELEMENT_CONTENT_MULT;
NEXT;
}
return(ret);
}
if ((RAW == '(') || (RAW == '|')) {
ret = cur = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA);
if (ret == NULL) return(NULL);
}
while ((RAW == '|') && (ctxt->instate != XML_PARSER_EOF)) {
NEXT;
if (elem == NULL) {
ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR);
if (ret == NULL) return(NULL);
ret->c1 = cur;
if (cur != NULL)
cur->parent = ret;
cur = ret;
} else {
n = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR);
if (n == NULL) return(NULL);
n->c1 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT);
if (n->c1 != NULL)
n->c1->parent = n;
cur->c2 = n;
if (n != NULL)
n->parent = cur;
cur = n;
}
SKIP_BLANKS;
elem = xmlParseName(ctxt);
if (elem == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseElementMixedContentDecl : Name expected\n");
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
SKIP_BLANKS;
GROW;
}
if ((RAW == ')') && (NXT(1) == '*')) {
if (elem != NULL) {
cur->c2 = xmlNewDocElementContent(ctxt->myDoc, elem,
XML_ELEMENT_CONTENT_ELEMENT);
if (cur->c2 != NULL)
cur->c2->parent = cur;
}
if (ret != NULL)
ret->ocur = XML_ELEMENT_CONTENT_MULT;
if ((ctxt->validate) && (ctxt->input->id != inputchk)) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Element content declaration doesn't start and stop in the same entity\n",
NULL, NULL);
}
SKIP(2);
} else {
xmlFreeDocElementContent(ctxt->myDoc, ret);
xmlFatalErr(ctxt, XML_ERR_MIXED_NOT_STARTED, NULL);
return(NULL);
}
} else {
xmlFatalErr(ctxt, XML_ERR_PCDATA_REQUIRED, NULL);
}
return(ret);
}
/**
* xmlParseElementChildrenContentDeclPriv:
* @ctxt: an XML parser context
* @inputchk: the input used for the current entity, needed for boundary checks
* @depth: the level of recursion
*
* parse the declaration for a Mixed Element content
* The leading '(' and spaces have been skipped in xmlParseElementContentDecl
*
*
* [47] children ::= (choice | seq) ('?' | '*' | '+')?
*
* [48] cp ::= (Name | choice | seq) ('?' | '*' | '+')?
*
* [49] choice ::= '(' S? cp ( S? '|' S? cp )* S? ')'
*
* [50] seq ::= '(' S? cp ( S? ',' S? cp )* S? ')'
*
* [ VC: Proper Group/PE Nesting ] applies to [49] and [50]
* TODO Parameter-entity replacement text must be properly nested
* with parenthesized groups. That is to say, if either of the
* opening or closing parentheses in a choice, seq, or Mixed
* construct is contained in the replacement text for a parameter
* entity, both must be contained in the same replacement text. For
* interoperability, if a parameter-entity reference appears in a
* choice, seq, or Mixed construct, its replacement text should not
* be empty, and neither the first nor last non-blank character of
* the replacement text should be a connector (| or ,).
*
* Returns the tree of xmlElementContentPtr describing the element
* hierarchy.
*/
static xmlElementContentPtr
xmlParseElementChildrenContentDeclPriv(xmlParserCtxtPtr ctxt, int inputchk,
int depth) {
xmlElementContentPtr ret = NULL, cur = NULL, last = NULL, op = NULL;
const xmlChar *elem;
xmlChar type = 0;
if (((depth > 128) && ((ctxt->options & XML_PARSE_HUGE) == 0)) ||
(depth > 2048)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_ELEMCONTENT_NOT_FINISHED,
"xmlParseElementChildrenContentDecl : depth %d too deep, use XML_PARSE_HUGE\n",
depth);
return(NULL);
}
SKIP_BLANKS;
GROW;
if (RAW == '(') {
int inputid = ctxt->input->id;
/* Recurse on first child */
NEXT;
SKIP_BLANKS;
cur = ret = xmlParseElementChildrenContentDeclPriv(ctxt, inputid,
depth + 1);
SKIP_BLANKS;
GROW;
} else {
elem = xmlParseName(ctxt);
if (elem == NULL) {
xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, NULL);
return(NULL);
}
cur = ret = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT);
if (cur == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
GROW;
if (RAW == '?') {
cur->ocur = XML_ELEMENT_CONTENT_OPT;
NEXT;
} else if (RAW == '*') {
cur->ocur = XML_ELEMENT_CONTENT_MULT;
NEXT;
} else if (RAW == '+') {
cur->ocur = XML_ELEMENT_CONTENT_PLUS;
NEXT;
} else {
cur->ocur = XML_ELEMENT_CONTENT_ONCE;
}
GROW;
}
SKIP_BLANKS;
SHRINK;
while ((RAW != ')') && (ctxt->instate != XML_PARSER_EOF)) {
/*
* Each loop we parse one separator and one element.
*/
if (RAW == ',') {
if (type == 0) type = CUR;
/*
* Detect "Name | Name , Name" error
*/
else if (type != CUR) {
xmlFatalErrMsgInt(ctxt, XML_ERR_SEPARATOR_REQUIRED,
"xmlParseElementChildrenContentDecl : '%c' expected\n",
type);
if ((last != NULL) && (last != ret))
xmlFreeDocElementContent(ctxt->myDoc, last);
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
NEXT;
op = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_SEQ);
if (op == NULL) {
if ((last != NULL) && (last != ret))
xmlFreeDocElementContent(ctxt->myDoc, last);
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
if (last == NULL) {
op->c1 = ret;
if (ret != NULL)
ret->parent = op;
ret = cur = op;
} else {
cur->c2 = op;
if (op != NULL)
op->parent = cur;
op->c1 = last;
if (last != NULL)
last->parent = op;
cur =op;
last = NULL;
}
} else if (RAW == '|') {
if (type == 0) type = CUR;
/*
* Detect "Name , Name | Name" error
*/
else if (type != CUR) {
xmlFatalErrMsgInt(ctxt, XML_ERR_SEPARATOR_REQUIRED,
"xmlParseElementChildrenContentDecl : '%c' expected\n",
type);
if ((last != NULL) && (last != ret))
xmlFreeDocElementContent(ctxt->myDoc, last);
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
NEXT;
op = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR);
if (op == NULL) {
if ((last != NULL) && (last != ret))
xmlFreeDocElementContent(ctxt->myDoc, last);
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
if (last == NULL) {
op->c1 = ret;
if (ret != NULL)
ret->parent = op;
ret = cur = op;
} else {
cur->c2 = op;
if (op != NULL)
op->parent = cur;
op->c1 = last;
if (last != NULL)
last->parent = op;
cur =op;
last = NULL;
}
} else {
xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_FINISHED, NULL);
if ((last != NULL) && (last != ret))
xmlFreeDocElementContent(ctxt->myDoc, last);
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
GROW;
SKIP_BLANKS;
GROW;
if (RAW == '(') {
int inputid = ctxt->input->id;
/* Recurse on second child */
NEXT;
SKIP_BLANKS;
last = xmlParseElementChildrenContentDeclPriv(ctxt, inputid,
depth + 1);
SKIP_BLANKS;
} else {
elem = xmlParseName(ctxt);
if (elem == NULL) {
xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, NULL);
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
last = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT);
if (last == NULL) {
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
if (RAW == '?') {
last->ocur = XML_ELEMENT_CONTENT_OPT;
NEXT;
} else if (RAW == '*') {
last->ocur = XML_ELEMENT_CONTENT_MULT;
NEXT;
} else if (RAW == '+') {
last->ocur = XML_ELEMENT_CONTENT_PLUS;
NEXT;
} else {
last->ocur = XML_ELEMENT_CONTENT_ONCE;
}
}
SKIP_BLANKS;
GROW;
}
if ((cur != NULL) && (last != NULL)) {
cur->c2 = last;
if (last != NULL)
last->parent = cur;
}
if ((ctxt->validate) && (ctxt->input->id != inputchk)) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Element content declaration doesn't start and stop in the same entity\n",
NULL, NULL);
}
NEXT;
if (RAW == '?') {
if (ret != NULL) {
if ((ret->ocur == XML_ELEMENT_CONTENT_PLUS) ||
(ret->ocur == XML_ELEMENT_CONTENT_MULT))
ret->ocur = XML_ELEMENT_CONTENT_MULT;
else
ret->ocur = XML_ELEMENT_CONTENT_OPT;
}
NEXT;
} else if (RAW == '*') {
if (ret != NULL) {
ret->ocur = XML_ELEMENT_CONTENT_MULT;
cur = ret;
/*
* Some normalization:
* (a | b* | c?)* == (a | b | c)*
*/
while ((cur != NULL) && (cur->type == XML_ELEMENT_CONTENT_OR)) {
if ((cur->c1 != NULL) &&
((cur->c1->ocur == XML_ELEMENT_CONTENT_OPT) ||
(cur->c1->ocur == XML_ELEMENT_CONTENT_MULT)))
cur->c1->ocur = XML_ELEMENT_CONTENT_ONCE;
if ((cur->c2 != NULL) &&
((cur->c2->ocur == XML_ELEMENT_CONTENT_OPT) ||
(cur->c2->ocur == XML_ELEMENT_CONTENT_MULT)))
cur->c2->ocur = XML_ELEMENT_CONTENT_ONCE;
cur = cur->c2;
}
}
NEXT;
} else if (RAW == '+') {
if (ret != NULL) {
int found = 0;
if ((ret->ocur == XML_ELEMENT_CONTENT_OPT) ||
(ret->ocur == XML_ELEMENT_CONTENT_MULT))
ret->ocur = XML_ELEMENT_CONTENT_MULT;
else
ret->ocur = XML_ELEMENT_CONTENT_PLUS;
/*
* Some normalization:
* (a | b*)+ == (a | b)*
* (a | b?)+ == (a | b)*
*/
while ((cur != NULL) && (cur->type == XML_ELEMENT_CONTENT_OR)) {
if ((cur->c1 != NULL) &&
((cur->c1->ocur == XML_ELEMENT_CONTENT_OPT) ||
(cur->c1->ocur == XML_ELEMENT_CONTENT_MULT))) {
cur->c1->ocur = XML_ELEMENT_CONTENT_ONCE;
found = 1;
}
if ((cur->c2 != NULL) &&
((cur->c2->ocur == XML_ELEMENT_CONTENT_OPT) ||
(cur->c2->ocur == XML_ELEMENT_CONTENT_MULT))) {
cur->c2->ocur = XML_ELEMENT_CONTENT_ONCE;
found = 1;
}
cur = cur->c2;
}
if (found)
ret->ocur = XML_ELEMENT_CONTENT_MULT;
}
NEXT;
}
return(ret);
}
/**
* xmlParseElementChildrenContentDecl:
* @ctxt: an XML parser context
* @inputchk: the input used for the current entity, needed for boundary checks
*
* parse the declaration for a Mixed Element content
* The leading '(' and spaces have been skipped in xmlParseElementContentDecl
*
* [47] children ::= (choice | seq) ('?' | '*' | '+')?
*
* [48] cp ::= (Name | choice | seq) ('?' | '*' | '+')?
*
* [49] choice ::= '(' S? cp ( S? '|' S? cp )* S? ')'
*
* [50] seq ::= '(' S? cp ( S? ',' S? cp )* S? ')'
*
* [ VC: Proper Group/PE Nesting ] applies to [49] and [50]
* TODO Parameter-entity replacement text must be properly nested
* with parenthesized groups. That is to say, if either of the
* opening or closing parentheses in a choice, seq, or Mixed
* construct is contained in the replacement text for a parameter
* entity, both must be contained in the same replacement text. For
* interoperability, if a parameter-entity reference appears in a
* choice, seq, or Mixed construct, its replacement text should not
* be empty, and neither the first nor last non-blank character of
* the replacement text should be a connector (| or ,).
*
* Returns the tree of xmlElementContentPtr describing the element
* hierarchy.
*/
xmlElementContentPtr
xmlParseElementChildrenContentDecl(xmlParserCtxtPtr ctxt, int inputchk) {
/* stub left for API/ABI compat */
return(xmlParseElementChildrenContentDeclPriv(ctxt, inputchk, 1));
}
/**
* xmlParseElementContentDecl:
* @ctxt: an XML parser context
* @name: the name of the element being defined.
* @result: the Element Content pointer will be stored here if any
*
* parse the declaration for an Element content either Mixed or Children,
* the cases EMPTY and ANY are handled directly in xmlParseElementDecl
*
* [46] contentspec ::= 'EMPTY' | 'ANY' | Mixed | children
*
* returns: the type of element content XML_ELEMENT_TYPE_xxx
*/
int
xmlParseElementContentDecl(xmlParserCtxtPtr ctxt, const xmlChar *name,
xmlElementContentPtr *result) {
xmlElementContentPtr tree = NULL;
int inputid = ctxt->input->id;
int res;
*result = NULL;
if (RAW != '(') {
xmlFatalErrMsgStr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED,
"xmlParseElementContentDecl : %s '(' expected\n", name);
return(-1);
}
NEXT;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
SKIP_BLANKS;
if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) {
tree = xmlParseElementMixedContentDecl(ctxt, inputid);
res = XML_ELEMENT_TYPE_MIXED;
} else {
tree = xmlParseElementChildrenContentDeclPriv(ctxt, inputid, 1);
res = XML_ELEMENT_TYPE_ELEMENT;
}
SKIP_BLANKS;
*result = tree;
return(res);
}
/**
* xmlParseElementDecl:
* @ctxt: an XML parser context
*
* parse an Element declaration.
*
* [45] elementdecl ::= '<!ELEMENT' S Name S contentspec S? '>'
*
* [ VC: Unique Element Type Declaration ]
* No element type may be declared more than once
*
* Returns the type of the element, or -1 in case of error
*/
int
xmlParseElementDecl(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
int ret = -1;
xmlElementContentPtr content = NULL;
/* GROW; done in the caller */
if (CMP9(CUR_PTR, '<', '!', 'E', 'L', 'E', 'M', 'E', 'N', 'T')) {
xmlParserInputPtr input = ctxt->input;
SKIP(9);
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'ELEMENT'\n");
return(-1);
}
SKIP_BLANKS;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseElementDecl: no name for Element\n");
return(-1);
}
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the element name\n");
}
SKIP_BLANKS;
if (CMP5(CUR_PTR, 'E', 'M', 'P', 'T', 'Y')) {
SKIP(5);
/*
* Element must always be empty.
*/
ret = XML_ELEMENT_TYPE_EMPTY;
} else if ((RAW == 'A') && (NXT(1) == 'N') &&
(NXT(2) == 'Y')) {
SKIP(3);
/*
* Element is a generic container.
*/
ret = XML_ELEMENT_TYPE_ANY;
} else if (RAW == '(') {
ret = xmlParseElementContentDecl(ctxt, name, &content);
} else {
/*
* [ WFC: PEs in Internal Subset ] error handling.
*/
if ((RAW == '%') && (ctxt->external == 0) &&
(ctxt->inputNr == 1)) {
xmlFatalErrMsg(ctxt, XML_ERR_PEREF_IN_INT_SUBSET,
"PEReference: forbidden within markup decl in internal subset\n");
} else {
xmlFatalErrMsg(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED,
"xmlParseElementDecl: 'EMPTY', 'ANY' or '(' expected\n");
}
return(-1);
}
SKIP_BLANKS;
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
SKIP_BLANKS;
if (RAW != '>') {
xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL);
if (content != NULL) {
xmlFreeDocElementContent(ctxt->myDoc, content);
}
} else {
if (input != ctxt->input) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Element declaration doesn't start and stop in the same entity\n");
}
NEXT;
if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
(ctxt->sax->elementDecl != NULL)) {
if (content != NULL)
content->parent = NULL;
ctxt->sax->elementDecl(ctxt->userData, name, ret,
content);
if ((content != NULL) && (content->parent == NULL)) {
/*
* this is a trick: if xmlAddElementDecl is called,
* instead of copying the full tree it is plugged directly
* if called from the parser. Avoid duplicating the
* interfaces or change the API/ABI
*/
xmlFreeDocElementContent(ctxt->myDoc, content);
}
} else if (content != NULL) {
xmlFreeDocElementContent(ctxt->myDoc, content);
}
}
}
return(ret);
}
/**
* xmlParseConditionalSections
* @ctxt: an XML parser context
*
* [61] conditionalSect ::= includeSect | ignoreSect
* [62] includeSect ::= '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>'
* [63] ignoreSect ::= '<![' S? 'IGNORE' S? '[' ignoreSectContents* ']]>'
* [64] ignoreSectContents ::= Ignore ('<![' ignoreSectContents ']]>' Ignore)*
* [65] Ignore ::= Char* - (Char* ('<![' | ']]>') Char*)
*/
static void
xmlParseConditionalSections(xmlParserCtxtPtr ctxt) {
int id = ctxt->input->id;
SKIP(3);
SKIP_BLANKS;
if (CMP7(CUR_PTR, 'I', 'N', 'C', 'L', 'U', 'D', 'E')) {
SKIP(7);
SKIP_BLANKS;
if (RAW != '[') {
xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
xmlHaltParser(ctxt);
return;
} else {
if (ctxt->input->id != id) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"All markup of the conditional section is not in the same entity\n",
NULL, NULL);
}
NEXT;
}
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Entering INCLUDE Conditional Section\n");
}
while (((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') ||
(NXT(2) != '>'))) && (ctxt->instate != XML_PARSER_EOF)) {
const xmlChar *check = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
xmlParseConditionalSections(ctxt);
} else if (IS_BLANK_CH(CUR)) {
NEXT;
} else if (RAW == '%') {
xmlParsePEReference(ctxt);
} else
xmlParseMarkupDecl(ctxt);
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) {
xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL);
xmlHaltParser(ctxt);
break;
}
}
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Leaving INCLUDE Conditional Section\n");
}
} else if (CMP6(CUR_PTR, 'I', 'G', 'N', 'O', 'R', 'E')) {
int state;
xmlParserInputState instate;
int depth = 0;
SKIP(6);
SKIP_BLANKS;
if (RAW != '[') {
xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
xmlHaltParser(ctxt);
return;
} else {
if (ctxt->input->id != id) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"All markup of the conditional section is not in the same entity\n",
NULL, NULL);
}
NEXT;
}
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Entering IGNORE Conditional Section\n");
}
/*
* Parse up to the end of the conditional section
* But disable SAX event generating DTD building in the meantime
*/
state = ctxt->disableSAX;
instate = ctxt->instate;
if (ctxt->recovery == 0) ctxt->disableSAX = 1;
ctxt->instate = XML_PARSER_IGNORE;
while (((depth >= 0) && (RAW != 0)) &&
(ctxt->instate != XML_PARSER_EOF)) {
if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
depth++;
SKIP(3);
continue;
}
if ((RAW == ']') && (NXT(1) == ']') && (NXT(2) == '>')) {
if (--depth >= 0) SKIP(3);
continue;
}
NEXT;
continue;
}
ctxt->disableSAX = state;
ctxt->instate = instate;
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Leaving IGNORE Conditional Section\n");
}
} else {
xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID_KEYWORD, NULL);
xmlHaltParser(ctxt);
return;
}
if (RAW == 0)
SHRINK;
if (RAW == 0) {
xmlFatalErr(ctxt, XML_ERR_CONDSEC_NOT_FINISHED, NULL);
} else {
if (ctxt->input->id != id) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"All markup of the conditional section is not in the same entity\n",
NULL, NULL);
}
if ((ctxt-> instate != XML_PARSER_EOF) &&
((ctxt->input->cur + 3) <= ctxt->input->end))
SKIP(3);
}
}
/**
* xmlParseMarkupDecl:
* @ctxt: an XML parser context
*
* parse Markup declarations
*
* [29] markupdecl ::= elementdecl | AttlistDecl | EntityDecl |
* NotationDecl | PI | Comment
*
* [ VC: Proper Declaration/PE Nesting ]
* Parameter-entity replacement text must be properly nested with
* markup declarations. That is to say, if either the first character
* or the last character of a markup declaration (markupdecl above) is
* contained in the replacement text for a parameter-entity reference,
* both must be contained in the same replacement text.
*
* [ WFC: PEs in Internal Subset ]
* In the internal DTD subset, parameter-entity references can occur
* only where markup declarations can occur, not within markup declarations.
* (This does not apply to references that occur in external parameter
* entities or to the external subset.)
*/
void
xmlParseMarkupDecl(xmlParserCtxtPtr ctxt) {
GROW;
if (CUR == '<') {
if (NXT(1) == '!') {
switch (NXT(2)) {
case 'E':
if (NXT(3) == 'L')
xmlParseElementDecl(ctxt);
else if (NXT(3) == 'N')
xmlParseEntityDecl(ctxt);
break;
case 'A':
xmlParseAttributeListDecl(ctxt);
break;
case 'N':
xmlParseNotationDecl(ctxt);
break;
case '-':
xmlParseComment(ctxt);
break;
default:
/* there is an error but it will be detected later */
break;
}
} else if (NXT(1) == '?') {
xmlParsePI(ctxt);
}
}
/*
* detect requirement to exit there and act accordingly
* and avoid having instate overriden later on
*/
if (ctxt->instate == XML_PARSER_EOF)
return;
/*
* This is only for internal subset. On external entities,
* the replacement is done before parsing stage
*/
if ((ctxt->external == 0) && (ctxt->inputNr == 1))
xmlParsePEReference(ctxt);
/*
* Conditional sections are allowed from entities included
* by PE References in the internal subset.
*/
if ((ctxt->external == 0) && (ctxt->inputNr > 1)) {
if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
xmlParseConditionalSections(ctxt);
}
}
ctxt->instate = XML_PARSER_DTD;
}
/**
* xmlParseTextDecl:
* @ctxt: an XML parser context
*
* parse an XML declaration header for external entities
*
* [77] TextDecl ::= '<?xml' VersionInfo? EncodingDecl S? '?>'
*/
void
xmlParseTextDecl(xmlParserCtxtPtr ctxt) {
xmlChar *version;
const xmlChar *encoding;
/*
* We know that '<?xml' is here.
*/
if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
SKIP(5);
} else {
xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_STARTED, NULL);
return;
}
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space needed after '<?xml'\n");
}
SKIP_BLANKS;
/*
* We may have the VersionInfo here.
*/
version = xmlParseVersionInfo(ctxt);
if (version == NULL)
version = xmlCharStrdup(XML_DEFAULT_VERSION);
else {
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space needed here\n");
}
}
ctxt->input->version = version;
/*
* We must have the encoding declaration
*/
encoding = xmlParseEncodingDecl(ctxt);
if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing right here
*/
return;
}
if ((encoding == NULL) && (ctxt->errNo == XML_ERR_OK)) {
xmlFatalErrMsg(ctxt, XML_ERR_MISSING_ENCODING,
"Missing encoding in text declaration\n");
}
SKIP_BLANKS;
if ((RAW == '?') && (NXT(1) == '>')) {
SKIP(2);
} else if (RAW == '>') {
/* Deprecated old WD ... */
xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL);
NEXT;
} else {
xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL);
MOVETO_ENDTAG(CUR_PTR);
NEXT;
}
}
/**
* xmlParseExternalSubset:
* @ctxt: an XML parser context
* @ExternalID: the external identifier
* @SystemID: the system identifier (or URL)
*
* parse Markup declarations from an external subset
*
* [30] extSubset ::= textDecl? extSubsetDecl
*
* [31] extSubsetDecl ::= (markupdecl | conditionalSect | PEReference | S) *
*/
void
xmlParseExternalSubset(xmlParserCtxtPtr ctxt, const xmlChar *ExternalID,
const xmlChar *SystemID) {
xmlDetectSAX2(ctxt);
GROW;
if ((ctxt->encoding == NULL) &&
(ctxt->input->end - ctxt->input->cur >= 4)) {
xmlChar start[4];
xmlCharEncoding enc;
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE)
xmlSwitchEncoding(ctxt, enc);
}
if (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) {
xmlParseTextDecl(ctxt);
if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing right here
*/
xmlHaltParser(ctxt);
return;
}
}
if (ctxt->myDoc == NULL) {
ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0");
if (ctxt->myDoc == NULL) {
xmlErrMemory(ctxt, "New Doc failed");
return;
}
ctxt->myDoc->properties = XML_DOC_INTERNAL;
}
if ((ctxt->myDoc != NULL) && (ctxt->myDoc->intSubset == NULL))
xmlCreateIntSubset(ctxt->myDoc, NULL, ExternalID, SystemID);
ctxt->instate = XML_PARSER_DTD;
ctxt->external = 1;
while (((RAW == '<') && (NXT(1) == '?')) ||
((RAW == '<') && (NXT(1) == '!')) ||
(RAW == '%') || IS_BLANK_CH(CUR)) {
const xmlChar *check = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
GROW;
if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
xmlParseConditionalSections(ctxt);
} else if (IS_BLANK_CH(CUR)) {
NEXT;
} else if (RAW == '%') {
xmlParsePEReference(ctxt);
} else
xmlParseMarkupDecl(ctxt);
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) {
xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL);
break;
}
}
if (RAW != 0) {
xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL);
}
}
/**
* xmlParseReference:
* @ctxt: an XML parser context
*
* parse and handle entity references in content, depending on the SAX
* interface, this may end-up in a call to character() if this is a
* CharRef, a predefined entity, if there is no reference() callback.
* or if the parser was asked to switch to that mode.
*
* [67] Reference ::= EntityRef | CharRef
*/
void
xmlParseReference(xmlParserCtxtPtr ctxt) {
xmlEntityPtr ent;
xmlChar *val;
int was_checked;
xmlNodePtr list = NULL;
xmlParserErrors ret = XML_ERR_OK;
if (RAW != '&')
return;
/*
* Simple case of a CharRef
*/
if (NXT(1) == '#') {
int i = 0;
xmlChar out[10];
int hex = NXT(2);
int value = xmlParseCharRef(ctxt);
if (value == 0)
return;
if (ctxt->charset != XML_CHAR_ENCODING_UTF8) {
/*
* So we are using non-UTF-8 buffers
* Check that the char fit on 8bits, if not
* generate a CharRef.
*/
if (value <= 0xFF) {
out[0] = value;
out[1] = 0;
if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->characters(ctxt->userData, out, 1);
} else {
if ((hex == 'x') || (hex == 'X'))
snprintf((char *)out, sizeof(out), "#x%X", value);
else
snprintf((char *)out, sizeof(out), "#%d", value);
if ((ctxt->sax != NULL) && (ctxt->sax->reference != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->reference(ctxt->userData, out);
}
} else {
/*
* Just encode the value in UTF-8
*/
COPY_BUF(0 ,out, i, value);
out[i] = 0;
if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->characters(ctxt->userData, out, i);
}
return;
}
/*
* We are seeing an entity reference
*/
ent = xmlParseEntityRef(ctxt);
if (ent == NULL) return;
if (!ctxt->wellFormed)
return;
was_checked = ent->checked;
/* special case of predefined entities */
if ((ent->name == NULL) ||
(ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
val = ent->content;
if (val == NULL) return;
/*
* inline the entity.
*/
if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->characters(ctxt->userData, val, xmlStrlen(val));
return;
}
/*
* The first reference to the entity trigger a parsing phase
* where the ent->children is filled with the result from
* the parsing.
* Note: external parsed entities will not be loaded, it is not
* required for a non-validating parser, unless the parsing option
* of validating, or substituting entities were given. Doing so is
* far more secure as the parser will only process data coming from
* the document entity by default.
*/
if (((ent->checked == 0) ||
((ent->children == NULL) && (ctxt->options & XML_PARSE_NOENT))) &&
((ent->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY) ||
(ctxt->options & (XML_PARSE_NOENT | XML_PARSE_DTDVALID)))) {
unsigned long oldnbent = ctxt->nbentities;
/*
* This is a bit hackish but this seems the best
* way to make sure both SAX and DOM entity support
* behaves okay.
*/
void *user_data;
if (ctxt->userData == ctxt)
user_data = NULL;
else
user_data = ctxt->userData;
/*
* Check that this entity is well formed
* 4.3.2: An internal general parsed entity is well-formed
* if its replacement text matches the production labeled
* content.
*/
if (ent->etype == XML_INTERNAL_GENERAL_ENTITY) {
ctxt->depth++;
ret = xmlParseBalancedChunkMemoryInternal(ctxt, ent->content,
user_data, &list);
ctxt->depth--;
} else if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY) {
ctxt->depth++;
ret = xmlParseExternalEntityPrivate(ctxt->myDoc, ctxt, ctxt->sax,
user_data, ctxt->depth, ent->URI,
ent->ExternalID, &list);
ctxt->depth--;
} else {
ret = XML_ERR_ENTITY_PE_INTERNAL;
xmlErrMsgStr(ctxt, XML_ERR_INTERNAL_ERROR,
"invalid entity type found\n", NULL);
}
/*
* Store the number of entities needing parsing for this entity
* content and do checkings
*/
ent->checked = (ctxt->nbentities - oldnbent + 1) * 2;
if ((ent->content != NULL) && (xmlStrchr(ent->content, '<')))
ent->checked |= 1;
if (ret == XML_ERR_ENTITY_LOOP) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
xmlFreeNodeList(list);
return;
}
if (xmlParserEntityCheck(ctxt, 0, ent, 0)) {
xmlFreeNodeList(list);
return;
}
if ((ret == XML_ERR_OK) && (list != NULL)) {
if (((ent->etype == XML_INTERNAL_GENERAL_ENTITY) ||
(ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY))&&
(ent->children == NULL)) {
ent->children = list;
if (ctxt->replaceEntities) {
/*
* Prune it directly in the generated document
* except for single text nodes.
*/
if (((list->type == XML_TEXT_NODE) &&
(list->next == NULL)) ||
(ctxt->parseMode == XML_PARSE_READER)) {
list->parent = (xmlNodePtr) ent;
list = NULL;
ent->owner = 1;
} else {
ent->owner = 0;
while (list != NULL) {
list->parent = (xmlNodePtr) ctxt->node;
list->doc = ctxt->myDoc;
if (list->next == NULL)
ent->last = list;
list = list->next;
}
list = ent->children;
#ifdef LIBXML_LEGACY_ENABLED
if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)
xmlAddEntityReference(ent, list, NULL);
#endif /* LIBXML_LEGACY_ENABLED */
}
} else {
ent->owner = 1;
while (list != NULL) {
list->parent = (xmlNodePtr) ent;
xmlSetTreeDoc(list, ent->doc);
if (list->next == NULL)
ent->last = list;
list = list->next;
}
}
} else {
xmlFreeNodeList(list);
list = NULL;
}
} else if ((ret != XML_ERR_OK) &&
(ret != XML_WAR_UNDECLARED_ENTITY)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"Entity '%s' failed to parse\n", ent->name);
xmlParserEntityCheck(ctxt, 0, ent, 0);
} else if (list != NULL) {
xmlFreeNodeList(list);
list = NULL;
}
if (ent->checked == 0)
ent->checked = 2;
} else if (ent->checked != 1) {
ctxt->nbentities += ent->checked / 2;
}
/*
* Now that the entity content has been gathered
* provide it to the application, this can take different forms based
* on the parsing modes.
*/
if (ent->children == NULL) {
/*
* Probably running in SAX mode and the callbacks don't
* build the entity content. So unless we already went
* though parsing for first checking go though the entity
* content to generate callbacks associated to the entity
*/
if (was_checked != 0) {
void *user_data;
/*
* This is a bit hackish but this seems the best
* way to make sure both SAX and DOM entity support
* behaves okay.
*/
if (ctxt->userData == ctxt)
user_data = NULL;
else
user_data = ctxt->userData;
if (ent->etype == XML_INTERNAL_GENERAL_ENTITY) {
ctxt->depth++;
ret = xmlParseBalancedChunkMemoryInternal(ctxt,
ent->content, user_data, NULL);
ctxt->depth--;
} else if (ent->etype ==
XML_EXTERNAL_GENERAL_PARSED_ENTITY) {
ctxt->depth++;
ret = xmlParseExternalEntityPrivate(ctxt->myDoc, ctxt,
ctxt->sax, user_data, ctxt->depth,
ent->URI, ent->ExternalID, NULL);
ctxt->depth--;
} else {
ret = XML_ERR_ENTITY_PE_INTERNAL;
xmlErrMsgStr(ctxt, XML_ERR_INTERNAL_ERROR,
"invalid entity type found\n", NULL);
}
if (ret == XML_ERR_ENTITY_LOOP) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
return;
}
}
if ((ctxt->sax != NULL) && (ctxt->sax->reference != NULL) &&
(ctxt->replaceEntities == 0) && (!ctxt->disableSAX)) {
/*
* Entity reference callback comes second, it's somewhat
* superfluous but a compatibility to historical behaviour
*/
ctxt->sax->reference(ctxt->userData, ent->name);
}
return;
}
/*
* If we didn't get any children for the entity being built
*/
if ((ctxt->sax != NULL) && (ctxt->sax->reference != NULL) &&
(ctxt->replaceEntities == 0) && (!ctxt->disableSAX)) {
/*
* Create a node.
*/
ctxt->sax->reference(ctxt->userData, ent->name);
return;
}
if ((ctxt->replaceEntities) || (ent->children == NULL)) {
/*
* There is a problem on the handling of _private for entities
* (bug 155816): Should we copy the content of the field from
* the entity (possibly overwriting some value set by the user
* when a copy is created), should we leave it alone, or should
* we try to take care of different situations? The problem
* is exacerbated by the usage of this field by the xmlReader.
* To fix this bug, we look at _private on the created node
* and, if it's NULL, we copy in whatever was in the entity.
* If it's not NULL we leave it alone. This is somewhat of a
* hack - maybe we should have further tests to determine
* what to do.
*/
if ((ctxt->node != NULL) && (ent->children != NULL)) {
/*
* Seems we are generating the DOM content, do
* a simple tree copy for all references except the first
* In the first occurrence list contains the replacement.
*/
if (((list == NULL) && (ent->owner == 0)) ||
(ctxt->parseMode == XML_PARSE_READER)) {
xmlNodePtr nw = NULL, cur, firstChild = NULL;
/*
* We are copying here, make sure there is no abuse
*/
ctxt->sizeentcopy += ent->length + 5;
if (xmlParserEntityCheck(ctxt, 0, ent, ctxt->sizeentcopy))
return;
/*
* when operating on a reader, the entities definitions
* are always owning the entities subtree.
if (ctxt->parseMode == XML_PARSE_READER)
ent->owner = 1;
*/
cur = ent->children;
while (cur != NULL) {
nw = xmlDocCopyNode(cur, ctxt->myDoc, 1);
if (nw != NULL) {
if (nw->_private == NULL)
nw->_private = cur->_private;
if (firstChild == NULL){
firstChild = nw;
}
nw = xmlAddChild(ctxt->node, nw);
}
if (cur == ent->last) {
/*
* needed to detect some strange empty
* node cases in the reader tests
*/
if ((ctxt->parseMode == XML_PARSE_READER) &&
(nw != NULL) &&
(nw->type == XML_ELEMENT_NODE) &&
(nw->children == NULL))
nw->extra = 1;
break;
}
cur = cur->next;
}
#ifdef LIBXML_LEGACY_ENABLED
if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)
xmlAddEntityReference(ent, firstChild, nw);
#endif /* LIBXML_LEGACY_ENABLED */
} else if ((list == NULL) || (ctxt->inputNr > 0)) {
xmlNodePtr nw = NULL, cur, next, last,
firstChild = NULL;
/*
* We are copying here, make sure there is no abuse
*/
ctxt->sizeentcopy += ent->length + 5;
if (xmlParserEntityCheck(ctxt, 0, ent, ctxt->sizeentcopy))
return;
/*
* Copy the entity child list and make it the new
* entity child list. The goal is to make sure any
* ID or REF referenced will be the one from the
* document content and not the entity copy.
*/
cur = ent->children;
ent->children = NULL;
last = ent->last;
ent->last = NULL;
while (cur != NULL) {
next = cur->next;
cur->next = NULL;
cur->parent = NULL;
nw = xmlDocCopyNode(cur, ctxt->myDoc, 1);
if (nw != NULL) {
if (nw->_private == NULL)
nw->_private = cur->_private;
if (firstChild == NULL){
firstChild = cur;
}
xmlAddChild((xmlNodePtr) ent, nw);
xmlAddChild(ctxt->node, cur);
}
if (cur == last)
break;
cur = next;
}
if (ent->owner == 0)
ent->owner = 1;
#ifdef LIBXML_LEGACY_ENABLED
if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)
xmlAddEntityReference(ent, firstChild, nw);
#endif /* LIBXML_LEGACY_ENABLED */
} else {
const xmlChar *nbktext;
/*
* the name change is to avoid coalescing of the
* node with a possible previous text one which
* would make ent->children a dangling pointer
*/
nbktext = xmlDictLookup(ctxt->dict, BAD_CAST "nbktext",
-1);
if (ent->children->type == XML_TEXT_NODE)
ent->children->name = nbktext;
if ((ent->last != ent->children) &&
(ent->last->type == XML_TEXT_NODE))
ent->last->name = nbktext;
xmlAddChildList(ctxt->node, ent->children);
}
/*
* This is to avoid a nasty side effect, see
* characters() in SAX.c
*/
ctxt->nodemem = 0;
ctxt->nodelen = 0;
return;
}
}
}
/**
* xmlParseEntityRef:
* @ctxt: an XML parser context
*
* parse ENTITY references declarations
*
* [68] EntityRef ::= '&' Name ';'
*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an internal DTD
* subset which contains no parameter entity references, or a document
* with "standalone='yes'", the Name given in the entity reference
* must match that in an entity declaration, except that well-formed
* documents need not declare any of the following entities: amp, lt,
* gt, apos, quot. The declaration of a parameter entity must precede
* any reference to it. Similarly, the declaration of a general entity
* must precede any reference to it which appears in a default value in an
* attribute-list declaration. Note that if entities are declared in the
* external subset or in external parameter entities, a non-validating
* processor is not obligated to read and process their declarations;
* for such documents, the rule that an entity must be declared is a
* well-formedness constraint only if standalone='yes'.
*
* [ WFC: Parsed Entity ]
* An entity reference must not contain the name of an unparsed entity
*
* Returns the xmlEntityPtr if found, or NULL otherwise.
*/
xmlEntityPtr
xmlParseEntityRef(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
xmlEntityPtr ent = NULL;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
if (RAW != '&')
return(NULL);
NEXT;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseEntityRef: no name\n");
return(NULL);
}
if (RAW != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
return(NULL);
}
NEXT;
/*
* Predefined entities override any extra definition
*/
if ((ctxt->options & XML_PARSE_OLDSAX) == 0) {
ent = xmlGetPredefinedEntity(name);
if (ent != NULL)
return(ent);
}
/*
* Increase the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Ask first SAX for entity resolution, otherwise try the
* entities which may have stored in the parser context.
*/
if (ctxt->sax != NULL) {
if (ctxt->sax->getEntity != NULL)
ent = ctxt->sax->getEntity(ctxt->userData, name);
if ((ctxt->wellFormed == 1 ) && (ent == NULL) &&
(ctxt->options & XML_PARSE_OLDSAX))
ent = xmlGetPredefinedEntity(name);
if ((ctxt->wellFormed == 1 ) && (ent == NULL) &&
(ctxt->userData==ctxt)) {
ent = xmlSAX2GetEntity(ctxt, name);
}
}
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", the
* Name given in the entity reference must match that in an
* entity declaration, except that well-formed documents
* need not declare any of the following entities: amp, lt,
* gt, apos, quot.
* The declaration of a parameter entity must precede any
* reference to it.
* Similarly, the declaration of a general entity must
* precede any reference to it which appears in a default
* value in an attribute-list declaration. Note that if
* entities are declared in the external subset or in
* external parameter entities, a non-validating processor
* is not obligated to read and process their declarations;
* for such documents, the rule that an entity must be
* declared is a well-formedness constraint only if
* standalone='yes'.
*/
if (ent == NULL) {
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"Entity '%s' not defined\n", name);
} else {
xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Entity '%s' not defined\n", name);
if ((ctxt->inSubset == 0) &&
(ctxt->sax != NULL) &&
(ctxt->sax->reference != NULL)) {
ctxt->sax->reference(ctxt->userData, name);
}
}
xmlParserEntityCheck(ctxt, 0, ent, 0);
ctxt->valid = 0;
}
/*
* [ WFC: Parsed Entity ]
* An entity reference must not contain the name of an
* unparsed entity
*/
else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY,
"Entity reference to unparsed entity %s\n", name);
}
/*
* [ WFC: No External Entity References ]
* Attribute values cannot contain direct or indirect
* entity references to external entities.
*/
else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
(ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL,
"Attribute references external entity '%s'\n", name);
}
/*
* [ WFC: No < in Attribute Values ]
* The replacement text of any entity referred to directly or
* indirectly in an attribute value (other than "<") must
* not contain a <.
*/
else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
(ent != NULL) &&
(ent->etype != XML_INTERNAL_PREDEFINED_ENTITY)) {
if (((ent->checked & 1) || (ent->checked == 0)) &&
(ent->content != NULL) && (xmlStrchr(ent->content, '<'))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
"'<' in entity '%s' is not allowed in attributes values\n", name);
}
}
/*
* Internal check, no parameter entities here ...
*/
else {
switch (ent->etype) {
case XML_INTERNAL_PARAMETER_ENTITY:
case XML_EXTERNAL_PARAMETER_ENTITY:
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
"Attempt to reference the parameter entity '%s'\n",
name);
break;
default:
break;
}
}
/*
* [ WFC: No Recursion ]
* A parsed entity must not contain a recursive reference
* to itself, either directly or indirectly.
* Done somewhere else
*/
return(ent);
}
/**
* xmlParseStringEntityRef:
* @ctxt: an XML parser context
* @str: a pointer to an index in the string
*
* parse ENTITY references declarations, but this version parses it from
* a string value.
*
* [68] EntityRef ::= '&' Name ';'
*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an internal DTD
* subset which contains no parameter entity references, or a document
* with "standalone='yes'", the Name given in the entity reference
* must match that in an entity declaration, except that well-formed
* documents need not declare any of the following entities: amp, lt,
* gt, apos, quot. The declaration of a parameter entity must precede
* any reference to it. Similarly, the declaration of a general entity
* must precede any reference to it which appears in a default value in an
* attribute-list declaration. Note that if entities are declared in the
* external subset or in external parameter entities, a non-validating
* processor is not obligated to read and process their declarations;
* for such documents, the rule that an entity must be declared is a
* well-formedness constraint only if standalone='yes'.
*
* [ WFC: Parsed Entity ]
* An entity reference must not contain the name of an unparsed entity
*
* Returns the xmlEntityPtr if found, or NULL otherwise. The str pointer
* is updated to the current location in the string.
*/
static xmlEntityPtr
xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar ** str) {
xmlChar *name;
const xmlChar *ptr;
xmlChar cur;
xmlEntityPtr ent = NULL;
if ((str == NULL) || (*str == NULL))
return(NULL);
ptr = *str;
cur = *ptr;
if (cur != '&')
return(NULL);
ptr++;
name = xmlParseStringName(ctxt, &ptr);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseStringEntityRef: no name\n");
*str = ptr;
return(NULL);
}
if (*ptr != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
xmlFree(name);
*str = ptr;
return(NULL);
}
ptr++;
/*
* Predefined entities override any extra definition
*/
if ((ctxt->options & XML_PARSE_OLDSAX) == 0) {
ent = xmlGetPredefinedEntity(name);
if (ent != NULL) {
xmlFree(name);
*str = ptr;
return(ent);
}
}
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Ask first SAX for entity resolution, otherwise try the
* entities which may have stored in the parser context.
*/
if (ctxt->sax != NULL) {
if (ctxt->sax->getEntity != NULL)
ent = ctxt->sax->getEntity(ctxt->userData, name);
if ((ent == NULL) && (ctxt->options & XML_PARSE_OLDSAX))
ent = xmlGetPredefinedEntity(name);
if ((ent == NULL) && (ctxt->userData==ctxt)) {
ent = xmlSAX2GetEntity(ctxt, name);
}
}
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(name);
return(NULL);
}
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", the
* Name given in the entity reference must match that in an
* entity declaration, except that well-formed documents
* need not declare any of the following entities: amp, lt,
* gt, apos, quot.
* The declaration of a parameter entity must precede any
* reference to it.
* Similarly, the declaration of a general entity must
* precede any reference to it which appears in a default
* value in an attribute-list declaration. Note that if
* entities are declared in the external subset or in
* external parameter entities, a non-validating processor
* is not obligated to read and process their declarations;
* for such documents, the rule that an entity must be
* declared is a well-formedness constraint only if
* standalone='yes'.
*/
if (ent == NULL) {
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"Entity '%s' not defined\n", name);
} else {
xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Entity '%s' not defined\n",
name);
}
xmlParserEntityCheck(ctxt, 0, ent, 0);
/* TODO ? check regressions ctxt->valid = 0; */
}
/*
* [ WFC: Parsed Entity ]
* An entity reference must not contain the name of an
* unparsed entity
*/
else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY,
"Entity reference to unparsed entity %s\n", name);
}
/*
* [ WFC: No External Entity References ]
* Attribute values cannot contain direct or indirect
* entity references to external entities.
*/
else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
(ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL,
"Attribute references external entity '%s'\n", name);
}
/*
* [ WFC: No < in Attribute Values ]
* The replacement text of any entity referred to directly or
* indirectly in an attribute value (other than "<") must
* not contain a <.
*/
else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
(ent != NULL) && (ent->content != NULL) &&
(ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) &&
(xmlStrchr(ent->content, '<'))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
"'<' in entity '%s' is not allowed in attributes values\n",
name);
}
/*
* Internal check, no parameter entities here ...
*/
else {
switch (ent->etype) {
case XML_INTERNAL_PARAMETER_ENTITY:
case XML_EXTERNAL_PARAMETER_ENTITY:
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
"Attempt to reference the parameter entity '%s'\n",
name);
break;
default:
break;
}
}
/*
* [ WFC: No Recursion ]
* A parsed entity must not contain a recursive reference
* to itself, either directly or indirectly.
* Done somewhere else
*/
xmlFree(name);
*str = ptr;
return(ent);
}
/**
* xmlParsePEReference:
* @ctxt: an XML parser context
*
* parse PEReference declarations
* The entity content is handled directly by pushing it's content as
* a new input stream.
*
* [69] PEReference ::= '%' Name ';'
*
* [ WFC: No Recursion ]
* A parsed entity must not contain a recursive
* reference to itself, either directly or indirectly.
*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an internal DTD
* subset which contains no parameter entity references, or a document
* with "standalone='yes'", ... ... The declaration of a parameter
* entity must precede any reference to it...
*
* [ VC: Entity Declared ]
* In a document with an external subset or external parameter entities
* with "standalone='no'", ... ... The declaration of a parameter entity
* must precede any reference to it...
*
* [ WFC: In DTD ]
* Parameter-entity references may only appear in the DTD.
* NOTE: misleading but this is handled.
*/
void
xmlParsePEReference(xmlParserCtxtPtr ctxt)
{
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%')
return;
NEXT;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParsePEReference: no name\n");
return;
}
if (RAW != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
return;
}
NEXT;
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Request the entity from SAX
*/
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (ctxt->instate == XML_PARSER_EOF)
return;
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must
* precede any reference to it...
*/
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
xmlParserEntityCheck(ctxt, 0, NULL, 0);
} else {
/*
* Internal checking in case the entity quest barfed
*/
if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Internal: %%%s; is not a parameter entity\n",
name, NULL);
} else if (ctxt->input->free != deallocblankswrapper) {
input = xmlNewBlanksWrapperInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
} else {
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
((ctxt->options & XML_PARSE_NOENT) == 0) &&
((ctxt->options & XML_PARSE_DTDVALID) == 0) &&
((ctxt->options & XML_PARSE_DTDLOAD) == 0) &&
((ctxt->options & XML_PARSE_DTDATTR) == 0) &&
(ctxt->replaceEntities == 0) &&
(ctxt->validate == 0))
return;
/*
* TODO !!!
* handle the extra spaces added before and after
* c.f. http://www.w3.org/TR/REC-xml#as-PE
*/
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
if (ctxt->errNo ==
XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing
* right here
*/
xmlHaltParser(ctxt);
return;
}
}
}
}
ctxt->hasPErefs = 1;
}
/**
* xmlLoadEntityContent:
* @ctxt: an XML parser context
* @entity: an unloaded system entity
*
* Load the original content of the given system entity from the
* ExternalID/SystemID given. This is to be used for Included in Literal
* http://www.w3.org/TR/REC-xml/#inliteral processing of entities references
*
* Returns 0 in case of success and -1 in case of failure
*/
static int
xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) {
xmlParserInputPtr input;
xmlBufferPtr buf;
int l, c;
int count = 0;
if ((ctxt == NULL) || (entity == NULL) ||
((entity->etype != XML_EXTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY)) ||
(entity->content != NULL)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlLoadEntityContent parameter error");
return(-1);
}
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"Reading %s entity content input\n", entity->name);
buf = xmlBufferCreate();
if (buf == NULL) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlLoadEntityContent parameter error");
return(-1);
}
input = xmlNewEntityInputStream(ctxt, entity);
if (input == NULL) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlLoadEntityContent input error");
xmlBufferFree(buf);
return(-1);
}
/*
* Push the entity as the current input, read char by char
* saving to the buffer until the end of the entity or an error
*/
if (xmlPushInput(ctxt, input) < 0) {
xmlBufferFree(buf);
return(-1);
}
GROW;
c = CUR_CHAR(l);
while ((ctxt->input == input) && (ctxt->input->cur < ctxt->input->end) &&
(IS_CHAR(c))) {
xmlBufferAdd(buf, ctxt->input->cur, l);
if (count++ > XML_PARSER_CHUNK_SIZE) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF) {
xmlBufferFree(buf);
return(-1);
}
}
NEXTL(l);
c = CUR_CHAR(l);
if (c == 0) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF) {
xmlBufferFree(buf);
return(-1);
}
c = CUR_CHAR(l);
}
}
if ((ctxt->input == input) && (ctxt->input->cur >= ctxt->input->end)) {
xmlPopInput(ctxt);
} else if (!IS_CHAR(c)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlLoadEntityContent: invalid char value %d\n",
c);
xmlBufferFree(buf);
return(-1);
}
entity->content = buf->content;
buf->content = NULL;
xmlBufferFree(buf);
return(0);
}
/**
* xmlParseStringPEReference:
* @ctxt: an XML parser context
* @str: a pointer to an index in the string
*
* parse PEReference declarations
*
* [69] PEReference ::= '%' Name ';'
*
* [ WFC: No Recursion ]
* A parsed entity must not contain a recursive
* reference to itself, either directly or indirectly.
*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an internal DTD
* subset which contains no parameter entity references, or a document
* with "standalone='yes'", ... ... The declaration of a parameter
* entity must precede any reference to it...
*
* [ VC: Entity Declared ]
* In a document with an external subset or external parameter entities
* with "standalone='no'", ... ... The declaration of a parameter entity
* must precede any reference to it...
*
* [ WFC: In DTD ]
* Parameter-entity references may only appear in the DTD.
* NOTE: misleading but this is handled.
*
* Returns the string of the entity content.
* str is updated to the current value of the index
*/
static xmlEntityPtr
xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) {
const xmlChar *ptr;
xmlChar cur;
xmlChar *name;
xmlEntityPtr entity = NULL;
if ((str == NULL) || (*str == NULL)) return(NULL);
ptr = *str;
cur = *ptr;
if (cur != '%')
return(NULL);
ptr++;
name = xmlParseStringName(ctxt, &ptr);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseStringPEReference: no name\n");
*str = ptr;
return(NULL);
}
cur = *ptr;
if (cur != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
xmlFree(name);
*str = ptr;
return(NULL);
}
ptr++;
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Request the entity from SAX
*/
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(name);
return(NULL);
}
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n", name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must
* precede any reference to it...
*/
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
xmlParserEntityCheck(ctxt, 0, NULL, 0);
} else {
/*
* Internal checking in case the entity quest barfed
*/
if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"%%%s; is not a parameter entity\n",
name, NULL);
}
}
ctxt->hasPErefs = 1;
xmlFree(name);
*str = ptr;
return(entity);
}
/**
* xmlParseDocTypeDecl:
* @ctxt: an XML parser context
*
* parse a DOCTYPE declaration
*
* [28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S?
* ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
*
* [ VC: Root Element Type ]
* The Name in the document type declaration must match the element
* type of the root element.
*/
void
xmlParseDocTypeDecl(xmlParserCtxtPtr ctxt) {
const xmlChar *name = NULL;
xmlChar *ExternalID = NULL;
xmlChar *URI = NULL;
/*
* We know that '<!DOCTYPE' has been detected.
*/
SKIP(9);
SKIP_BLANKS;
/*
* Parse the DOCTYPE name.
*/
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseDocTypeDecl : no DOCTYPE name !\n");
}
ctxt->intSubName = name;
SKIP_BLANKS;
/*
* Check for SystemID and ExternalID
*/
URI = xmlParseExternalID(ctxt, &ExternalID, 1);
if ((URI != NULL) || (ExternalID != NULL)) {
ctxt->hasExternalSubset = 1;
}
ctxt->extSubURI = URI;
ctxt->extSubSystem = ExternalID;
SKIP_BLANKS;
/*
* Create and update the internal subset.
*/
if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI);
if (ctxt->instate == XML_PARSER_EOF)
return;
/*
* Is there any internal subset declarations ?
* they are handled separately in xmlParseInternalSubset()
*/
if (RAW == '[')
return;
/*
* We should be at the end of the DOCTYPE declaration.
*/
if (RAW != '>') {
xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL);
}
NEXT;
}
/**
* xmlParseInternalSubset:
* @ctxt: an XML parser context
*
* parse the internal subset declaration
*
* [28 end] ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
*/
static void
xmlParseInternalSubset(xmlParserCtxtPtr ctxt) {
/*
* Is there any DTD definition ?
*/
if (RAW == '[') {
ctxt->instate = XML_PARSER_DTD;
NEXT;
/*
* Parse the succession of Markup declarations and
* PEReferences.
* Subsequence (markupdecl | PEReference | S)*
*/
while ((RAW != ']') && (ctxt->instate != XML_PARSER_EOF)) {
const xmlChar *check = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
SKIP_BLANKS;
xmlParseMarkupDecl(ctxt);
xmlParsePEReference(ctxt);
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlParseInternalSubset: error detected in Markup declaration\n");
break;
}
}
if (RAW == ']') {
NEXT;
SKIP_BLANKS;
}
}
/*
* We should be at the end of the DOCTYPE declaration.
*/
if (RAW != '>') {
xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL);
return;
}
NEXT;
}
#ifdef LIBXML_SAX1_ENABLED
/**
* xmlParseAttribute:
* @ctxt: an XML parser context
* @value: a xmlChar ** used to store the value of the attribute
*
* parse an attribute
*
* [41] Attribute ::= Name Eq AttValue
*
* [ WFC: No External Entity References ]
* Attribute values cannot contain direct or indirect entity references
* to external entities.
*
* [ WFC: No < in Attribute Values ]
* The replacement text of any entity referred to directly or indirectly in
* an attribute value (other than "<") must not contain a <.
*
* [ VC: Attribute Value Type ]
* The attribute must have been declared; the value must be of the type
* declared for it.
*
* [25] Eq ::= S? '=' S?
*
* With namespace:
*
* [NS 11] Attribute ::= QName Eq AttValue
*
* Also the case QName == xmlns:??? is handled independently as a namespace
* definition.
*
* Returns the attribute name, and the value in *value.
*/
const xmlChar *
xmlParseAttribute(xmlParserCtxtPtr ctxt, xmlChar **value) {
const xmlChar *name;
xmlChar *val;
*value = NULL;
GROW;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"error parsing attribute name\n");
return(NULL);
}
/*
* read the value
*/
SKIP_BLANKS;
if (RAW == '=') {
NEXT;
SKIP_BLANKS;
val = xmlParseAttValue(ctxt);
ctxt->instate = XML_PARSER_CONTENT;
} else {
xmlFatalErrMsgStr(ctxt, XML_ERR_ATTRIBUTE_WITHOUT_VALUE,
"Specification mandate value for attribute %s\n", name);
return(NULL);
}
/*
* Check that xml:lang conforms to the specification
* No more registered as an error, just generate a warning now
* since this was deprecated in XML second edition
*/
if ((ctxt->pedantic) && (xmlStrEqual(name, BAD_CAST "xml:lang"))) {
if (!xmlCheckLanguageID(val)) {
xmlWarningMsg(ctxt, XML_WAR_LANG_VALUE,
"Malformed value for xml:lang : %s\n",
val, NULL);
}
}
/*
* Check that xml:space conforms to the specification
*/
if (xmlStrEqual(name, BAD_CAST "xml:space")) {
if (xmlStrEqual(val, BAD_CAST "default"))
*(ctxt->space) = 0;
else if (xmlStrEqual(val, BAD_CAST "preserve"))
*(ctxt->space) = 1;
else {
xmlWarningMsg(ctxt, XML_WAR_SPACE_VALUE,
"Invalid value \"%s\" for xml:space : \"default\" or \"preserve\" expected\n",
val, NULL);
}
}
*value = val;
return(name);
}
/**
* xmlParseStartTag:
* @ctxt: an XML parser context
*
* parse a start of tag either for rule element or
* EmptyElement. In both case we don't parse the tag closing chars.
*
* [40] STag ::= '<' Name (S Attribute)* S? '>'
*
* [ WFC: Unique Att Spec ]
* No attribute name may appear more than once in the same start-tag or
* empty-element tag.
*
* [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>'
*
* [ WFC: Unique Att Spec ]
* No attribute name may appear more than once in the same start-tag or
* empty-element tag.
*
* With namespace:
*
* [NS 8] STag ::= '<' QName (S Attribute)* S? '>'
*
* [NS 10] EmptyElement ::= '<' QName (S Attribute)* S? '/>'
*
* Returns the element name parsed
*/
const xmlChar *
xmlParseStartTag(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
const xmlChar *attname;
xmlChar *attvalue;
const xmlChar **atts = ctxt->atts;
int nbatts = 0;
int maxatts = ctxt->maxatts;
int i;
if (RAW != '<') return(NULL);
NEXT1;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseStartTag: invalid element name\n");
return(NULL);
}
/*
* Now parse the attributes, it ends up with the ending
*
* (S Attribute)* S?
*/
SKIP_BLANKS;
GROW;
while (((RAW != '>') &&
((RAW != '/') || (NXT(1) != '>')) &&
(IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) {
const xmlChar *q = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
attname = xmlParseAttribute(ctxt, &attvalue);
if ((attname != NULL) && (attvalue != NULL)) {
/*
* [ WFC: Unique Att Spec ]
* No attribute name may appear more than once in the same
* start-tag or empty-element tag.
*/
for (i = 0; i < nbatts;i += 2) {
if (xmlStrEqual(atts[i], attname)) {
xmlErrAttributeDup(ctxt, NULL, attname);
xmlFree(attvalue);
goto failed;
}
}
/*
* Add the pair to atts
*/
if (atts == NULL) {
maxatts = 22; /* allow for 10 attrs by default */
atts = (const xmlChar **)
xmlMalloc(maxatts * sizeof(xmlChar *));
if (atts == NULL) {
xmlErrMemory(ctxt, NULL);
if (attvalue != NULL)
xmlFree(attvalue);
goto failed;
}
ctxt->atts = atts;
ctxt->maxatts = maxatts;
} else if (nbatts + 4 > maxatts) {
const xmlChar **n;
maxatts *= 2;
n = (const xmlChar **) xmlRealloc((void *) atts,
maxatts * sizeof(const xmlChar *));
if (n == NULL) {
xmlErrMemory(ctxt, NULL);
if (attvalue != NULL)
xmlFree(attvalue);
goto failed;
}
atts = n;
ctxt->atts = atts;
ctxt->maxatts = maxatts;
}
atts[nbatts++] = attname;
atts[nbatts++] = attvalue;
atts[nbatts] = NULL;
atts[nbatts + 1] = NULL;
} else {
if (attvalue != NULL)
xmlFree(attvalue);
}
failed:
GROW
if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
break;
if (!IS_BLANK_CH(RAW)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"attributes construct error\n");
}
SKIP_BLANKS;
if ((cons == ctxt->input->consumed) && (q == CUR_PTR) &&
(attname == NULL) && (attvalue == NULL)) {
xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlParseStartTag: problem parsing attributes\n");
break;
}
SHRINK;
GROW;
}
/*
* SAX: Start of Element !
*/
if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL) &&
(!ctxt->disableSAX)) {
if (nbatts > 0)
ctxt->sax->startElement(ctxt->userData, name, atts);
else
ctxt->sax->startElement(ctxt->userData, name, NULL);
}
if (atts != NULL) {
/* Free only the content strings */
for (i = 1;i < nbatts;i+=2)
if (atts[i] != NULL)
xmlFree((xmlChar *) atts[i]);
}
return(name);
}
/**
* xmlParseEndTag1:
* @ctxt: an XML parser context
* @line: line of the start tag
* @nsNr: number of namespaces on the start tag
*
* parse an end of tag
*
* [42] ETag ::= '</' Name S? '>'
*
* With namespace
*
* [NS 9] ETag ::= '</' QName S? '>'
*/
static void
xmlParseEndTag1(xmlParserCtxtPtr ctxt, int line) {
const xmlChar *name;
GROW;
if ((RAW != '<') || (NXT(1) != '/')) {
xmlFatalErrMsg(ctxt, XML_ERR_LTSLASH_REQUIRED,
"xmlParseEndTag: '</' not found\n");
return;
}
SKIP(2);
name = xmlParseNameAndCompare(ctxt,ctxt->name);
/*
* We should definitely be at the ending "S? '>'" part
*/
GROW;
SKIP_BLANKS;
if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) {
xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL);
} else
NEXT1;
/*
* [ WFC: Element Type Match ]
* The Name in an element's end-tag must match the element type in the
* start-tag.
*
*/
if (name != (xmlChar*)1) {
if (name == NULL) name = BAD_CAST "unparseable";
xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NAME_MISMATCH,
"Opening and ending tag mismatch: %s line %d and %s\n",
ctxt->name, line, name);
}
/*
* SAX: End of Tag
*/
if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElement(ctxt->userData, ctxt->name);
namePop(ctxt);
spacePop(ctxt);
return;
}
/**
* xmlParseEndTag:
* @ctxt: an XML parser context
*
* parse an end of tag
*
* [42] ETag ::= '</' Name S? '>'
*
* With namespace
*
* [NS 9] ETag ::= '</' QName S? '>'
*/
void
xmlParseEndTag(xmlParserCtxtPtr ctxt) {
xmlParseEndTag1(ctxt, 0);
}
#endif /* LIBXML_SAX1_ENABLED */
/************************************************************************
* *
* SAX 2 specific operations *
* *
************************************************************************/
/*
* xmlGetNamespace:
* @ctxt: an XML parser context
* @prefix: the prefix to lookup
*
* Lookup the namespace name for the @prefix (which ca be NULL)
* The prefix must come from the @ctxt->dict dictionary
*
* Returns the namespace name or NULL if not bound
*/
static const xmlChar *
xmlGetNamespace(xmlParserCtxtPtr ctxt, const xmlChar *prefix) {
int i;
if (prefix == ctxt->str_xml) return(ctxt->str_xml_ns);
for (i = ctxt->nsNr - 2;i >= 0;i-=2)
if (ctxt->nsTab[i] == prefix) {
if ((prefix == NULL) && (*ctxt->nsTab[i + 1] == 0))
return(NULL);
return(ctxt->nsTab[i + 1]);
}
return(NULL);
}
/**
* xmlParseQName:
* @ctxt: an XML parser context
* @prefix: pointer to store the prefix part
*
* parse an XML Namespace QName
*
* [6] QName ::= (Prefix ':')? LocalPart
* [7] Prefix ::= NCName
* [8] LocalPart ::= NCName
*
* Returns the Name parsed or NULL
*/
static const xmlChar *
xmlParseQName(xmlParserCtxtPtr ctxt, const xmlChar **prefix) {
const xmlChar *l, *p;
GROW;
l = xmlParseNCName(ctxt);
if (l == NULL) {
if (CUR == ':') {
l = xmlParseName(ctxt);
if (l != NULL) {
xmlNsErr(ctxt, XML_NS_ERR_QNAME,
"Failed to parse QName '%s'\n", l, NULL, NULL);
*prefix = NULL;
return(l);
}
}
return(NULL);
}
if (CUR == ':') {
NEXT;
p = l;
l = xmlParseNCName(ctxt);
if (l == NULL) {
xmlChar *tmp;
xmlNsErr(ctxt, XML_NS_ERR_QNAME,
"Failed to parse QName '%s:'\n", p, NULL, NULL);
l = xmlParseNmtoken(ctxt);
if (l == NULL)
tmp = xmlBuildQName(BAD_CAST "", p, NULL, 0);
else {
tmp = xmlBuildQName(l, p, NULL, 0);
xmlFree((char *)l);
}
p = xmlDictLookup(ctxt->dict, tmp, -1);
if (tmp != NULL) xmlFree(tmp);
*prefix = NULL;
return(p);
}
if (CUR == ':') {
xmlChar *tmp;
xmlNsErr(ctxt, XML_NS_ERR_QNAME,
"Failed to parse QName '%s:%s:'\n", p, l, NULL);
NEXT;
tmp = (xmlChar *) xmlParseName(ctxt);
if (tmp != NULL) {
tmp = xmlBuildQName(tmp, l, NULL, 0);
l = xmlDictLookup(ctxt->dict, tmp, -1);
if (tmp != NULL) xmlFree(tmp);
*prefix = p;
return(l);
}
tmp = xmlBuildQName(BAD_CAST "", l, NULL, 0);
l = xmlDictLookup(ctxt->dict, tmp, -1);
if (tmp != NULL) xmlFree(tmp);
*prefix = p;
return(l);
}
*prefix = p;
} else
*prefix = NULL;
return(l);
}
/**
* xmlParseQNameAndCompare:
* @ctxt: an XML parser context
* @name: the localname
* @prefix: the prefix, if any.
*
* parse an XML name and compares for match
* (specialized for endtag parsing)
*
* Returns NULL for an illegal name, (xmlChar*) 1 for success
* and the name for mismatch
*/
static const xmlChar *
xmlParseQNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *name,
xmlChar const *prefix) {
const xmlChar *cmp;
const xmlChar *in;
const xmlChar *ret;
const xmlChar *prefix2;
if (prefix == NULL) return(xmlParseNameAndCompare(ctxt, name));
GROW;
in = ctxt->input->cur;
cmp = prefix;
while (*in != 0 && *in == *cmp) {
++in;
++cmp;
}
if ((*cmp == 0) && (*in == ':')) {
in++;
cmp = name;
while (*in != 0 && *in == *cmp) {
++in;
++cmp;
}
if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) {
/* success */
ctxt->input->cur = in;
return((const xmlChar*) 1);
}
}
/*
* all strings coms from the dictionary, equality can be done directly
*/
ret = xmlParseQName (ctxt, &prefix2);
if ((ret == name) && (prefix == prefix2))
return((const xmlChar*) 1);
return ret;
}
/**
* xmlParseAttValueInternal:
* @ctxt: an XML parser context
* @len: attribute len result
* @alloc: whether the attribute was reallocated as a new string
* @normalize: if 1 then further non-CDATA normalization must be done
*
* parse a value for an attribute.
* NOTE: if no normalization is needed, the routine will return pointers
* directly from the data buffer.
*
* 3.3.3 Attribute-Value Normalization:
* Before the value of an attribute is passed to the application or
* checked for validity, the XML processor must normalize it as follows:
* - a character reference is processed by appending the referenced
* character to the attribute value
* - an entity reference is processed by recursively processing the
* replacement text of the entity
* - a whitespace character (#x20, #xD, #xA, #x9) is processed by
* appending #x20 to the normalized value, except that only a single
* #x20 is appended for a "#xD#xA" sequence that is part of an external
* parsed entity or the literal entity value of an internal parsed entity
* - other characters are processed by appending them to the normalized value
* If the declared value is not CDATA, then the XML processor must further
* process the normalized attribute value by discarding any leading and
* trailing space (#x20) characters, and by replacing sequences of space
* (#x20) characters by a single space (#x20) character.
* All attributes for which no declaration has been read should be treated
* by a non-validating parser as if declared CDATA.
*
* Returns the AttValue parsed or NULL. The value has to be freed by the
* caller if it was copied, this can be detected by val[*len] == 0.
*/
static xmlChar *
xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc,
int normalize)
{
xmlChar limit = 0;
const xmlChar *in = NULL, *start, *end, *last;
xmlChar *ret = NULL;
int line, col;
GROW;
in = (xmlChar *) CUR_PTR;
line = ctxt->input->line;
col = ctxt->input->col;
if (*in != '"' && *in != '\'') {
xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL);
return (NULL);
}
ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE;
/*
* try to handle in this routine the most common case where no
* allocation of a new string is required and where content is
* pure ASCII.
*/
limit = *in++;
col++;
end = ctxt->input->end;
start = in;
if (in >= end) {
const xmlChar *oldbase = ctxt->input->base;
GROW;
if (oldbase != ctxt->input->base) {
long delta = ctxt->input->base - oldbase;
start = start + delta;
in = in + delta;
}
end = ctxt->input->end;
}
if (normalize) {
/*
* Skip any leading spaces
*/
while ((in < end) && (*in != limit) &&
((*in == 0x20) || (*in == 0x9) ||
(*in == 0xA) || (*in == 0xD))) {
if (*in == 0xA) {
line++; col = 1;
} else {
col++;
}
in++;
start = in;
if (in >= end) {
const xmlChar *oldbase = ctxt->input->base;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
if (oldbase != ctxt->input->base) {
long delta = ctxt->input->base - oldbase;
start = start + delta;
in = in + delta;
}
end = ctxt->input->end;
if (((in - start) > XML_MAX_TEXT_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
"AttValue length too long\n");
return(NULL);
}
}
}
while ((in < end) && (*in != limit) && (*in >= 0x20) &&
(*in <= 0x7f) && (*in != '&') && (*in != '<')) {
col++;
if ((*in++ == 0x20) && (*in == 0x20)) break;
if (in >= end) {
const xmlChar *oldbase = ctxt->input->base;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
if (oldbase != ctxt->input->base) {
long delta = ctxt->input->base - oldbase;
start = start + delta;
in = in + delta;
}
end = ctxt->input->end;
if (((in - start) > XML_MAX_TEXT_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
"AttValue length too long\n");
return(NULL);
}
}
}
last = in;
/*
* skip the trailing blanks
*/
while ((last[-1] == 0x20) && (last > start)) last--;
while ((in < end) && (*in != limit) &&
((*in == 0x20) || (*in == 0x9) ||
(*in == 0xA) || (*in == 0xD))) {
if (*in == 0xA) {
line++, col = 1;
} else {
col++;
}
in++;
if (in >= end) {
const xmlChar *oldbase = ctxt->input->base;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
if (oldbase != ctxt->input->base) {
long delta = ctxt->input->base - oldbase;
start = start + delta;
in = in + delta;
last = last + delta;
}
end = ctxt->input->end;
if (((in - start) > XML_MAX_TEXT_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
"AttValue length too long\n");
return(NULL);
}
}
}
if (((in - start) > XML_MAX_TEXT_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
"AttValue length too long\n");
return(NULL);
}
if (*in != limit) goto need_complex;
} else {
while ((in < end) && (*in != limit) && (*in >= 0x20) &&
(*in <= 0x7f) && (*in != '&') && (*in != '<')) {
in++;
col++;
if (in >= end) {
const xmlChar *oldbase = ctxt->input->base;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
if (oldbase != ctxt->input->base) {
long delta = ctxt->input->base - oldbase;
start = start + delta;
in = in + delta;
}
end = ctxt->input->end;
if (((in - start) > XML_MAX_TEXT_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
"AttValue length too long\n");
return(NULL);
}
}
}
last = in;
if (((in - start) > XML_MAX_TEXT_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
"AttValue length too long\n");
return(NULL);
}
if (*in != limit) goto need_complex;
}
in++;
col++;
if (len != NULL) {
*len = last - start;
ret = (xmlChar *) start;
} else {
if (alloc) *alloc = 1;
ret = xmlStrndup(start, last - start);
}
CUR_PTR = in;
ctxt->input->line = line;
ctxt->input->col = col;
if (alloc) *alloc = 0;
return ret;
need_complex:
if (alloc) *alloc = 1;
return xmlParseAttValueComplex(ctxt, len, normalize);
}
/**
* xmlParseAttribute2:
* @ctxt: an XML parser context
* @pref: the element prefix
* @elem: the element name
* @prefix: a xmlChar ** used to store the value of the attribute prefix
* @value: a xmlChar ** used to store the value of the attribute
* @len: an int * to save the length of the attribute
* @alloc: an int * to indicate if the attribute was allocated
*
* parse an attribute in the new SAX2 framework.
*
* Returns the attribute name, and the value in *value, .
*/
static const xmlChar *
xmlParseAttribute2(xmlParserCtxtPtr ctxt,
const xmlChar * pref, const xmlChar * elem,
const xmlChar ** prefix, xmlChar ** value,
int *len, int *alloc)
{
const xmlChar *name;
xmlChar *val, *internal_val = NULL;
int normalize = 0;
*value = NULL;
GROW;
name = xmlParseQName(ctxt, prefix);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"error parsing attribute name\n");
return (NULL);
}
/*
* get the type if needed
*/
if (ctxt->attsSpecial != NULL) {
int type;
type = (int) (long) xmlHashQLookup2(ctxt->attsSpecial,
pref, elem, *prefix, name);
if (type != 0)
normalize = 1;
}
/*
* read the value
*/
SKIP_BLANKS;
if (RAW == '=') {
NEXT;
SKIP_BLANKS;
val = xmlParseAttValueInternal(ctxt, len, alloc, normalize);
if (normalize) {
/*
* Sometimes a second normalisation pass for spaces is needed
* but that only happens if charrefs or entities refernces
* have been used in the attribute value, i.e. the attribute
* value have been extracted in an allocated string already.
*/
if (*alloc) {
const xmlChar *val2;
val2 = xmlAttrNormalizeSpace2(ctxt, val, len);
if ((val2 != NULL) && (val2 != val)) {
xmlFree(val);
val = (xmlChar *) val2;
}
}
}
ctxt->instate = XML_PARSER_CONTENT;
} else {
xmlFatalErrMsgStr(ctxt, XML_ERR_ATTRIBUTE_WITHOUT_VALUE,
"Specification mandate value for attribute %s\n",
name);
return (NULL);
}
if (*prefix == ctxt->str_xml) {
/*
* Check that xml:lang conforms to the specification
* No more registered as an error, just generate a warning now
* since this was deprecated in XML second edition
*/
if ((ctxt->pedantic) && (xmlStrEqual(name, BAD_CAST "lang"))) {
internal_val = xmlStrndup(val, *len);
if (!xmlCheckLanguageID(internal_val)) {
xmlWarningMsg(ctxt, XML_WAR_LANG_VALUE,
"Malformed value for xml:lang : %s\n",
internal_val, NULL);
}
}
/*
* Check that xml:space conforms to the specification
*/
if (xmlStrEqual(name, BAD_CAST "space")) {
internal_val = xmlStrndup(val, *len);
if (xmlStrEqual(internal_val, BAD_CAST "default"))
*(ctxt->space) = 0;
else if (xmlStrEqual(internal_val, BAD_CAST "preserve"))
*(ctxt->space) = 1;
else {
xmlWarningMsg(ctxt, XML_WAR_SPACE_VALUE,
"Invalid value \"%s\" for xml:space : \"default\" or \"preserve\" expected\n",
internal_val, NULL);
}
}
if (internal_val) {
xmlFree(internal_val);
}
}
*value = val;
return (name);
}
/**
* xmlParseStartTag2:
* @ctxt: an XML parser context
*
* parse a start of tag either for rule element or
* EmptyElement. In both case we don't parse the tag closing chars.
* This routine is called when running SAX2 parsing
*
* [40] STag ::= '<' Name (S Attribute)* S? '>'
*
* [ WFC: Unique Att Spec ]
* No attribute name may appear more than once in the same start-tag or
* empty-element tag.
*
* [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>'
*
* [ WFC: Unique Att Spec ]
* No attribute name may appear more than once in the same start-tag or
* empty-element tag.
*
* With namespace:
*
* [NS 8] STag ::= '<' QName (S Attribute)* S? '>'
*
* [NS 10] EmptyElement ::= '<' QName (S Attribute)* S? '/>'
*
* Returns the element name parsed
*/
static const xmlChar *
xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref,
const xmlChar **URI, int *tlen) {
const xmlChar *localname;
const xmlChar *prefix;
const xmlChar *attname;
const xmlChar *aprefix;
const xmlChar *nsname;
xmlChar *attvalue;
const xmlChar **atts = ctxt->atts;
int maxatts = ctxt->maxatts;
int nratts, nbatts, nbdef;
int i, j, nbNs, attval;
unsigned long cur;
int nsNr = ctxt->nsNr;
if (RAW != '<') return(NULL);
NEXT1;
/*
* NOTE: it is crucial with the SAX2 API to never call SHRINK beyond that
* point since the attribute values may be stored as pointers to
* the buffer and calling SHRINK would destroy them !
* The Shrinking is only possible once the full set of attribute
* callbacks have been done.
*/
SHRINK;
cur = ctxt->input->cur - ctxt->input->base;
nbatts = 0;
nratts = 0;
nbdef = 0;
nbNs = 0;
attval = 0;
/* Forget any namespaces added during an earlier parse of this element. */
ctxt->nsNr = nsNr;
localname = xmlParseQName(ctxt, &prefix);
if (localname == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"StartTag: invalid element name\n");
return(NULL);
}
*tlen = ctxt->input->cur - ctxt->input->base - cur;
/*
* Now parse the attributes, it ends up with the ending
*
* (S Attribute)* S?
*/
SKIP_BLANKS;
GROW;
while (((RAW != '>') &&
((RAW != '/') || (NXT(1) != '>')) &&
(IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) {
const xmlChar *q = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
int len = -1, alloc = 0;
attname = xmlParseAttribute2(ctxt, prefix, localname,
&aprefix, &attvalue, &len, &alloc);
if ((attname == NULL) || (attvalue == NULL))
goto next_attr;
if (len < 0) len = xmlStrlen(attvalue);
if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len);
xmlURIPtr uri;
if (URL == NULL) {
xmlErrMemory(ctxt, "dictionary allocation failure");
if ((attvalue != NULL) && (alloc != 0))
xmlFree(attvalue);
return(NULL);
}
if (*URL != 0) {
uri = xmlParseURI((const char *) URL);
if (uri == NULL) {
xmlNsErr(ctxt, XML_WAR_NS_URI,
"xmlns: '%s' is not a valid URI\n",
URL, NULL, NULL);
} else {
if (uri->scheme == NULL) {
xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
"xmlns: URI %s is not absolute\n",
URL, NULL, NULL);
}
xmlFreeURI(uri);
}
if (URL == ctxt->str_xml_ns) {
if (attname != ctxt->str_xml) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"xml namespace URI cannot be the default namespace\n",
NULL, NULL, NULL);
}
goto next_attr;
}
if ((len == 29) &&
(xmlStrEqual(URL,
BAD_CAST "http://www.w3.org/2000/xmlns/"))) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"reuse of the xmlns namespace name is forbidden\n",
NULL, NULL, NULL);
goto next_attr;
}
}
/*
* check that it's not a defined namespace
*/
for (j = 1;j <= nbNs;j++)
if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL)
break;
if (j <= nbNs)
xmlErrAttributeDup(ctxt, NULL, attname);
else
if (nsPush(ctxt, NULL, URL) > 0) nbNs++;
} else if (aprefix == ctxt->str_xmlns) {
const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len);
xmlURIPtr uri;
if (attname == ctxt->str_xml) {
if (URL != ctxt->str_xml_ns) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"xml namespace prefix mapped to wrong URI\n",
NULL, NULL, NULL);
}
/*
* Do not keep a namespace definition node
*/
goto next_attr;
}
if (URL == ctxt->str_xml_ns) {
if (attname != ctxt->str_xml) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"xml namespace URI mapped to wrong prefix\n",
NULL, NULL, NULL);
}
goto next_attr;
}
if (attname == ctxt->str_xmlns) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"redefinition of the xmlns prefix is forbidden\n",
NULL, NULL, NULL);
goto next_attr;
}
if ((len == 29) &&
(xmlStrEqual(URL,
BAD_CAST "http://www.w3.org/2000/xmlns/"))) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"reuse of the xmlns namespace name is forbidden\n",
NULL, NULL, NULL);
goto next_attr;
}
if ((URL == NULL) || (URL[0] == 0)) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"xmlns:%s: Empty XML namespace is not allowed\n",
attname, NULL, NULL);
goto next_attr;
} else {
uri = xmlParseURI((const char *) URL);
if (uri == NULL) {
xmlNsErr(ctxt, XML_WAR_NS_URI,
"xmlns:%s: '%s' is not a valid URI\n",
attname, URL, NULL);
} else {
if ((ctxt->pedantic) && (uri->scheme == NULL)) {
xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
"xmlns:%s: URI %s is not absolute\n",
attname, URL, NULL);
}
xmlFreeURI(uri);
}
}
/*
* check that it's not a defined namespace
*/
for (j = 1;j <= nbNs;j++)
if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname)
break;
if (j <= nbNs)
xmlErrAttributeDup(ctxt, aprefix, attname);
else
if (nsPush(ctxt, attname, URL) > 0) nbNs++;
} else {
/*
* Add the pair to atts
*/
if ((atts == NULL) || (nbatts + 5 > maxatts)) {
if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) {
goto next_attr;
}
maxatts = ctxt->maxatts;
atts = ctxt->atts;
}
ctxt->attallocs[nratts++] = alloc;
atts[nbatts++] = attname;
atts[nbatts++] = aprefix;
/*
* The namespace URI field is used temporarily to point at the
* base of the current input buffer for non-alloced attributes.
* When the input buffer is reallocated, all the pointers become
* invalid, but they can be reconstructed later.
*/
if (alloc)
atts[nbatts++] = NULL;
else
atts[nbatts++] = ctxt->input->base;
atts[nbatts++] = attvalue;
attvalue += len;
atts[nbatts++] = attvalue;
/*
* tag if some deallocation is needed
*/
if (alloc != 0) attval = 1;
attvalue = NULL; /* moved into atts */
}
next_attr:
if ((attvalue != NULL) && (alloc != 0)) {
xmlFree(attvalue);
attvalue = NULL;
}
GROW
if (ctxt->instate == XML_PARSER_EOF)
break;
if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
break;
if (!IS_BLANK_CH(RAW)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"attributes construct error\n");
break;
}
SKIP_BLANKS;
if ((cons == ctxt->input->consumed) && (q == CUR_PTR) &&
(attname == NULL) && (attvalue == NULL)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlParseStartTag: problem parsing attributes\n");
break;
}
GROW;
}
/* Reconstruct attribute value pointers. */
for (i = 0, j = 0; j < nratts; i += 5, j++) {
if (atts[i+2] != NULL) {
/*
* Arithmetic on dangling pointers is technically undefined
* behavior, but well...
*/
ptrdiff_t offset = ctxt->input->base - atts[i+2];
atts[i+2] = NULL; /* Reset repurposed namespace URI */
atts[i+3] += offset; /* value */
atts[i+4] += offset; /* valuend */
}
}
/*
* The attributes defaulting
*/
if (ctxt->attsDefault != NULL) {
xmlDefAttrsPtr defaults;
defaults = xmlHashLookup2(ctxt->attsDefault, localname, prefix);
if (defaults != NULL) {
for (i = 0;i < defaults->nbAttrs;i++) {
attname = defaults->values[5 * i];
aprefix = defaults->values[5 * i + 1];
/*
* special work for namespaces defaulted defs
*/
if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
/*
* check that it's not a defined namespace
*/
for (j = 1;j <= nbNs;j++)
if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL)
break;
if (j <= nbNs) continue;
nsname = xmlGetNamespace(ctxt, NULL);
if (nsname != defaults->values[5 * i + 2]) {
if (nsPush(ctxt, NULL,
defaults->values[5 * i + 2]) > 0)
nbNs++;
}
} else if (aprefix == ctxt->str_xmlns) {
/*
* check that it's not a defined namespace
*/
for (j = 1;j <= nbNs;j++)
if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname)
break;
if (j <= nbNs) continue;
nsname = xmlGetNamespace(ctxt, attname);
if (nsname != defaults->values[2]) {
if (nsPush(ctxt, attname,
defaults->values[5 * i + 2]) > 0)
nbNs++;
}
} else {
/*
* check that it's not a defined attribute
*/
for (j = 0;j < nbatts;j+=5) {
if ((attname == atts[j]) && (aprefix == atts[j+1]))
break;
}
if (j < nbatts) continue;
if ((atts == NULL) || (nbatts + 5 > maxatts)) {
if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) {
return(NULL);
}
maxatts = ctxt->maxatts;
atts = ctxt->atts;
}
atts[nbatts++] = attname;
atts[nbatts++] = aprefix;
if (aprefix == NULL)
atts[nbatts++] = NULL;
else
atts[nbatts++] = xmlGetNamespace(ctxt, aprefix);
atts[nbatts++] = defaults->values[5 * i + 2];
atts[nbatts++] = defaults->values[5 * i + 3];
if ((ctxt->standalone == 1) &&
(defaults->values[5 * i + 4] != NULL)) {
xmlValidityError(ctxt, XML_DTD_STANDALONE_DEFAULTED,
"standalone: attribute %s on %s defaulted from external subset\n",
attname, localname);
}
nbdef++;
}
}
}
}
/*
* The attributes checkings
*/
for (i = 0; i < nbatts;i += 5) {
/*
* The default namespace does not apply to attribute names.
*/
if (atts[i + 1] != NULL) {
nsname = xmlGetNamespace(ctxt, atts[i + 1]);
if (nsname == NULL) {
xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
"Namespace prefix %s for %s on %s is not defined\n",
atts[i + 1], atts[i], localname);
}
atts[i + 2] = nsname;
} else
nsname = NULL;
/*
* [ WFC: Unique Att Spec ]
* No attribute name may appear more than once in the same
* start-tag or empty-element tag.
* As extended by the Namespace in XML REC.
*/
for (j = 0; j < i;j += 5) {
if (atts[i] == atts[j]) {
if (atts[i+1] == atts[j+1]) {
xmlErrAttributeDup(ctxt, atts[i+1], atts[i]);
break;
}
if ((nsname != NULL) && (atts[j + 2] == nsname)) {
xmlNsErr(ctxt, XML_NS_ERR_ATTRIBUTE_REDEFINED,
"Namespaced Attribute %s in '%s' redefined\n",
atts[i], nsname, NULL);
break;
}
}
}
}
nsname = xmlGetNamespace(ctxt, prefix);
if ((prefix != NULL) && (nsname == NULL)) {
xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
"Namespace prefix %s on %s is not defined\n",
prefix, localname, NULL);
}
*pref = prefix;
*URI = nsname;
/*
* SAX: Start of Element !
*/
if ((ctxt->sax != NULL) && (ctxt->sax->startElementNs != NULL) &&
(!ctxt->disableSAX)) {
if (nbNs > 0)
ctxt->sax->startElementNs(ctxt->userData, localname, prefix,
nsname, nbNs, &ctxt->nsTab[ctxt->nsNr - 2 * nbNs],
nbatts / 5, nbdef, atts);
else
ctxt->sax->startElementNs(ctxt->userData, localname, prefix,
nsname, 0, NULL, nbatts / 5, nbdef, atts);
}
/*
* Free up attribute allocated strings if needed
*/
if (attval != 0) {
for (i = 3,j = 0; j < nratts;i += 5,j++)
if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL))
xmlFree((xmlChar *) atts[i]);
}
return(localname);
}
/**
* xmlParseEndTag2:
* @ctxt: an XML parser context
* @line: line of the start tag
* @nsNr: number of namespaces on the start tag
*
* parse an end of tag
*
* [42] ETag ::= '</' Name S? '>'
*
* With namespace
*
* [NS 9] ETag ::= '</' QName S? '>'
*/
static void
xmlParseEndTag2(xmlParserCtxtPtr ctxt, const xmlChar *prefix,
const xmlChar *URI, int line, int nsNr, int tlen) {
const xmlChar *name;
size_t curLength;
GROW;
if ((RAW != '<') || (NXT(1) != '/')) {
xmlFatalErr(ctxt, XML_ERR_LTSLASH_REQUIRED, NULL);
return;
}
SKIP(2);
curLength = ctxt->input->end - ctxt->input->cur;
if ((tlen > 0) && (curLength >= (size_t)tlen) &&
(xmlStrncmp(ctxt->input->cur, ctxt->name, tlen) == 0)) {
if ((curLength >= (size_t)(tlen + 1)) &&
(ctxt->input->cur[tlen] == '>')) {
ctxt->input->cur += tlen + 1;
ctxt->input->col += tlen + 1;
goto done;
}
ctxt->input->cur += tlen;
ctxt->input->col += tlen;
name = (xmlChar*)1;
} else {
if (prefix == NULL)
name = xmlParseNameAndCompare(ctxt, ctxt->name);
else
name = xmlParseQNameAndCompare(ctxt, ctxt->name, prefix);
}
/*
* We should definitely be at the ending "S? '>'" part
*/
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return;
SKIP_BLANKS;
if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) {
xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL);
} else
NEXT1;
/*
* [ WFC: Element Type Match ]
* The Name in an element's end-tag must match the element type in the
* start-tag.
*
*/
if (name != (xmlChar*)1) {
if (name == NULL) name = BAD_CAST "unparseable";
if ((line == 0) && (ctxt->node != NULL))
line = ctxt->node->line;
xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NAME_MISMATCH,
"Opening and ending tag mismatch: %s line %d and %s\n",
ctxt->name, line, name);
}
/*
* SAX: End of Tag
*/
done:
if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElementNs(ctxt->userData, ctxt->name, prefix, URI);
spacePop(ctxt);
if (nsNr != 0)
nsPop(ctxt, nsNr);
return;
}
/**
* xmlParseCDSect:
* @ctxt: an XML parser context
*
* Parse escaped pure raw content.
*
* [18] CDSect ::= CDStart CData CDEnd
*
* [19] CDStart ::= '<![CDATA['
*
* [20] Data ::= (Char* - (Char* ']]>' Char*))
*
* [21] CDEnd ::= ']]>'
*/
void
xmlParseCDSect(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
int r, rl;
int s, sl;
int cur, l;
int count = 0;
/* Check 2.6.0 was NXT(0) not RAW */
if (CMP9(CUR_PTR, '<', '!', '[', 'C', 'D', 'A', 'T', 'A', '[')) {
SKIP(9);
} else
return;
ctxt->instate = XML_PARSER_CDATA_SECTION;
r = CUR_CHAR(rl);
if (!IS_CHAR(r)) {
xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL);
ctxt->instate = XML_PARSER_CONTENT;
return;
}
NEXTL(rl);
s = CUR_CHAR(sl);
if (!IS_CHAR(s)) {
xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL);
ctxt->instate = XML_PARSER_CONTENT;
return;
}
NEXTL(sl);
cur = CUR_CHAR(l);
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return;
}
while (IS_CHAR(cur) &&
((r != ']') || (s != ']') || (cur != '>'))) {
if (len + 5 >= size) {
xmlChar *tmp;
if ((size > XML_MAX_TEXT_LENGTH) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_CDATA_NOT_FINISHED,
"CData section too big found", NULL);
xmlFree (buf);
return;
}
tmp = (xmlChar *) xmlRealloc(buf, size * 2 * sizeof(xmlChar));
if (tmp == NULL) {
xmlFree(buf);
xmlErrMemory(ctxt, NULL);
return;
}
buf = tmp;
size *= 2;
}
COPY_BUF(rl,buf,len,r);
r = s;
rl = sl;
s = cur;
sl = l;
count++;
if (count > 50) {
GROW;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return;
}
count = 0;
}
NEXTL(l);
cur = CUR_CHAR(l);
}
buf[len] = 0;
ctxt->instate = XML_PARSER_CONTENT;
if (cur != '>') {
xmlFatalErrMsgStr(ctxt, XML_ERR_CDATA_NOT_FINISHED,
"CData section not finished\n%.50s\n", buf);
xmlFree(buf);
return;
}
NEXTL(l);
/*
* OK the buffer is to be consumed as cdata.
*/
if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) {
if (ctxt->sax->cdataBlock != NULL)
ctxt->sax->cdataBlock(ctxt->userData, buf, len);
else if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData, buf, len);
}
xmlFree(buf);
}
/**
* xmlParseContent:
* @ctxt: an XML parser context
*
* Parse a content:
*
* [43] content ::= (element | CharData | Reference | CDSect | PI | Comment)*
*/
void
xmlParseContent(xmlParserCtxtPtr ctxt) {
GROW;
while ((RAW != 0) &&
((RAW != '<') || (NXT(1) != '/')) &&
(ctxt->instate != XML_PARSER_EOF)) {
const xmlChar *test = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
const xmlChar *cur = ctxt->input->cur;
/*
* First case : a Processing Instruction.
*/
if ((*cur == '<') && (cur[1] == '?')) {
xmlParsePI(ctxt);
}
/*
* Second case : a CDSection
*/
/* 2.6.0 test was *cur not RAW */
else if (CMP9(CUR_PTR, '<', '!', '[', 'C', 'D', 'A', 'T', 'A', '[')) {
xmlParseCDSect(ctxt);
}
/*
* Third case : a comment
*/
else if ((*cur == '<') && (NXT(1) == '!') &&
(NXT(2) == '-') && (NXT(3) == '-')) {
xmlParseComment(ctxt);
ctxt->instate = XML_PARSER_CONTENT;
}
/*
* Fourth case : a sub-element.
*/
else if (*cur == '<') {
xmlParseElement(ctxt);
}
/*
* Fifth case : a reference. If if has not been resolved,
* parsing returns it's Name, create the node
*/
else if (*cur == '&') {
xmlParseReference(ctxt);
}
/*
* Last case, text. Note that References are handled directly.
*/
else {
xmlParseCharData(ctxt, 0);
}
GROW;
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
SHRINK;
if ((cons == ctxt->input->consumed) && (test == CUR_PTR)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"detected an error in element content\n");
xmlHaltParser(ctxt);
break;
}
}
}
/**
* xmlParseElement:
* @ctxt: an XML parser context
*
* parse an XML element, this is highly recursive
*
* [39] element ::= EmptyElemTag | STag content ETag
*
* [ WFC: Element Type Match ]
* The Name in an element's end-tag must match the element type in the
* start-tag.
*
*/
void
xmlParseElement(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
const xmlChar *prefix = NULL;
const xmlChar *URI = NULL;
xmlParserNodeInfo node_info;
int line, tlen = 0;
xmlNodePtr ret;
int nsNr = ctxt->nsNr;
if (((unsigned int) ctxt->nameNr > xmlParserMaxDepth) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INTERNAL_ERROR,
"Excessive depth in document: %d use XML_PARSE_HUGE option\n",
xmlParserMaxDepth);
xmlHaltParser(ctxt);
return;
}
/* Capture start position */
if (ctxt->record_info) {
node_info.begin_pos = ctxt->input->consumed +
(CUR_PTR - ctxt->input->base);
node_info.begin_line = ctxt->input->line;
}
if (ctxt->spaceNr == 0)
spacePush(ctxt, -1);
else if (*ctxt->space == -2)
spacePush(ctxt, -1);
else
spacePush(ctxt, *ctxt->space);
line = ctxt->input->line;
#ifdef LIBXML_SAX1_ENABLED
if (ctxt->sax2)
#endif /* LIBXML_SAX1_ENABLED */
name = xmlParseStartTag2(ctxt, &prefix, &URI, &tlen);
#ifdef LIBXML_SAX1_ENABLED
else
name = xmlParseStartTag(ctxt);
#endif /* LIBXML_SAX1_ENABLED */
if (ctxt->instate == XML_PARSER_EOF)
return;
if (name == NULL) {
spacePop(ctxt);
return;
}
namePush(ctxt, name);
ret = ctxt->node;
#ifdef LIBXML_VALID_ENABLED
/*
* [ VC: Root Element Type ]
* The Name in the document type declaration must match the element
* type of the root element.
*/
if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc &&
ctxt->node && (ctxt->node == ctxt->myDoc->children))
ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc);
#endif /* LIBXML_VALID_ENABLED */
/*
* Check for an Empty Element.
*/
if ((RAW == '/') && (NXT(1) == '>')) {
SKIP(2);
if (ctxt->sax2) {
if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElementNs(ctxt->userData, name, prefix, URI);
#ifdef LIBXML_SAX1_ENABLED
} else {
if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElement(ctxt->userData, name);
#endif /* LIBXML_SAX1_ENABLED */
}
namePop(ctxt);
spacePop(ctxt);
if (nsNr != ctxt->nsNr)
nsPop(ctxt, ctxt->nsNr - nsNr);
if ( ret != NULL && ctxt->record_info ) {
node_info.end_pos = ctxt->input->consumed +
(CUR_PTR - ctxt->input->base);
node_info.end_line = ctxt->input->line;
node_info.node = ret;
xmlParserAddNodeInfo(ctxt, &node_info);
}
return;
}
if (RAW == '>') {
NEXT1;
} else {
xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_GT_REQUIRED,
"Couldn't find end of Start Tag %s line %d\n",
name, line, NULL);
/*
* end of parsing of this node.
*/
nodePop(ctxt);
namePop(ctxt);
spacePop(ctxt);
if (nsNr != ctxt->nsNr)
nsPop(ctxt, ctxt->nsNr - nsNr);
/*
* Capture end position and add node
*/
if ( ret != NULL && ctxt->record_info ) {
node_info.end_pos = ctxt->input->consumed +
(CUR_PTR - ctxt->input->base);
node_info.end_line = ctxt->input->line;
node_info.node = ret;
xmlParserAddNodeInfo(ctxt, &node_info);
}
return;
}
/*
* Parse the content of the element:
*/
xmlParseContent(ctxt);
if (ctxt->instate == XML_PARSER_EOF)
return;
if (!IS_BYTE_CHAR(RAW)) {
xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED,
"Premature end of data in tag %s line %d\n",
name, line, NULL);
/*
* end of parsing of this node.
*/
nodePop(ctxt);
namePop(ctxt);
spacePop(ctxt);
if (nsNr != ctxt->nsNr)
nsPop(ctxt, ctxt->nsNr - nsNr);
return;
}
/*
* parse the end of tag: '</' should be here.
*/
if (ctxt->sax2) {
xmlParseEndTag2(ctxt, prefix, URI, line, ctxt->nsNr - nsNr, tlen);
namePop(ctxt);
}
#ifdef LIBXML_SAX1_ENABLED
else
xmlParseEndTag1(ctxt, line);
#endif /* LIBXML_SAX1_ENABLED */
/*
* Capture end position and add node
*/
if ( ret != NULL && ctxt->record_info ) {
node_info.end_pos = ctxt->input->consumed +
(CUR_PTR - ctxt->input->base);
node_info.end_line = ctxt->input->line;
node_info.node = ret;
xmlParserAddNodeInfo(ctxt, &node_info);
}
}
/**
* xmlParseVersionNum:
* @ctxt: an XML parser context
*
* parse the XML version value.
*
* [26] VersionNum ::= '1.' [0-9]+
*
* In practice allow [0-9].[0-9]+ at that level
*
* Returns the string giving the XML version number, or NULL
*/
xmlChar *
xmlParseVersionNum(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = 10;
xmlChar cur;
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
cur = CUR;
if (!((cur >= '0') && (cur <= '9'))) {
xmlFree(buf);
return(NULL);
}
buf[len++] = cur;
NEXT;
cur=CUR;
if (cur != '.') {
xmlFree(buf);
return(NULL);
}
buf[len++] = cur;
NEXT;
cur=CUR;
while ((cur >= '0') && (cur <= '9')) {
if (len + 1 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlFree(buf);
xmlErrMemory(ctxt, NULL);
return(NULL);
}
buf = tmp;
}
buf[len++] = cur;
NEXT;
cur=CUR;
}
buf[len] = 0;
return(buf);
}
/**
* xmlParseVersionInfo:
* @ctxt: an XML parser context
*
* parse the XML version.
*
* [24] VersionInfo ::= S 'version' Eq (' VersionNum ' | " VersionNum ")
*
* [25] Eq ::= S? '=' S?
*
* Returns the version string, e.g. "1.0"
*/
xmlChar *
xmlParseVersionInfo(xmlParserCtxtPtr ctxt) {
xmlChar *version = NULL;
if (CMP7(CUR_PTR, 'v', 'e', 'r', 's', 'i', 'o', 'n')) {
SKIP(7);
SKIP_BLANKS;
if (RAW != '=') {
xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL);
return(NULL);
}
NEXT;
SKIP_BLANKS;
if (RAW == '"') {
NEXT;
version = xmlParseVersionNum(ctxt);
if (RAW != '"') {
xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
} else
NEXT;
} else if (RAW == '\''){
NEXT;
version = xmlParseVersionNum(ctxt);
if (RAW != '\'') {
xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
} else
NEXT;
} else {
xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL);
}
}
return(version);
}
/**
* xmlParseEncName:
* @ctxt: an XML parser context
*
* parse the XML encoding name
*
* [81] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*
*
* Returns the encoding name value or NULL
*/
xmlChar *
xmlParseEncName(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = 10;
xmlChar cur;
cur = CUR;
if (((cur >= 'a') && (cur <= 'z')) ||
((cur >= 'A') && (cur <= 'Z'))) {
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
buf[len++] = cur;
NEXT;
cur = CUR;
while (((cur >= 'a') && (cur <= 'z')) ||
((cur >= 'A') && (cur <= 'Z')) ||
((cur >= '0') && (cur <= '9')) ||
(cur == '.') || (cur == '_') ||
(cur == '-')) {
if (len + 1 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buf);
return(NULL);
}
buf = tmp;
}
buf[len++] = cur;
NEXT;
cur = CUR;
if (cur == 0) {
SHRINK;
GROW;
cur = CUR;
}
}
buf[len] = 0;
} else {
xmlFatalErr(ctxt, XML_ERR_ENCODING_NAME, NULL);
}
return(buf);
}
/**
* xmlParseEncodingDecl:
* @ctxt: an XML parser context
*
* parse the XML encoding declaration
*
* [80] EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | "'" EncName "'")
*
* this setups the conversion filters.
*
* Returns the encoding value or NULL
*/
const xmlChar *
xmlParseEncodingDecl(xmlParserCtxtPtr ctxt) {
xmlChar *encoding = NULL;
SKIP_BLANKS;
if (CMP8(CUR_PTR, 'e', 'n', 'c', 'o', 'd', 'i', 'n', 'g')) {
SKIP(8);
SKIP_BLANKS;
if (RAW != '=') {
xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL);
return(NULL);
}
NEXT;
SKIP_BLANKS;
if (RAW == '"') {
NEXT;
encoding = xmlParseEncName(ctxt);
if (RAW != '"') {
xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
xmlFree((xmlChar *) encoding);
return(NULL);
} else
NEXT;
} else if (RAW == '\''){
NEXT;
encoding = xmlParseEncName(ctxt);
if (RAW != '\'') {
xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
xmlFree((xmlChar *) encoding);
return(NULL);
} else
NEXT;
} else {
xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL);
}
/*
* Non standard parsing, allowing the user to ignore encoding
*/
if (ctxt->options & XML_PARSE_IGNORE_ENC) {
xmlFree((xmlChar *) encoding);
return(NULL);
}
/*
* UTF-16 encoding stwich has already taken place at this stage,
* more over the little-endian/big-endian selection is already done
*/
if ((encoding != NULL) &&
((!xmlStrcasecmp(encoding, BAD_CAST "UTF-16")) ||
(!xmlStrcasecmp(encoding, BAD_CAST "UTF16")))) {
/*
* If no encoding was passed to the parser, that we are
* using UTF-16 and no decoder is present i.e. the
* document is apparently UTF-8 compatible, then raise an
* encoding mismatch fatal error
*/
if ((ctxt->encoding == NULL) &&
(ctxt->input->buf != NULL) &&
(ctxt->input->buf->encoder == NULL)) {
xmlFatalErrMsg(ctxt, XML_ERR_INVALID_ENCODING,
"Document labelled UTF-16 but has UTF-8 content\n");
}
if (ctxt->encoding != NULL)
xmlFree((xmlChar *) ctxt->encoding);
ctxt->encoding = encoding;
}
/*
* UTF-8 encoding is handled natively
*/
else if ((encoding != NULL) &&
((!xmlStrcasecmp(encoding, BAD_CAST "UTF-8")) ||
(!xmlStrcasecmp(encoding, BAD_CAST "UTF8")))) {
if (ctxt->encoding != NULL)
xmlFree((xmlChar *) ctxt->encoding);
ctxt->encoding = encoding;
}
else if (encoding != NULL) {
xmlCharEncodingHandlerPtr handler;
if (ctxt->input->encoding != NULL)
xmlFree((xmlChar *) ctxt->input->encoding);
ctxt->input->encoding = encoding;
handler = xmlFindCharEncodingHandler((const char *) encoding);
if (handler != NULL) {
if (xmlSwitchToEncoding(ctxt, handler) < 0) {
/* failed to convert */
ctxt->errNo = XML_ERR_UNSUPPORTED_ENCODING;
return(NULL);
}
} else {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNSUPPORTED_ENCODING,
"Unsupported encoding %s\n", encoding);
return(NULL);
}
}
}
return(encoding);
}
/**
* xmlParseSDDecl:
* @ctxt: an XML parser context
*
* parse the XML standalone declaration
*
* [32] SDDecl ::= S 'standalone' Eq
* (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no')'"'))
*
* [ VC: Standalone Document Declaration ]
* TODO The standalone document declaration must have the value "no"
* if any external markup declarations contain declarations of:
* - attributes with default values, if elements to which these
* attributes apply appear in the document without specifications
* of values for these attributes, or
* - entities (other than amp, lt, gt, apos, quot), if references
* to those entities appear in the document, or
* - attributes with values subject to normalization, where the
* attribute appears in the document with a value which will change
* as a result of normalization, or
* - element types with element content, if white space occurs directly
* within any instance of those types.
*
* Returns:
* 1 if standalone="yes"
* 0 if standalone="no"
* -2 if standalone attribute is missing or invalid
* (A standalone value of -2 means that the XML declaration was found,
* but no value was specified for the standalone attribute).
*/
int
xmlParseSDDecl(xmlParserCtxtPtr ctxt) {
int standalone = -2;
SKIP_BLANKS;
if (CMP10(CUR_PTR, 's', 't', 'a', 'n', 'd', 'a', 'l', 'o', 'n', 'e')) {
SKIP(10);
SKIP_BLANKS;
if (RAW != '=') {
xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL);
return(standalone);
}
NEXT;
SKIP_BLANKS;
if (RAW == '\''){
NEXT;
if ((RAW == 'n') && (NXT(1) == 'o')) {
standalone = 0;
SKIP(2);
} else if ((RAW == 'y') && (NXT(1) == 'e') &&
(NXT(2) == 's')) {
standalone = 1;
SKIP(3);
} else {
xmlFatalErr(ctxt, XML_ERR_STANDALONE_VALUE, NULL);
}
if (RAW != '\'') {
xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
} else
NEXT;
} else if (RAW == '"'){
NEXT;
if ((RAW == 'n') && (NXT(1) == 'o')) {
standalone = 0;
SKIP(2);
} else if ((RAW == 'y') && (NXT(1) == 'e') &&
(NXT(2) == 's')) {
standalone = 1;
SKIP(3);
} else {
xmlFatalErr(ctxt, XML_ERR_STANDALONE_VALUE, NULL);
}
if (RAW != '"') {
xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
} else
NEXT;
} else {
xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL);
}
}
return(standalone);
}
/**
* xmlParseXMLDecl:
* @ctxt: an XML parser context
*
* parse an XML declaration header
*
* [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
*/
void
xmlParseXMLDecl(xmlParserCtxtPtr ctxt) {
xmlChar *version;
/*
* This value for standalone indicates that the document has an
* XML declaration but it does not have a standalone attribute.
* It will be overwritten later if a standalone attribute is found.
*/
ctxt->input->standalone = -2;
/*
* We know that '<?xml' is here.
*/
SKIP(5);
if (!IS_BLANK_CH(RAW)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Blank needed after '<?xml'\n");
}
SKIP_BLANKS;
/*
* We must have the VersionInfo here.
*/
version = xmlParseVersionInfo(ctxt);
if (version == NULL) {
xmlFatalErr(ctxt, XML_ERR_VERSION_MISSING, NULL);
} else {
if (!xmlStrEqual(version, (const xmlChar *) XML_DEFAULT_VERSION)) {
/*
* Changed here for XML-1.0 5th edition
*/
if (ctxt->options & XML_PARSE_OLD10) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNKNOWN_VERSION,
"Unsupported version '%s'\n",
version);
} else {
if ((version[0] == '1') && ((version[1] == '.'))) {
xmlWarningMsg(ctxt, XML_WAR_UNKNOWN_VERSION,
"Unsupported version '%s'\n",
version, NULL);
} else {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNKNOWN_VERSION,
"Unsupported version '%s'\n",
version);
}
}
}
if (ctxt->version != NULL)
xmlFree((void *) ctxt->version);
ctxt->version = version;
}
/*
* We may have the encoding declaration
*/
if (!IS_BLANK_CH(RAW)) {
if ((RAW == '?') && (NXT(1) == '>')) {
SKIP(2);
return;
}
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Blank needed here\n");
}
xmlParseEncodingDecl(ctxt);
if ((ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) ||
(ctxt->instate == XML_PARSER_EOF)) {
/*
* The XML REC instructs us to stop parsing right here
*/
return;
}
/*
* We may have the standalone status.
*/
if ((ctxt->input->encoding != NULL) && (!IS_BLANK_CH(RAW))) {
if ((RAW == '?') && (NXT(1) == '>')) {
SKIP(2);
return;
}
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Blank needed here\n");
}
/*
* We can grow the input buffer freely at that point
*/
GROW;
SKIP_BLANKS;
ctxt->input->standalone = xmlParseSDDecl(ctxt);
SKIP_BLANKS;
if ((RAW == '?') && (NXT(1) == '>')) {
SKIP(2);
} else if (RAW == '>') {
/* Deprecated old WD ... */
xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL);
NEXT;
} else {
xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL);
MOVETO_ENDTAG(CUR_PTR);
NEXT;
}
}
/**
* xmlParseMisc:
* @ctxt: an XML parser context
*
* parse an XML Misc* optional field.
*
* [27] Misc ::= Comment | PI | S
*/
void
xmlParseMisc(xmlParserCtxtPtr ctxt) {
while ((ctxt->instate != XML_PARSER_EOF) &&
(((RAW == '<') && (NXT(1) == '?')) ||
(CMP4(CUR_PTR, '<', '!', '-', '-')) ||
IS_BLANK_CH(CUR))) {
if ((RAW == '<') && (NXT(1) == '?')) {
xmlParsePI(ctxt);
} else if (IS_BLANK_CH(CUR)) {
NEXT;
} else
xmlParseComment(ctxt);
}
}
/**
* xmlParseDocument:
* @ctxt: an XML parser context
*
* parse an XML document (and build a tree if using the standard SAX
* interface).
*
* [1] document ::= prolog element Misc*
*
* [22] prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
*
* Returns 0, -1 in case of error. the parser context is augmented
* as a result of the parsing.
*/
int
xmlParseDocument(xmlParserCtxtPtr ctxt) {
xmlChar start[4];
xmlCharEncoding enc;
xmlInitParser();
if ((ctxt == NULL) || (ctxt->input == NULL))
return(-1);
GROW;
/*
* SAX: detecting the level.
*/
xmlDetectSAX2(ctxt);
/*
* SAX: beginning of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
if ((ctxt->encoding == NULL) &&
((ctxt->input->end - ctxt->input->cur) >= 4)) {
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
*/
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(&start[0], 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if (CUR == 0) {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
return(-1);
}
/*
* Check for the XMLDecl in the Prolog.
* do not GROW here to avoid the detected encoder to decode more
* than just the first line, unless the amount of data is really
* too small to hold "<?xml version="1.0" encoding="foo"
*/
if ((ctxt->input->end - ctxt->input->cur) < 35) {
GROW;
}
if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
/*
* Note that we will switch encoding on the fly.
*/
xmlParseXMLDecl(ctxt);
if ((ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) ||
(ctxt->instate == XML_PARSER_EOF)) {
/*
* The XML REC instructs us to stop parsing right here
*/
return(-1);
}
ctxt->standalone = ctxt->input->standalone;
SKIP_BLANKS;
} else {
ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
}
if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
if ((ctxt->myDoc != NULL) && (ctxt->input != NULL) &&
(ctxt->input->buf != NULL) && (ctxt->input->buf->compressed >= 0)) {
ctxt->myDoc->compression = ctxt->input->buf->compressed;
}
/*
* The Misc part of the Prolog
*/
GROW;
xmlParseMisc(ctxt);
/*
* Then possibly doc type declaration(s) and more Misc
* (doctypedecl Misc*)?
*/
GROW;
if (CMP9(CUR_PTR, '<', '!', 'D', 'O', 'C', 'T', 'Y', 'P', 'E')) {
ctxt->inSubset = 1;
xmlParseDocTypeDecl(ctxt);
if (RAW == '[') {
ctxt->instate = XML_PARSER_DTD;
xmlParseInternalSubset(ctxt);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
}
/*
* Create and update the external subset.
*/
ctxt->inSubset = 2;
if ((ctxt->sax != NULL) && (ctxt->sax->externalSubset != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName,
ctxt->extSubSystem, ctxt->extSubURI);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
ctxt->inSubset = 0;
xmlCleanSpecialAttr(ctxt);
ctxt->instate = XML_PARSER_PROLOG;
xmlParseMisc(ctxt);
}
/*
* Time to start parsing the tree itself
*/
GROW;
if (RAW != '<') {
xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY,
"Start tag expected, '<' not found\n");
} else {
ctxt->instate = XML_PARSER_CONTENT;
xmlParseElement(ctxt);
ctxt->instate = XML_PARSER_EPILOG;
/*
* The Misc part at the end
*/
xmlParseMisc(ctxt);
if (RAW != 0) {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL);
}
ctxt->instate = XML_PARSER_EOF;
}
/*
* SAX: end of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
/*
* Remove locally kept entity definitions if the tree was not built
*/
if ((ctxt->myDoc != NULL) &&
(xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) {
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
if ((ctxt->wellFormed) && (ctxt->myDoc != NULL)) {
ctxt->myDoc->properties |= XML_DOC_WELLFORMED;
if (ctxt->valid)
ctxt->myDoc->properties |= XML_DOC_DTDVALID;
if (ctxt->nsWellFormed)
ctxt->myDoc->properties |= XML_DOC_NSVALID;
if (ctxt->options & XML_PARSE_OLD10)
ctxt->myDoc->properties |= XML_DOC_OLD10;
}
if (! ctxt->wellFormed) {
ctxt->valid = 0;
return(-1);
}
return(0);
}
/**
* xmlParseExtParsedEnt:
* @ctxt: an XML parser context
*
* parse a general parsed entity
* An external general parsed entity is well-formed if it matches the
* production labeled extParsedEnt.
*
* [78] extParsedEnt ::= TextDecl? content
*
* Returns 0, -1 in case of error. the parser context is augmented
* as a result of the parsing.
*/
int
xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) {
xmlChar start[4];
xmlCharEncoding enc;
if ((ctxt == NULL) || (ctxt->input == NULL))
return(-1);
xmlDefaultSAXHandlerInit();
xmlDetectSAX2(ctxt);
GROW;
/*
* SAX: beginning of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator);
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
*/
if ((ctxt->input->end - ctxt->input->cur) >= 4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if (CUR == 0) {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
}
/*
* Check for the XMLDecl in the Prolog.
*/
GROW;
if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
/*
* Note that we will switch encoding on the fly.
*/
xmlParseXMLDecl(ctxt);
if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing right here
*/
return(-1);
}
SKIP_BLANKS;
} else {
ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
}
if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
/*
* Doing validity checking on chunk doesn't make sense
*/
ctxt->instate = XML_PARSER_CONTENT;
ctxt->validate = 0;
ctxt->loadsubset = 0;
ctxt->depth = 0;
xmlParseContent(ctxt);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
if ((RAW == '<') && (NXT(1) == '/')) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
} else if (RAW != 0) {
xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL);
}
/*
* SAX: end of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
if (! ctxt->wellFormed) return(-1);
return(0);
}
#ifdef LIBXML_PUSH_ENABLED
/************************************************************************
* *
* Progressive parsing interfaces *
* *
************************************************************************/
/**
* xmlParseLookupSequence:
* @ctxt: an XML parser context
* @first: the first char to lookup
* @next: the next char to lookup or zero
* @third: the next char to lookup or zero
*
* Try to find if a sequence (first, next, third) or just (first next) or
* (first) is available in the input stream.
* This function has a side effect of (possibly) incrementing ctxt->checkIndex
* to avoid rescanning sequences of bytes, it DOES change the state of the
* parser, do not use liberally.
*
* Returns the index to the current parsing point if the full sequence
* is available, -1 otherwise.
*/
static int
xmlParseLookupSequence(xmlParserCtxtPtr ctxt, xmlChar first,
xmlChar next, xmlChar third) {
int base, len;
xmlParserInputPtr in;
const xmlChar *buf;
in = ctxt->input;
if (in == NULL) return(-1);
base = in->cur - in->base;
if (base < 0) return(-1);
if (ctxt->checkIndex > base)
base = ctxt->checkIndex;
if (in->buf == NULL) {
buf = in->base;
len = in->length;
} else {
buf = xmlBufContent(in->buf->buffer);
len = xmlBufUse(in->buf->buffer);
}
/* take into account the sequence length */
if (third) len -= 2;
else if (next) len --;
for (;base < len;base++) {
if (buf[base] == first) {
if (third != 0) {
if ((buf[base + 1] != next) ||
(buf[base + 2] != third)) continue;
} else if (next != 0) {
if (buf[base + 1] != next) continue;
}
ctxt->checkIndex = 0;
#ifdef DEBUG_PUSH
if (next == 0)
xmlGenericError(xmlGenericErrorContext,
"PP: lookup '%c' found at %d\n",
first, base);
else if (third == 0)
xmlGenericError(xmlGenericErrorContext,
"PP: lookup '%c%c' found at %d\n",
first, next, base);
else
xmlGenericError(xmlGenericErrorContext,
"PP: lookup '%c%c%c' found at %d\n",
first, next, third, base);
#endif
return(base - (in->cur - in->base));
}
}
ctxt->checkIndex = base;
#ifdef DEBUG_PUSH
if (next == 0)
xmlGenericError(xmlGenericErrorContext,
"PP: lookup '%c' failed\n", first);
else if (third == 0)
xmlGenericError(xmlGenericErrorContext,
"PP: lookup '%c%c' failed\n", first, next);
else
xmlGenericError(xmlGenericErrorContext,
"PP: lookup '%c%c%c' failed\n", first, next, third);
#endif
return(-1);
}
/**
* xmlParseGetLasts:
* @ctxt: an XML parser context
* @lastlt: pointer to store the last '<' from the input
* @lastgt: pointer to store the last '>' from the input
*
* Lookup the last < and > in the current chunk
*/
static void
xmlParseGetLasts(xmlParserCtxtPtr ctxt, const xmlChar **lastlt,
const xmlChar **lastgt) {
const xmlChar *tmp;
if ((ctxt == NULL) || (lastlt == NULL) || (lastgt == NULL)) {
xmlGenericError(xmlGenericErrorContext,
"Internal error: xmlParseGetLasts\n");
return;
}
if ((ctxt->progressive != 0) && (ctxt->inputNr == 1)) {
tmp = ctxt->input->end;
tmp--;
while ((tmp >= ctxt->input->base) && (*tmp != '<')) tmp--;
if (tmp < ctxt->input->base) {
*lastlt = NULL;
*lastgt = NULL;
} else {
*lastlt = tmp;
tmp++;
while ((tmp < ctxt->input->end) && (*tmp != '>')) {
if (*tmp == '\'') {
tmp++;
while ((tmp < ctxt->input->end) && (*tmp != '\'')) tmp++;
if (tmp < ctxt->input->end) tmp++;
} else if (*tmp == '"') {
tmp++;
while ((tmp < ctxt->input->end) && (*tmp != '"')) tmp++;
if (tmp < ctxt->input->end) tmp++;
} else
tmp++;
}
if (tmp < ctxt->input->end)
*lastgt = tmp;
else {
tmp = *lastlt;
tmp--;
while ((tmp >= ctxt->input->base) && (*tmp != '>')) tmp--;
if (tmp >= ctxt->input->base)
*lastgt = tmp;
else
*lastgt = NULL;
}
}
} else {
*lastlt = NULL;
*lastgt = NULL;
}
}
/**
* xmlCheckCdataPush:
* @cur: pointer to the block of characters
* @len: length of the block in bytes
* @complete: 1 if complete CDATA block is passed in, 0 if partial block
*
* Check that the block of characters is okay as SCdata content [20]
*
* Returns the number of bytes to pass if okay, a negative index where an
* UTF-8 error occured otherwise
*/
static int
xmlCheckCdataPush(const xmlChar *utf, int len, int complete) {
int ix;
unsigned char c;
int codepoint;
if ((utf == NULL) || (len <= 0))
return(0);
for (ix = 0; ix < len;) { /* string is 0-terminated */
c = utf[ix];
if ((c & 0x80) == 0x00) { /* 1-byte code, starts with 10 */
if (c >= 0x20)
ix++;
else if ((c == 0xA) || (c == 0xD) || (c == 0x9))
ix++;
else
return(-ix);
} else if ((c & 0xe0) == 0xc0) {/* 2-byte code, starts with 110 */
if (ix + 2 > len) return(complete ? -ix : ix);
if ((utf[ix+1] & 0xc0 ) != 0x80)
return(-ix);
codepoint = (utf[ix] & 0x1f) << 6;
codepoint |= utf[ix+1] & 0x3f;
if (!xmlIsCharQ(codepoint))
return(-ix);
ix += 2;
} else if ((c & 0xf0) == 0xe0) {/* 3-byte code, starts with 1110 */
if (ix + 3 > len) return(complete ? -ix : ix);
if (((utf[ix+1] & 0xc0) != 0x80) ||
((utf[ix+2] & 0xc0) != 0x80))
return(-ix);
codepoint = (utf[ix] & 0xf) << 12;
codepoint |= (utf[ix+1] & 0x3f) << 6;
codepoint |= utf[ix+2] & 0x3f;
if (!xmlIsCharQ(codepoint))
return(-ix);
ix += 3;
} else if ((c & 0xf8) == 0xf0) {/* 4-byte code, starts with 11110 */
if (ix + 4 > len) return(complete ? -ix : ix);
if (((utf[ix+1] & 0xc0) != 0x80) ||
((utf[ix+2] & 0xc0) != 0x80) ||
((utf[ix+3] & 0xc0) != 0x80))
return(-ix);
codepoint = (utf[ix] & 0x7) << 18;
codepoint |= (utf[ix+1] & 0x3f) << 12;
codepoint |= (utf[ix+2] & 0x3f) << 6;
codepoint |= utf[ix+3] & 0x3f;
if (!xmlIsCharQ(codepoint))
return(-ix);
ix += 4;
} else /* unknown encoding */
return(-ix);
}
return(ix);
}
/**
* xmlParseTryOrFinish:
* @ctxt: an XML parser context
* @terminate: last chunk indicator
*
* Try to progress on parsing
*
* Returns zero if no parsing was possible
*/
static int
xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) {
int ret = 0;
int avail, tlen;
xmlChar cur, next;
const xmlChar *lastlt, *lastgt;
if (ctxt->input == NULL)
return(0);
#ifdef DEBUG_PUSH
switch (ctxt->instate) {
case XML_PARSER_EOF:
xmlGenericError(xmlGenericErrorContext,
"PP: try EOF\n"); break;
case XML_PARSER_START:
xmlGenericError(xmlGenericErrorContext,
"PP: try START\n"); break;
case XML_PARSER_MISC:
xmlGenericError(xmlGenericErrorContext,
"PP: try MISC\n");break;
case XML_PARSER_COMMENT:
xmlGenericError(xmlGenericErrorContext,
"PP: try COMMENT\n");break;
case XML_PARSER_PROLOG:
xmlGenericError(xmlGenericErrorContext,
"PP: try PROLOG\n");break;
case XML_PARSER_START_TAG:
xmlGenericError(xmlGenericErrorContext,
"PP: try START_TAG\n");break;
case XML_PARSER_CONTENT:
xmlGenericError(xmlGenericErrorContext,
"PP: try CONTENT\n");break;
case XML_PARSER_CDATA_SECTION:
xmlGenericError(xmlGenericErrorContext,
"PP: try CDATA_SECTION\n");break;
case XML_PARSER_END_TAG:
xmlGenericError(xmlGenericErrorContext,
"PP: try END_TAG\n");break;
case XML_PARSER_ENTITY_DECL:
xmlGenericError(xmlGenericErrorContext,
"PP: try ENTITY_DECL\n");break;
case XML_PARSER_ENTITY_VALUE:
xmlGenericError(xmlGenericErrorContext,
"PP: try ENTITY_VALUE\n");break;
case XML_PARSER_ATTRIBUTE_VALUE:
xmlGenericError(xmlGenericErrorContext,
"PP: try ATTRIBUTE_VALUE\n");break;
case XML_PARSER_DTD:
xmlGenericError(xmlGenericErrorContext,
"PP: try DTD\n");break;
case XML_PARSER_EPILOG:
xmlGenericError(xmlGenericErrorContext,
"PP: try EPILOG\n");break;
case XML_PARSER_PI:
xmlGenericError(xmlGenericErrorContext,
"PP: try PI\n");break;
case XML_PARSER_IGNORE:
xmlGenericError(xmlGenericErrorContext,
"PP: try IGNORE\n");break;
}
#endif
if ((ctxt->input != NULL) &&
(ctxt->input->cur - ctxt->input->base > 4096)) {
xmlSHRINK(ctxt);
ctxt->checkIndex = 0;
}
xmlParseGetLasts(ctxt, &lastlt, &lastgt);
while (ctxt->instate != XML_PARSER_EOF) {
if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1))
return(0);
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
if (ctxt->input == NULL) break;
if (ctxt->input->buf == NULL)
avail = ctxt->input->length -
(ctxt->input->cur - ctxt->input->base);
else {
/*
* If we are operating on converted input, try to flush
* remainng chars to avoid them stalling in the non-converted
* buffer. But do not do this in document start where
* encoding="..." may not have been read and we work on a
* guessed encoding.
*/
if ((ctxt->instate != XML_PARSER_START) &&
(ctxt->input->buf->raw != NULL) &&
(xmlBufIsEmpty(ctxt->input->buf->raw) == 0)) {
size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer,
ctxt->input);
size_t current = ctxt->input->cur - ctxt->input->base;
xmlParserInputBufferPush(ctxt->input->buf, 0, "");
xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input,
base, current);
}
avail = xmlBufUse(ctxt->input->buf->buffer) -
(ctxt->input->cur - ctxt->input->base);
}
if (avail < 1)
goto done;
switch (ctxt->instate) {
case XML_PARSER_EOF:
/*
* Document parsing is done !
*/
goto done;
case XML_PARSER_START:
if (ctxt->charset == XML_CHAR_ENCODING_NONE) {
xmlChar start[4];
xmlCharEncoding enc;
/*
* Very first chars read from the document flow.
*/
if (avail < 4)
goto done;
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines,
* else xmlSwitchEncoding will set to (default)
* UTF8.
*/
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
xmlSwitchEncoding(ctxt, enc);
break;
}
if (avail < 2)
goto done;
cur = ctxt->input->cur[0];
next = ctxt->input->cur[1];
if (cur == 0) {
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData,
&xmlDefaultSAXLocator);
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
xmlHaltParser(ctxt);
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering EOF\n");
#endif
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
goto done;
}
if ((cur == '<') && (next == '?')) {
/* PI or XML decl */
if (avail < 5) return(ret);
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '?', '>', 0) < 0))
return(ret);
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData,
&xmlDefaultSAXLocator);
if ((ctxt->input->cur[2] == 'x') &&
(ctxt->input->cur[3] == 'm') &&
(ctxt->input->cur[4] == 'l') &&
(IS_BLANK_CH(ctxt->input->cur[5]))) {
ret += 5;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing XML Decl\n");
#endif
xmlParseXMLDecl(ctxt);
if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing right
* here
*/
xmlHaltParser(ctxt);
return(0);
}
ctxt->standalone = ctxt->input->standalone;
if ((ctxt->encoding == NULL) &&
(ctxt->input->encoding != NULL))
ctxt->encoding = xmlStrdup(ctxt->input->encoding);
if ((ctxt->sax) && (ctxt->sax->startDocument) &&
(!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
ctxt->instate = XML_PARSER_MISC;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering MISC\n");
#endif
} else {
ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
if ((ctxt->sax) && (ctxt->sax->startDocument) &&
(!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
ctxt->instate = XML_PARSER_MISC;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering MISC\n");
#endif
}
} else {
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData,
&xmlDefaultSAXLocator);
ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
if (ctxt->version == NULL) {
xmlErrMemory(ctxt, NULL);
break;
}
if ((ctxt->sax) && (ctxt->sax->startDocument) &&
(!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
ctxt->instate = XML_PARSER_MISC;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering MISC\n");
#endif
}
break;
case XML_PARSER_START_TAG: {
const xmlChar *name;
const xmlChar *prefix = NULL;
const xmlChar *URI = NULL;
int nsNr = ctxt->nsNr;
if ((avail < 2) && (ctxt->inputNr == 1))
goto done;
cur = ctxt->input->cur[0];
if (cur != '<') {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
xmlHaltParser(ctxt);
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
goto done;
}
if (!terminate) {
if (ctxt->progressive) {
/* > can be found unescaped in attribute values */
if ((lastgt == NULL) || (ctxt->input->cur >= lastgt))
goto done;
} else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) {
goto done;
}
}
if (ctxt->spaceNr == 0)
spacePush(ctxt, -1);
else if (*ctxt->space == -2)
spacePush(ctxt, -1);
else
spacePush(ctxt, *ctxt->space);
#ifdef LIBXML_SAX1_ENABLED
if (ctxt->sax2)
#endif /* LIBXML_SAX1_ENABLED */
name = xmlParseStartTag2(ctxt, &prefix, &URI, &tlen);
#ifdef LIBXML_SAX1_ENABLED
else
name = xmlParseStartTag(ctxt);
#endif /* LIBXML_SAX1_ENABLED */
if (ctxt->instate == XML_PARSER_EOF)
goto done;
if (name == NULL) {
spacePop(ctxt);
xmlHaltParser(ctxt);
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
goto done;
}
#ifdef LIBXML_VALID_ENABLED
/*
* [ VC: Root Element Type ]
* The Name in the document type declaration must match
* the element type of the root element.
*/
if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc &&
ctxt->node && (ctxt->node == ctxt->myDoc->children))
ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc);
#endif /* LIBXML_VALID_ENABLED */
/*
* Check for an Empty Element.
*/
if ((RAW == '/') && (NXT(1) == '>')) {
SKIP(2);
if (ctxt->sax2) {
if ((ctxt->sax != NULL) &&
(ctxt->sax->endElementNs != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElementNs(ctxt->userData, name,
prefix, URI);
if (ctxt->nsNr - nsNr > 0)
nsPop(ctxt, ctxt->nsNr - nsNr);
#ifdef LIBXML_SAX1_ENABLED
} else {
if ((ctxt->sax != NULL) &&
(ctxt->sax->endElement != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElement(ctxt->userData, name);
#endif /* LIBXML_SAX1_ENABLED */
}
if (ctxt->instate == XML_PARSER_EOF)
goto done;
spacePop(ctxt);
if (ctxt->nameNr == 0) {
ctxt->instate = XML_PARSER_EPILOG;
} else {
ctxt->instate = XML_PARSER_CONTENT;
}
ctxt->progressive = 1;
break;
}
if (RAW == '>') {
NEXT;
} else {
xmlFatalErrMsgStr(ctxt, XML_ERR_GT_REQUIRED,
"Couldn't find end of Start Tag %s\n",
name);
nodePop(ctxt);
spacePop(ctxt);
}
if (ctxt->sax2)
nameNsPush(ctxt, name, prefix, URI, ctxt->nsNr - nsNr);
#ifdef LIBXML_SAX1_ENABLED
else
namePush(ctxt, name);
#endif /* LIBXML_SAX1_ENABLED */
ctxt->instate = XML_PARSER_CONTENT;
ctxt->progressive = 1;
break;
}
case XML_PARSER_CONTENT: {
const xmlChar *test;
unsigned int cons;
if ((avail < 2) && (ctxt->inputNr == 1))
goto done;
cur = ctxt->input->cur[0];
next = ctxt->input->cur[1];
test = CUR_PTR;
cons = ctxt->input->consumed;
if ((cur == '<') && (next == '/')) {
ctxt->instate = XML_PARSER_END_TAG;
break;
} else if ((cur == '<') && (next == '?')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) {
ctxt->progressive = XML_PARSER_PI;
goto done;
}
xmlParsePI(ctxt);
ctxt->instate = XML_PARSER_CONTENT;
ctxt->progressive = 1;
} else if ((cur == '<') && (next != '!')) {
ctxt->instate = XML_PARSER_START_TAG;
break;
} else if ((cur == '<') && (next == '!') &&
(ctxt->input->cur[2] == '-') &&
(ctxt->input->cur[3] == '-')) {
int term;
if (avail < 4)
goto done;
ctxt->input->cur += 4;
term = xmlParseLookupSequence(ctxt, '-', '-', '>');
ctxt->input->cur -= 4;
if ((!terminate) && (term < 0)) {
ctxt->progressive = XML_PARSER_COMMENT;
goto done;
}
xmlParseComment(ctxt);
ctxt->instate = XML_PARSER_CONTENT;
ctxt->progressive = 1;
} else if ((cur == '<') && (ctxt->input->cur[1] == '!') &&
(ctxt->input->cur[2] == '[') &&
(ctxt->input->cur[3] == 'C') &&
(ctxt->input->cur[4] == 'D') &&
(ctxt->input->cur[5] == 'A') &&
(ctxt->input->cur[6] == 'T') &&
(ctxt->input->cur[7] == 'A') &&
(ctxt->input->cur[8] == '[')) {
SKIP(9);
ctxt->instate = XML_PARSER_CDATA_SECTION;
break;
} else if ((cur == '<') && (next == '!') &&
(avail < 9)) {
goto done;
} else if (cur == '&') {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, ';', 0, 0) < 0))
goto done;
xmlParseReference(ctxt);
} else {
/* TODO Avoid the extra copy, handle directly !!! */
/*
* Goal of the following test is:
* - minimize calls to the SAX 'character' callback
* when they are mergeable
* - handle an problem for isBlank when we only parse
* a sequence of blank chars and the next one is
* not available to check against '<' presence.
* - tries to homogenize the differences in SAX
* callbacks between the push and pull versions
* of the parser.
*/
if ((ctxt->inputNr == 1) &&
(avail < XML_PARSER_BIG_BUFFER_SIZE)) {
if (!terminate) {
if (ctxt->progressive) {
if ((lastlt == NULL) ||
(ctxt->input->cur > lastlt))
goto done;
} else if (xmlParseLookupSequence(ctxt,
'<', 0, 0) < 0) {
goto done;
}
}
}
ctxt->checkIndex = 0;
xmlParseCharData(ctxt, 0);
}
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
if ((cons == ctxt->input->consumed) && (test == CUR_PTR)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"detected an error in element content\n");
xmlHaltParser(ctxt);
break;
}
break;
}
case XML_PARSER_END_TAG:
if (avail < 2)
goto done;
if (!terminate) {
if (ctxt->progressive) {
/* > can be found unescaped in attribute values */
if ((lastgt == NULL) || (ctxt->input->cur >= lastgt))
goto done;
} else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) {
goto done;
}
}
if (ctxt->sax2) {
xmlParseEndTag2(ctxt,
(void *) ctxt->pushTab[ctxt->nameNr * 3 - 3],
(void *) ctxt->pushTab[ctxt->nameNr * 3 - 2], 0,
(int) (long) ctxt->pushTab[ctxt->nameNr * 3 - 1], 0);
nameNsPop(ctxt);
}
#ifdef LIBXML_SAX1_ENABLED
else
xmlParseEndTag1(ctxt, 0);
#endif /* LIBXML_SAX1_ENABLED */
if (ctxt->instate == XML_PARSER_EOF) {
/* Nothing */
} else if (ctxt->nameNr == 0) {
ctxt->instate = XML_PARSER_EPILOG;
} else {
ctxt->instate = XML_PARSER_CONTENT;
}
break;
case XML_PARSER_CDATA_SECTION: {
/*
* The Push mode need to have the SAX callback for
* cdataBlock merge back contiguous callbacks.
*/
int base;
base = xmlParseLookupSequence(ctxt, ']', ']', '>');
if (base < 0) {
if (avail >= XML_PARSER_BIG_BUFFER_SIZE + 2) {
int tmp;
tmp = xmlCheckCdataPush(ctxt->input->cur,
XML_PARSER_BIG_BUFFER_SIZE, 0);
if (tmp < 0) {
tmp = -tmp;
ctxt->input->cur += tmp;
goto encoding_error;
}
if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) {
if (ctxt->sax->cdataBlock != NULL)
ctxt->sax->cdataBlock(ctxt->userData,
ctxt->input->cur, tmp);
else if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData,
ctxt->input->cur, tmp);
}
if (ctxt->instate == XML_PARSER_EOF)
goto done;
SKIPL(tmp);
ctxt->checkIndex = 0;
}
goto done;
} else {
int tmp;
tmp = xmlCheckCdataPush(ctxt->input->cur, base, 1);
if ((tmp < 0) || (tmp != base)) {
tmp = -tmp;
ctxt->input->cur += tmp;
goto encoding_error;
}
if ((ctxt->sax != NULL) && (base == 0) &&
(ctxt->sax->cdataBlock != NULL) &&
(!ctxt->disableSAX)) {
/*
* Special case to provide identical behaviour
* between pull and push parsers on enpty CDATA
* sections
*/
if ((ctxt->input->cur - ctxt->input->base >= 9) &&
(!strncmp((const char *)&ctxt->input->cur[-9],
"<![CDATA[", 9)))
ctxt->sax->cdataBlock(ctxt->userData,
BAD_CAST "", 0);
} else if ((ctxt->sax != NULL) && (base > 0) &&
(!ctxt->disableSAX)) {
if (ctxt->sax->cdataBlock != NULL)
ctxt->sax->cdataBlock(ctxt->userData,
ctxt->input->cur, base);
else if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData,
ctxt->input->cur, base);
}
if (ctxt->instate == XML_PARSER_EOF)
goto done;
SKIPL(base + 3);
ctxt->checkIndex = 0;
ctxt->instate = XML_PARSER_CONTENT;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering CONTENT\n");
#endif
}
break;
}
case XML_PARSER_MISC:
SKIP_BLANKS;
if (ctxt->input->buf == NULL)
avail = ctxt->input->length -
(ctxt->input->cur - ctxt->input->base);
else
avail = xmlBufUse(ctxt->input->buf->buffer) -
(ctxt->input->cur - ctxt->input->base);
if (avail < 2)
goto done;
cur = ctxt->input->cur[0];
next = ctxt->input->cur[1];
if ((cur == '<') && (next == '?')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) {
ctxt->progressive = XML_PARSER_PI;
goto done;
}
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing PI\n");
#endif
xmlParsePI(ctxt);
if (ctxt->instate == XML_PARSER_EOF)
goto done;
ctxt->instate = XML_PARSER_MISC;
ctxt->progressive = 1;
ctxt->checkIndex = 0;
} else if ((cur == '<') && (next == '!') &&
(ctxt->input->cur[2] == '-') &&
(ctxt->input->cur[3] == '-')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) {
ctxt->progressive = XML_PARSER_COMMENT;
goto done;
}
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing Comment\n");
#endif
xmlParseComment(ctxt);
if (ctxt->instate == XML_PARSER_EOF)
goto done;
ctxt->instate = XML_PARSER_MISC;
ctxt->progressive = 1;
ctxt->checkIndex = 0;
} else if ((cur == '<') && (next == '!') &&
(ctxt->input->cur[2] == 'D') &&
(ctxt->input->cur[3] == 'O') &&
(ctxt->input->cur[4] == 'C') &&
(ctxt->input->cur[5] == 'T') &&
(ctxt->input->cur[6] == 'Y') &&
(ctxt->input->cur[7] == 'P') &&
(ctxt->input->cur[8] == 'E')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '>', 0, 0) < 0)) {
ctxt->progressive = XML_PARSER_DTD;
goto done;
}
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing internal subset\n");
#endif
ctxt->inSubset = 1;
ctxt->progressive = 0;
ctxt->checkIndex = 0;
xmlParseDocTypeDecl(ctxt);
if (ctxt->instate == XML_PARSER_EOF)
goto done;
if (RAW == '[') {
ctxt->instate = XML_PARSER_DTD;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering DTD\n");
#endif
} else {
/*
* Create and update the external subset.
*/
ctxt->inSubset = 2;
if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
(ctxt->sax->externalSubset != NULL))
ctxt->sax->externalSubset(ctxt->userData,
ctxt->intSubName, ctxt->extSubSystem,
ctxt->extSubURI);
ctxt->inSubset = 0;
xmlCleanSpecialAttr(ctxt);
ctxt->instate = XML_PARSER_PROLOG;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering PROLOG\n");
#endif
}
} else if ((cur == '<') && (next == '!') &&
(avail < 9)) {
goto done;
} else {
ctxt->instate = XML_PARSER_START_TAG;
ctxt->progressive = XML_PARSER_START_TAG;
xmlParseGetLasts(ctxt, &lastlt, &lastgt);
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering START_TAG\n");
#endif
}
break;
case XML_PARSER_PROLOG:
SKIP_BLANKS;
if (ctxt->input->buf == NULL)
avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base);
else
avail = xmlBufUse(ctxt->input->buf->buffer) -
(ctxt->input->cur - ctxt->input->base);
if (avail < 2)
goto done;
cur = ctxt->input->cur[0];
next = ctxt->input->cur[1];
if ((cur == '<') && (next == '?')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) {
ctxt->progressive = XML_PARSER_PI;
goto done;
}
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing PI\n");
#endif
xmlParsePI(ctxt);
if (ctxt->instate == XML_PARSER_EOF)
goto done;
ctxt->instate = XML_PARSER_PROLOG;
ctxt->progressive = 1;
} else if ((cur == '<') && (next == '!') &&
(ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) {
ctxt->progressive = XML_PARSER_COMMENT;
goto done;
}
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing Comment\n");
#endif
xmlParseComment(ctxt);
if (ctxt->instate == XML_PARSER_EOF)
goto done;
ctxt->instate = XML_PARSER_PROLOG;
ctxt->progressive = 1;
} else if ((cur == '<') && (next == '!') &&
(avail < 4)) {
goto done;
} else {
ctxt->instate = XML_PARSER_START_TAG;
if (ctxt->progressive == 0)
ctxt->progressive = XML_PARSER_START_TAG;
xmlParseGetLasts(ctxt, &lastlt, &lastgt);
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering START_TAG\n");
#endif
}
break;
case XML_PARSER_EPILOG:
SKIP_BLANKS;
if (ctxt->input->buf == NULL)
avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base);
else
avail = xmlBufUse(ctxt->input->buf->buffer) -
(ctxt->input->cur - ctxt->input->base);
if (avail < 2)
goto done;
cur = ctxt->input->cur[0];
next = ctxt->input->cur[1];
if ((cur == '<') && (next == '?')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) {
ctxt->progressive = XML_PARSER_PI;
goto done;
}
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing PI\n");
#endif
xmlParsePI(ctxt);
if (ctxt->instate == XML_PARSER_EOF)
goto done;
ctxt->instate = XML_PARSER_EPILOG;
ctxt->progressive = 1;
} else if ((cur == '<') && (next == '!') &&
(ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) {
if ((!terminate) &&
(xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) {
ctxt->progressive = XML_PARSER_COMMENT;
goto done;
}
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: Parsing Comment\n");
#endif
xmlParseComment(ctxt);
if (ctxt->instate == XML_PARSER_EOF)
goto done;
ctxt->instate = XML_PARSER_EPILOG;
ctxt->progressive = 1;
} else if ((cur == '<') && (next == '!') &&
(avail < 4)) {
goto done;
} else {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL);
xmlHaltParser(ctxt);
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering EOF\n");
#endif
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
goto done;
}
break;
case XML_PARSER_DTD: {
/*
* Sorry but progressive parsing of the internal subset
* is not expected to be supported. We first check that
* the full content of the internal subset is available and
* the parsing is launched only at that point.
* Internal subset ends up with "']' S? '>'" in an unescaped
* section and not in a ']]>' sequence which are conditional
* sections (whoever argued to keep that crap in XML deserve
* a place in hell !).
*/
int base, i;
xmlChar *buf;
xmlChar quote = 0;
size_t use;
base = ctxt->input->cur - ctxt->input->base;
if (base < 0) return(0);
if (ctxt->checkIndex > base)
base = ctxt->checkIndex;
buf = xmlBufContent(ctxt->input->buf->buffer);
use = xmlBufUse(ctxt->input->buf->buffer);
for (;(unsigned int) base < use; base++) {
if (quote != 0) {
if (buf[base] == quote)
quote = 0;
continue;
}
if ((quote == 0) && (buf[base] == '<')) {
int found = 0;
/* special handling of comments */
if (((unsigned int) base + 4 < use) &&
(buf[base + 1] == '!') &&
(buf[base + 2] == '-') &&
(buf[base + 3] == '-')) {
for (;(unsigned int) base + 3 < use; base++) {
if ((buf[base] == '-') &&
(buf[base + 1] == '-') &&
(buf[base + 2] == '>')) {
found = 1;
base += 2;
break;
}
}
if (!found) {
#if 0
fprintf(stderr, "unfinished comment\n");
#endif
break; /* for */
}
continue;
}
}
if (buf[base] == '"') {
quote = '"';
continue;
}
if (buf[base] == '\'') {
quote = '\'';
continue;
}
if (buf[base] == ']') {
#if 0
fprintf(stderr, "%c%c%c%c: ", buf[base],
buf[base + 1], buf[base + 2], buf[base + 3]);
#endif
if ((unsigned int) base +1 >= use)
break;
if (buf[base + 1] == ']') {
/* conditional crap, skip both ']' ! */
base++;
continue;
}
for (i = 1; (unsigned int) base + i < use; i++) {
if (buf[base + i] == '>') {
#if 0
fprintf(stderr, "found\n");
#endif
goto found_end_int_subset;
}
if (!IS_BLANK_CH(buf[base + i])) {
#if 0
fprintf(stderr, "not found\n");
#endif
goto not_end_of_int_subset;
}
}
#if 0
fprintf(stderr, "end of stream\n");
#endif
break;
}
not_end_of_int_subset:
continue; /* for */
}
/*
* We didn't found the end of the Internal subset
*/
if (quote == 0)
ctxt->checkIndex = base;
else
ctxt->checkIndex = 0;
#ifdef DEBUG_PUSH
if (next == 0)
xmlGenericError(xmlGenericErrorContext,
"PP: lookup of int subset end filed\n");
#endif
goto done;
found_end_int_subset:
ctxt->checkIndex = 0;
xmlParseInternalSubset(ctxt);
if (ctxt->instate == XML_PARSER_EOF)
goto done;
ctxt->inSubset = 2;
if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
(ctxt->sax->externalSubset != NULL))
ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName,
ctxt->extSubSystem, ctxt->extSubURI);
ctxt->inSubset = 0;
xmlCleanSpecialAttr(ctxt);
if (ctxt->instate == XML_PARSER_EOF)
goto done;
ctxt->instate = XML_PARSER_PROLOG;
ctxt->checkIndex = 0;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering PROLOG\n");
#endif
break;
}
case XML_PARSER_COMMENT:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == COMMENT\n");
ctxt->instate = XML_PARSER_CONTENT;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering CONTENT\n");
#endif
break;
case XML_PARSER_IGNORE:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == IGNORE");
ctxt->instate = XML_PARSER_DTD;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering DTD\n");
#endif
break;
case XML_PARSER_PI:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == PI\n");
ctxt->instate = XML_PARSER_CONTENT;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering CONTENT\n");
#endif
break;
case XML_PARSER_ENTITY_DECL:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == ENTITY_DECL\n");
ctxt->instate = XML_PARSER_DTD;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering DTD\n");
#endif
break;
case XML_PARSER_ENTITY_VALUE:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == ENTITY_VALUE\n");
ctxt->instate = XML_PARSER_CONTENT;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering DTD\n");
#endif
break;
case XML_PARSER_ATTRIBUTE_VALUE:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == ATTRIBUTE_VALUE\n");
ctxt->instate = XML_PARSER_START_TAG;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering START_TAG\n");
#endif
break;
case XML_PARSER_SYSTEM_LITERAL:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == SYSTEM_LITERAL\n");
ctxt->instate = XML_PARSER_START_TAG;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering START_TAG\n");
#endif
break;
case XML_PARSER_PUBLIC_LITERAL:
xmlGenericError(xmlGenericErrorContext,
"PP: internal error, state == PUBLIC_LITERAL\n");
ctxt->instate = XML_PARSER_START_TAG;
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext,
"PP: entering START_TAG\n");
#endif
break;
}
}
done:
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext, "PP: done %d\n", ret);
#endif
return(ret);
encoding_error:
{
char buffer[150];
snprintf(buffer, 149, "Bytes: 0x%02X 0x%02X 0x%02X 0x%02X\n",
ctxt->input->cur[0], ctxt->input->cur[1],
ctxt->input->cur[2], ctxt->input->cur[3]);
__xmlErrEncoding(ctxt, XML_ERR_INVALID_CHAR,
"Input is not proper UTF-8, indicate encoding !\n%s",
BAD_CAST buffer, NULL);
}
return(0);
}
/**
* xmlParseCheckTransition:
* @ctxt: an XML parser context
* @chunk: a char array
* @size: the size in byte of the chunk
*
* Check depending on the current parser state if the chunk given must be
* processed immediately or one need more data to advance on parsing.
*
* Returns -1 in case of error, 0 if the push is not needed and 1 if needed
*/
static int
xmlParseCheckTransition(xmlParserCtxtPtr ctxt, const char *chunk, int size) {
if ((ctxt == NULL) || (chunk == NULL) || (size < 0))
return(-1);
if (ctxt->instate == XML_PARSER_START_TAG) {
if (memchr(chunk, '>', size) != NULL)
return(1);
return(0);
}
if (ctxt->progressive == XML_PARSER_COMMENT) {
if (memchr(chunk, '>', size) != NULL)
return(1);
return(0);
}
if (ctxt->instate == XML_PARSER_CDATA_SECTION) {
if (memchr(chunk, '>', size) != NULL)
return(1);
return(0);
}
if (ctxt->progressive == XML_PARSER_PI) {
if (memchr(chunk, '>', size) != NULL)
return(1);
return(0);
}
if (ctxt->instate == XML_PARSER_END_TAG) {
if (memchr(chunk, '>', size) != NULL)
return(1);
return(0);
}
if ((ctxt->progressive == XML_PARSER_DTD) ||
(ctxt->instate == XML_PARSER_DTD)) {
if (memchr(chunk, '>', size) != NULL)
return(1);
return(0);
}
return(1);
}
/**
* xmlParseChunk:
* @ctxt: an XML parser context
* @chunk: an char array
* @size: the size in byte of the chunk
* @terminate: last chunk indicator
*
* Parse a Chunk of memory
*
* Returns zero if no error, the xmlParserErrors otherwise.
*/
int
xmlParseChunk(xmlParserCtxtPtr ctxt, const char *chunk, int size,
int terminate) {
int end_in_lf = 0;
int remain = 0;
size_t old_avail = 0;
size_t avail = 0;
if (ctxt == NULL)
return(XML_ERR_INTERNAL_ERROR);
if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1))
return(ctxt->errNo);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
if (ctxt->instate == XML_PARSER_START)
xmlDetectSAX2(ctxt);
if ((size > 0) && (chunk != NULL) && (!terminate) &&
(chunk[size - 1] == '\r')) {
end_in_lf = 1;
size--;
}
xmldecl_done:
if ((size > 0) && (chunk != NULL) && (ctxt->input != NULL) &&
(ctxt->input->buf != NULL) && (ctxt->instate != XML_PARSER_EOF)) {
size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input);
size_t cur = ctxt->input->cur - ctxt->input->base;
int res;
old_avail = xmlBufUse(ctxt->input->buf->buffer);
/*
* Specific handling if we autodetected an encoding, we should not
* push more than the first line ... which depend on the encoding
* And only push the rest once the final encoding was detected
*/
if ((ctxt->instate == XML_PARSER_START) && (ctxt->input != NULL) &&
(ctxt->input->buf != NULL) && (ctxt->input->buf->encoder != NULL)) {
unsigned int len = 45;
if ((xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name,
BAD_CAST "UTF-16")) ||
(xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name,
BAD_CAST "UTF16")))
len = 90;
else if ((xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name,
BAD_CAST "UCS-4")) ||
(xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name,
BAD_CAST "UCS4")))
len = 180;
if (ctxt->input->buf->rawconsumed < len)
len -= ctxt->input->buf->rawconsumed;
/*
* Change size for reading the initial declaration only
* if size is greater than len. Otherwise, memmove in xmlBufferAdd
* will blindly copy extra bytes from memory.
*/
if ((unsigned int) size > len) {
remain = size - len;
size = len;
} else {
remain = 0;
}
}
res = xmlParserInputBufferPush(ctxt->input->buf, size, chunk);
if (res < 0) {
ctxt->errNo = XML_PARSER_EOF;
xmlHaltParser(ctxt);
return (XML_PARSER_EOF);
}
xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, cur);
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext, "PP: pushed %d\n", size);
#endif
} else if (ctxt->instate != XML_PARSER_EOF) {
if ((ctxt->input != NULL) && ctxt->input->buf != NULL) {
xmlParserInputBufferPtr in = ctxt->input->buf;
if ((in->encoder != NULL) && (in->buffer != NULL) &&
(in->raw != NULL)) {
int nbchars;
size_t base = xmlBufGetInputBase(in->buffer, ctxt->input);
size_t current = ctxt->input->cur - ctxt->input->base;
nbchars = xmlCharEncInput(in, terminate);
if (nbchars < 0) {
/* TODO 2.6.0 */
xmlGenericError(xmlGenericErrorContext,
"xmlParseChunk: encoder error\n");
return(XML_ERR_INVALID_ENCODING);
}
xmlBufSetInputBaseCur(in->buffer, ctxt->input, base, current);
}
}
}
if (remain != 0) {
xmlParseTryOrFinish(ctxt, 0);
} else {
if ((ctxt->input != NULL) && (ctxt->input->buf != NULL))
avail = xmlBufUse(ctxt->input->buf->buffer);
/*
* Depending on the current state it may not be such
* a good idea to try parsing if there is nothing in the chunk
* which would be worth doing a parser state transition and we
* need to wait for more data
*/
if ((terminate) || (avail > XML_MAX_TEXT_LENGTH) ||
(old_avail == 0) || (avail == 0) ||
(xmlParseCheckTransition(ctxt,
(const char *)&ctxt->input->base[old_avail],
avail - old_avail)))
xmlParseTryOrFinish(ctxt, terminate);
}
if (ctxt->instate == XML_PARSER_EOF)
return(ctxt->errNo);
if ((ctxt->input != NULL) &&
(((ctxt->input->end - ctxt->input->cur) > XML_MAX_LOOKUP_LIMIT) ||
((ctxt->input->cur - ctxt->input->base) > XML_MAX_LOOKUP_LIMIT)) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "Huge input lookup");
xmlHaltParser(ctxt);
}
if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1))
return(ctxt->errNo);
if (remain != 0) {
chunk += size;
size = remain;
remain = 0;
goto xmldecl_done;
}
if ((end_in_lf == 1) && (ctxt->input != NULL) &&
(ctxt->input->buf != NULL)) {
size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer,
ctxt->input);
size_t current = ctxt->input->cur - ctxt->input->base;
xmlParserInputBufferPush(ctxt->input->buf, 1, "\r");
xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input,
base, current);
}
if (terminate) {
/*
* Check for termination
*/
int cur_avail = 0;
if (ctxt->input != NULL) {
if (ctxt->input->buf == NULL)
cur_avail = ctxt->input->length -
(ctxt->input->cur - ctxt->input->base);
else
cur_avail = xmlBufUse(ctxt->input->buf->buffer) -
(ctxt->input->cur - ctxt->input->base);
}
if ((ctxt->instate != XML_PARSER_EOF) &&
(ctxt->instate != XML_PARSER_EPILOG)) {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL);
}
if ((ctxt->instate == XML_PARSER_EPILOG) && (cur_avail > 0)) {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL);
}
if (ctxt->instate != XML_PARSER_EOF) {
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
}
ctxt->instate = XML_PARSER_EOF;
}
if (ctxt->wellFormed == 0)
return((xmlParserErrors) ctxt->errNo);
else
return(0);
}
/************************************************************************
* *
* I/O front end functions to the parser *
* *
************************************************************************/
/**
* xmlCreatePushParserCtxt:
* @sax: a SAX handler
* @user_data: The user data returned on SAX callbacks
* @chunk: a pointer to an array of chars
* @size: number of chars in the array
* @filename: an optional file name or URI
*
* Create a parser context for using the XML parser in push mode.
* If @buffer and @size are non-NULL, the data is used to detect
* the encoding. The remaining characters will be parsed so they
* don't need to be fed in again through xmlParseChunk.
* To allow content encoding detection, @size should be >= 4
* The value of @filename is used for fetching external entities
* and error/warning reports.
*
* Returns the new parser context or NULL
*/
xmlParserCtxtPtr
xmlCreatePushParserCtxt(xmlSAXHandlerPtr sax, void *user_data,
const char *chunk, int size, const char *filename) {
xmlParserCtxtPtr ctxt;
xmlParserInputPtr inputStream;
xmlParserInputBufferPtr buf;
xmlCharEncoding enc = XML_CHAR_ENCODING_NONE;
/*
* plug some encoding conversion routines
*/
if ((chunk != NULL) && (size >= 4))
enc = xmlDetectCharEncoding((const xmlChar *) chunk, size);
buf = xmlAllocParserInputBuffer(enc);
if (buf == NULL) return(NULL);
ctxt = xmlNewParserCtxt();
if (ctxt == NULL) {
xmlErrMemory(NULL, "creating parser: out of memory\n");
xmlFreeParserInputBuffer(buf);
return(NULL);
}
ctxt->dictNames = 1;
ctxt->pushTab = (void **) xmlMalloc(ctxt->nameMax * 3 * sizeof(xmlChar *));
if (ctxt->pushTab == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFreeParserInputBuffer(buf);
xmlFreeParserCtxt(ctxt);
return(NULL);
}
if (sax != NULL) {
#ifdef LIBXML_SAX1_ENABLED
if (ctxt->sax != (xmlSAXHandlerPtr) &xmlDefaultSAXHandler)
#endif /* LIBXML_SAX1_ENABLED */
xmlFree(ctxt->sax);
ctxt->sax = (xmlSAXHandlerPtr) xmlMalloc(sizeof(xmlSAXHandler));
if (ctxt->sax == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFreeParserInputBuffer(buf);
xmlFreeParserCtxt(ctxt);
return(NULL);
}
memset(ctxt->sax, 0, sizeof(xmlSAXHandler));
if (sax->initialized == XML_SAX2_MAGIC)
memcpy(ctxt->sax, sax, sizeof(xmlSAXHandler));
else
memcpy(ctxt->sax, sax, sizeof(xmlSAXHandlerV1));
if (user_data != NULL)
ctxt->userData = user_data;
}
if (filename == NULL) {
ctxt->directory = NULL;
} else {
ctxt->directory = xmlParserGetDirectory(filename);
}
inputStream = xmlNewInputStream(ctxt);
if (inputStream == NULL) {
xmlFreeParserCtxt(ctxt);
xmlFreeParserInputBuffer(buf);
return(NULL);
}
if (filename == NULL)
inputStream->filename = NULL;
else {
inputStream->filename = (char *)
xmlCanonicPath((const xmlChar *) filename);
if (inputStream->filename == NULL) {
xmlFreeParserCtxt(ctxt);
xmlFreeParserInputBuffer(buf);
return(NULL);
}
}
inputStream->buf = buf;
xmlBufResetInput(inputStream->buf->buffer, inputStream);
inputPush(ctxt, inputStream);
/*
* If the caller didn't provide an initial 'chunk' for determining
* the encoding, we set the context to XML_CHAR_ENCODING_NONE so
* that it can be automatically determined later
*/
if ((size == 0) || (chunk == NULL)) {
ctxt->charset = XML_CHAR_ENCODING_NONE;
} else if ((ctxt->input != NULL) && (ctxt->input->buf != NULL)) {
size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input);
size_t cur = ctxt->input->cur - ctxt->input->base;
xmlParserInputBufferPush(ctxt->input->buf, size, chunk);
xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, cur);
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext, "PP: pushed %d\n", size);
#endif
}
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
return(ctxt);
}
#endif /* LIBXML_PUSH_ENABLED */
/**
* xmlHaltParser:
* @ctxt: an XML parser context
*
* Blocks further parser processing don't override error
* for internal use
*/
static void
xmlHaltParser(xmlParserCtxtPtr ctxt) {
if (ctxt == NULL)
return;
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
if (ctxt->input != NULL) {
/*
* in case there was a specific allocation deallocate before
* overriding base
*/
if (ctxt->input->free != NULL) {
ctxt->input->free((xmlChar *) ctxt->input->base);
ctxt->input->free = NULL;
}
ctxt->input->cur = BAD_CAST"";
ctxt->input->base = ctxt->input->cur;
}
}
/**
* xmlStopParser:
* @ctxt: an XML parser context
*
* Blocks further parser processing
*/
void
xmlStopParser(xmlParserCtxtPtr ctxt) {
if (ctxt == NULL)
return;
xmlHaltParser(ctxt);
ctxt->errNo = XML_ERR_USER_STOP;
}
/**
* xmlCreateIOParserCtxt:
* @sax: a SAX handler
* @user_data: The user data returned on SAX callbacks
* @ioread: an I/O read function
* @ioclose: an I/O close function
* @ioctx: an I/O handler
* @enc: the charset encoding if known
*
* Create a parser context for using the XML parser with an existing
* I/O stream
*
* Returns the new parser context or NULL
*/
xmlParserCtxtPtr
xmlCreateIOParserCtxt(xmlSAXHandlerPtr sax, void *user_data,
xmlInputReadCallback ioread, xmlInputCloseCallback ioclose,
void *ioctx, xmlCharEncoding enc) {
xmlParserCtxtPtr ctxt;
xmlParserInputPtr inputStream;
xmlParserInputBufferPtr buf;
if (ioread == NULL) return(NULL);
buf = xmlParserInputBufferCreateIO(ioread, ioclose, ioctx, enc);
if (buf == NULL) {
if (ioclose != NULL)
ioclose(ioctx);
return (NULL);
}
ctxt = xmlNewParserCtxt();
if (ctxt == NULL) {
xmlFreeParserInputBuffer(buf);
return(NULL);
}
if (sax != NULL) {
#ifdef LIBXML_SAX1_ENABLED
if (ctxt->sax != (xmlSAXHandlerPtr) &xmlDefaultSAXHandler)
#endif /* LIBXML_SAX1_ENABLED */
xmlFree(ctxt->sax);
ctxt->sax = (xmlSAXHandlerPtr) xmlMalloc(sizeof(xmlSAXHandler));
if (ctxt->sax == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFreeParserCtxt(ctxt);
return(NULL);
}
memset(ctxt->sax, 0, sizeof(xmlSAXHandler));
if (sax->initialized == XML_SAX2_MAGIC)
memcpy(ctxt->sax, sax, sizeof(xmlSAXHandler));
else
memcpy(ctxt->sax, sax, sizeof(xmlSAXHandlerV1));
if (user_data != NULL)
ctxt->userData = user_data;
}
inputStream = xmlNewIOInputStream(ctxt, buf, enc);
if (inputStream == NULL) {
xmlFreeParserCtxt(ctxt);
return(NULL);
}
inputPush(ctxt, inputStream);
return(ctxt);
}
#ifdef LIBXML_VALID_ENABLED
/************************************************************************
* *
* Front ends when parsing a DTD *
* *
************************************************************************/
/**
* xmlIOParseDTD:
* @sax: the SAX handler block or NULL
* @input: an Input Buffer
* @enc: the charset encoding if known
*
* Load and parse a DTD
*
* Returns the resulting xmlDtdPtr or NULL in case of error.
* @input will be freed by the function in any case.
*/
xmlDtdPtr
xmlIOParseDTD(xmlSAXHandlerPtr sax, xmlParserInputBufferPtr input,
xmlCharEncoding enc) {
xmlDtdPtr ret = NULL;
xmlParserCtxtPtr ctxt;
xmlParserInputPtr pinput = NULL;
xmlChar start[4];
if (input == NULL)
return(NULL);
ctxt = xmlNewParserCtxt();
if (ctxt == NULL) {
xmlFreeParserInputBuffer(input);
return(NULL);
}
/* We are loading a DTD */
ctxt->options |= XML_PARSE_DTDLOAD;
/*
* Set-up the SAX context
*/
if (sax != NULL) {
if (ctxt->sax != NULL)
xmlFree(ctxt->sax);
ctxt->sax = sax;
ctxt->userData = ctxt;
}
xmlDetectSAX2(ctxt);
/*
* generate a parser input from the I/O handler
*/
pinput = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
if (pinput == NULL) {
if (sax != NULL) ctxt->sax = NULL;
xmlFreeParserInputBuffer(input);
xmlFreeParserCtxt(ctxt);
return(NULL);
}
/*
* plug some encoding conversion routines here.
*/
if (xmlPushInput(ctxt, pinput) < 0) {
if (sax != NULL) ctxt->sax = NULL;
xmlFreeParserCtxt(ctxt);
return(NULL);
}
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
pinput->filename = NULL;
pinput->line = 1;
pinput->col = 1;
pinput->base = ctxt->input->cur;
pinput->cur = ctxt->input->cur;
pinput->free = NULL;
/*
* let's parse that entity knowing it's an external subset.
*/
ctxt->inSubset = 2;
ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0");
if (ctxt->myDoc == NULL) {
xmlErrMemory(ctxt, "New Doc failed");
return(NULL);
}
ctxt->myDoc->properties = XML_DOC_INTERNAL;
ctxt->myDoc->extSubset = xmlNewDtd(ctxt->myDoc, BAD_CAST "none",
BAD_CAST "none", BAD_CAST "none");
if ((enc == XML_CHAR_ENCODING_NONE) &&
((ctxt->input->end - ctxt->input->cur) >= 4)) {
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
*/
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
xmlParseExternalSubset(ctxt, BAD_CAST "none", BAD_CAST "none");
if (ctxt->myDoc != NULL) {
if (ctxt->wellFormed) {
ret = ctxt->myDoc->extSubset;
ctxt->myDoc->extSubset = NULL;
if (ret != NULL) {
xmlNodePtr tmp;
ret->doc = NULL;
tmp = ret->children;
while (tmp != NULL) {
tmp->doc = NULL;
tmp = tmp->next;
}
}
} else {
ret = NULL;
}
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
if (sax != NULL) ctxt->sax = NULL;
xmlFreeParserCtxt(ctxt);
return(ret);
}
/**
* xmlSAXParseDTD:
* @sax: the SAX handler block
* @ExternalID: a NAME* containing the External ID of the DTD
* @SystemID: a NAME* containing the URL to the DTD
*
* Load and parse an external subset.
*
* Returns the resulting xmlDtdPtr or NULL in case of error.
*/
xmlDtdPtr
xmlSAXParseDTD(xmlSAXHandlerPtr sax, const xmlChar *ExternalID,
const xmlChar *SystemID) {
xmlDtdPtr ret = NULL;
xmlParserCtxtPtr ctxt;
xmlParserInputPtr input = NULL;
xmlCharEncoding enc;
xmlChar* systemIdCanonic;
if ((ExternalID == NULL) && (SystemID == NULL)) return(NULL);
ctxt = xmlNewParserCtxt();
if (ctxt == NULL) {
return(NULL);
}
/* We are loading a DTD */
ctxt->options |= XML_PARSE_DTDLOAD;
/*
* Set-up the SAX context
*/
if (sax != NULL) {
if (ctxt->sax != NULL)
xmlFree(ctxt->sax);
ctxt->sax = sax;
ctxt->userData = ctxt;
}
/*
* Canonicalise the system ID
*/
systemIdCanonic = xmlCanonicPath(SystemID);
if ((SystemID != NULL) && (systemIdCanonic == NULL)) {
xmlFreeParserCtxt(ctxt);
return(NULL);
}
/*
* Ask the Entity resolver to load the damn thing
*/
if ((ctxt->sax != NULL) && (ctxt->sax->resolveEntity != NULL))
input = ctxt->sax->resolveEntity(ctxt->userData, ExternalID,
systemIdCanonic);
if (input == NULL) {
if (sax != NULL) ctxt->sax = NULL;
xmlFreeParserCtxt(ctxt);
if (systemIdCanonic != NULL)
xmlFree(systemIdCanonic);
return(NULL);
}
/*
* plug some encoding conversion routines here.
*/
if (xmlPushInput(ctxt, input) < 0) {
if (sax != NULL) ctxt->sax = NULL;
xmlFreeParserCtxt(ctxt);
if (systemIdCanonic != NULL)
xmlFree(systemIdCanonic);
return(NULL);
}
if ((ctxt->input->end - ctxt->input->cur) >= 4) {
enc = xmlDetectCharEncoding(ctxt->input->cur, 4);
xmlSwitchEncoding(ctxt, enc);
}
if (input->filename == NULL)
input->filename = (char *) systemIdCanonic;
else
xmlFree(systemIdCanonic);
input->line = 1;
input->col = 1;
input->base = ctxt->input->cur;
input->cur = ctxt->input->cur;
input->free = NULL;
/*
* let's parse that entity knowing it's an external subset.
*/
ctxt->inSubset = 2;
ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0");
if (ctxt->myDoc == NULL) {
xmlErrMemory(ctxt, "New Doc failed");
if (sax != NULL) ctxt->sax = NULL;
xmlFreeParserCtxt(ctxt);
return(NULL);
}
ctxt->myDoc->properties = XML_DOC_INTERNAL;
ctxt->myDoc->extSubset = xmlNewDtd(ctxt->myDoc, BAD_CAST "none",
ExternalID, SystemID);
xmlParseExternalSubset(ctxt, ExternalID, SystemID);
if (ctxt->myDoc != NULL) {
if (ctxt->wellFormed) {
ret = ctxt->myDoc->extSubset;
ctxt->myDoc->extSubset = NULL;
if (ret != NULL) {
xmlNodePtr tmp;
ret->doc = NULL;
tmp = ret->children;
while (tmp != NULL) {
tmp->doc = NULL;
tmp = tmp->next;
}
}
} else {
ret = NULL;
}
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
if (sax != NULL) ctxt->sax = NULL;
xmlFreeParserCtxt(ctxt);
return(ret);
}
/**
* xmlParseDTD:
* @ExternalID: a NAME* containing the External ID of the DTD
* @SystemID: a NAME* containing the URL to the DTD
*
* Load and parse an external subset.
*
* Returns the resulting xmlDtdPtr or NULL in case of error.
*/
xmlDtdPtr
xmlParseDTD(const xmlChar *ExternalID, const xmlChar *SystemID) {
return(xmlSAXParseDTD(NULL, ExternalID, SystemID));
}
#endif /* LIBXML_VALID_ENABLED */
/************************************************************************
* *
* Front ends when parsing an Entity *
* *
************************************************************************/
/**
* xmlParseCtxtExternalEntity:
* @ctx: the existing parsing context
* @URL: the URL for the entity to load
* @ID: the System ID for the entity to load
* @lst: the return value for the set of parsed nodes
*
* Parse an external general entity within an existing parsing context
* An external general parsed entity is well-formed if it matches the
* production labeled extParsedEnt.
*
* [78] extParsedEnt ::= TextDecl? content
*
* Returns 0 if the entity is well formed, -1 in case of args problem and
* the parser error code otherwise
*/
int
xmlParseCtxtExternalEntity(xmlParserCtxtPtr ctx, const xmlChar *URL,
const xmlChar *ID, xmlNodePtr *lst) {
xmlParserCtxtPtr ctxt;
xmlDocPtr newDoc;
xmlNodePtr newRoot;
xmlSAXHandlerPtr oldsax = NULL;
int ret = 0;
xmlChar start[4];
xmlCharEncoding enc;
if (ctx == NULL) return(-1);
if (((ctx->depth > 40) && ((ctx->options & XML_PARSE_HUGE) == 0)) ||
(ctx->depth > 1024)) {
return(XML_ERR_ENTITY_LOOP);
}
if (lst != NULL)
*lst = NULL;
if ((URL == NULL) && (ID == NULL))
return(-1);
if (ctx->myDoc == NULL) /* @@ relax but check for dereferences */
return(-1);
ctxt = xmlCreateEntityParserCtxtInternal(URL, ID, NULL, ctx);
if (ctxt == NULL) {
return(-1);
}
oldsax = ctxt->sax;
ctxt->sax = ctx->sax;
xmlDetectSAX2(ctxt);
newDoc = xmlNewDoc(BAD_CAST "1.0");
if (newDoc == NULL) {
xmlFreeParserCtxt(ctxt);
return(-1);
}
newDoc->properties = XML_DOC_INTERNAL;
if (ctx->myDoc->dict) {
newDoc->dict = ctx->myDoc->dict;
xmlDictReference(newDoc->dict);
}
if (ctx->myDoc != NULL) {
newDoc->intSubset = ctx->myDoc->intSubset;
newDoc->extSubset = ctx->myDoc->extSubset;
}
if (ctx->myDoc->URL != NULL) {
newDoc->URL = xmlStrdup(ctx->myDoc->URL);
}
newRoot = xmlNewDocNode(newDoc, NULL, BAD_CAST "pseudoroot", NULL);
if (newRoot == NULL) {
ctxt->sax = oldsax;
xmlFreeParserCtxt(ctxt);
newDoc->intSubset = NULL;
newDoc->extSubset = NULL;
xmlFreeDoc(newDoc);
return(-1);
}
xmlAddChild((xmlNodePtr) newDoc, newRoot);
nodePush(ctxt, newDoc->children);
if (ctx->myDoc == NULL) {
ctxt->myDoc = newDoc;
} else {
ctxt->myDoc = ctx->myDoc;
newDoc->children->doc = ctx->myDoc;
}
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
*/
GROW
if ((ctxt->input->end - ctxt->input->cur) >= 4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
/*
* Parse a possible text declaration first
*/
if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
/*
* An XML-1.0 document can't reference an entity not XML-1.0
*/
if ((xmlStrEqual(ctx->version, BAD_CAST "1.0")) &&
(!xmlStrEqual(ctxt->input->version, BAD_CAST "1.0"))) {
xmlFatalErrMsg(ctxt, XML_ERR_VERSION_MISMATCH,
"Version mismatch between document and entity\n");
}
}
/*
* If the user provided its own SAX callbacks then reuse the
* useData callback field, otherwise the expected setup in a
* DOM builder is to have userData == ctxt
*/
if (ctx->userData == ctx)
ctxt->userData = ctxt;
else
ctxt->userData = ctx->userData;
/*
* Doing validity checking on chunk doesn't make sense
*/
ctxt->instate = XML_PARSER_CONTENT;
ctxt->validate = ctx->validate;
ctxt->valid = ctx->valid;
ctxt->loadsubset = ctx->loadsubset;
ctxt->depth = ctx->depth + 1;
ctxt->replaceEntities = ctx->replaceEntities;
if (ctxt->validate) {
ctxt->vctxt.error = ctx->vctxt.error;
ctxt->vctxt.warning = ctx->vctxt.warning;
} else {
ctxt->vctxt.error = NULL;
ctxt->vctxt.warning = NULL;
}
ctxt->vctxt.nodeTab = NULL;
ctxt->vctxt.nodeNr = 0;
ctxt->vctxt.nodeMax = 0;
ctxt->vctxt.node = NULL;
if (ctxt->dict != NULL) xmlDictFree(ctxt->dict);
ctxt->dict = ctx->dict;
ctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST "xml", 3);
ctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST "xmlns", 5);
ctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36);
ctxt->dictNames = ctx->dictNames;
ctxt->attsDefault = ctx->attsDefault;
ctxt->attsSpecial = ctx->attsSpecial;
ctxt->linenumbers = ctx->linenumbers;
xmlParseContent(ctxt);
ctx->validate = ctxt->validate;
ctx->valid = ctxt->valid;
if ((RAW == '<') && (NXT(1) == '/')) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
} else if (RAW != 0) {
xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL);
}
if (ctxt->node != newDoc->children) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
}
if (!ctxt->wellFormed) {
if (ctxt->errNo == 0)
ret = 1;
else
ret = ctxt->errNo;
} else {
if (lst != NULL) {
xmlNodePtr cur;
/*
* Return the newly created nodeset after unlinking it from
* they pseudo parent.
*/
cur = newDoc->children->children;
*lst = cur;
while (cur != NULL) {
cur->parent = NULL;
cur = cur->next;
}
newDoc->children->children = NULL;
}
ret = 0;
}
ctxt->sax = oldsax;
ctxt->dict = NULL;
ctxt->attsDefault = NULL;
ctxt->attsSpecial = NULL;
xmlFreeParserCtxt(ctxt);
newDoc->intSubset = NULL;
newDoc->extSubset = NULL;
xmlFreeDoc(newDoc);
return(ret);
}
/**
* xmlParseExternalEntityPrivate:
* @doc: the document the chunk pertains to
* @oldctxt: the previous parser context if available
* @sax: the SAX handler bloc (possibly NULL)
* @user_data: The user data returned on SAX callbacks (possibly NULL)
* @depth: Used for loop detection, use 0
* @URL: the URL for the entity to load
* @ID: the System ID for the entity to load
* @list: the return value for the set of parsed nodes
*
* Private version of xmlParseExternalEntity()
*
* Returns 0 if the entity is well formed, -1 in case of args problem and
* the parser error code otherwise
*/
static xmlParserErrors
xmlParseExternalEntityPrivate(xmlDocPtr doc, xmlParserCtxtPtr oldctxt,
xmlSAXHandlerPtr sax,
void *user_data, int depth, const xmlChar *URL,
const xmlChar *ID, xmlNodePtr *list) {
xmlParserCtxtPtr ctxt;
xmlDocPtr newDoc;
xmlNodePtr newRoot;
xmlSAXHandlerPtr oldsax = NULL;
xmlParserErrors ret = XML_ERR_OK;
xmlChar start[4];
xmlCharEncoding enc;
if (((depth > 40) &&
((oldctxt == NULL) || (oldctxt->options & XML_PARSE_HUGE) == 0)) ||
(depth > 1024)) {
return(XML_ERR_ENTITY_LOOP);
}
if (list != NULL)
*list = NULL;
if ((URL == NULL) && (ID == NULL))
return(XML_ERR_INTERNAL_ERROR);
if (doc == NULL)
return(XML_ERR_INTERNAL_ERROR);
ctxt = xmlCreateEntityParserCtxtInternal(URL, ID, NULL, oldctxt);
if (ctxt == NULL) return(XML_WAR_UNDECLARED_ENTITY);
ctxt->userData = ctxt;
if (oldctxt != NULL) {
ctxt->_private = oldctxt->_private;
ctxt->loadsubset = oldctxt->loadsubset;
ctxt->validate = oldctxt->validate;
ctxt->external = oldctxt->external;
ctxt->record_info = oldctxt->record_info;
ctxt->node_seq.maximum = oldctxt->node_seq.maximum;
ctxt->node_seq.length = oldctxt->node_seq.length;
ctxt->node_seq.buffer = oldctxt->node_seq.buffer;
} else {
/*
* Doing validity checking on chunk without context
* doesn't make sense
*/
ctxt->_private = NULL;
ctxt->validate = 0;
ctxt->external = 2;
ctxt->loadsubset = 0;
}
if (sax != NULL) {
oldsax = ctxt->sax;
ctxt->sax = sax;
if (user_data != NULL)
ctxt->userData = user_data;
}
xmlDetectSAX2(ctxt);
newDoc = xmlNewDoc(BAD_CAST "1.0");
if (newDoc == NULL) {
ctxt->node_seq.maximum = 0;
ctxt->node_seq.length = 0;
ctxt->node_seq.buffer = NULL;
xmlFreeParserCtxt(ctxt);
return(XML_ERR_INTERNAL_ERROR);
}
newDoc->properties = XML_DOC_INTERNAL;
newDoc->intSubset = doc->intSubset;
newDoc->extSubset = doc->extSubset;
newDoc->dict = doc->dict;
xmlDictReference(newDoc->dict);
if (doc->URL != NULL) {
newDoc->URL = xmlStrdup(doc->URL);
}
newRoot = xmlNewDocNode(newDoc, NULL, BAD_CAST "pseudoroot", NULL);
if (newRoot == NULL) {
if (sax != NULL)
ctxt->sax = oldsax;
ctxt->node_seq.maximum = 0;
ctxt->node_seq.length = 0;
ctxt->node_seq.buffer = NULL;
xmlFreeParserCtxt(ctxt);
newDoc->intSubset = NULL;
newDoc->extSubset = NULL;
xmlFreeDoc(newDoc);
return(XML_ERR_INTERNAL_ERROR);
}
xmlAddChild((xmlNodePtr) newDoc, newRoot);
nodePush(ctxt, newDoc->children);
ctxt->myDoc = doc;
newRoot->doc = doc;
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
*/
GROW;
if ((ctxt->input->end - ctxt->input->cur) >= 4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
/*
* Parse a possible text declaration first
*/
if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
}
ctxt->instate = XML_PARSER_CONTENT;
ctxt->depth = depth;
xmlParseContent(ctxt);
if ((RAW == '<') && (NXT(1) == '/')) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
} else if (RAW != 0) {
xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL);
}
if (ctxt->node != newDoc->children) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
}
if (!ctxt->wellFormed) {
if (ctxt->errNo == 0)
ret = XML_ERR_INTERNAL_ERROR;
else
ret = (xmlParserErrors)ctxt->errNo;
} else {
if (list != NULL) {
xmlNodePtr cur;
/*
* Return the newly created nodeset after unlinking it from
* they pseudo parent.
*/
cur = newDoc->children->children;
*list = cur;
while (cur != NULL) {
cur->parent = NULL;
cur = cur->next;
}
newDoc->children->children = NULL;
}
ret = XML_ERR_OK;
}
/*
* Record in the parent context the number of entities replacement
* done when parsing that reference.
*/
if (oldctxt != NULL)
oldctxt->nbentities += ctxt->nbentities;
/*
* Also record the size of the entity parsed
*/
if (ctxt->input != NULL && oldctxt != NULL) {
oldctxt->sizeentities += ctxt->input->consumed;
oldctxt->sizeentities += (ctxt->input->cur - ctxt->input->base);
}
/*
* And record the last error if any
*/
if (ctxt->lastError.code != XML_ERR_OK)
xmlCopyError(&ctxt->lastError, &oldctxt->lastError);
if (sax != NULL)
ctxt->sax = oldsax;
if (oldctxt != NULL) {
oldctxt->node_seq.maximum = ctxt->node_seq.maximum;
oldctxt->node_seq.length = ctxt->node_seq.length;
oldctxt->node_seq.buffer = ctxt->node_seq.buffer;
}
ctxt->node_seq.maximum = 0;
ctxt->node_seq.length = 0;
ctxt->node_seq.buffer = NULL;
xmlFreeParserCtxt(ctxt);
newDoc->intSubset = NULL;
newDoc->extSubset = NULL;
xmlFreeDoc(newDoc);
return(ret);
}
#ifdef LIBXML_SAX1_ENABLED
/**
* xmlParseExternalEntity:
* @doc: the document the chunk pertains to
* @sax: the SAX handler bloc (possibly NULL)
* @user_data: The user data returned on SAX callbacks (possibly NULL)
* @depth: Used for loop detection, use 0
* @URL: the URL for the entity to load
* @ID: the System ID for the entity to load
* @lst: the return value for the set of parsed nodes
*
* Parse an external general entity
* An external general parsed entity is well-formed if it matches the
* production labeled extParsedEnt.
*
* [78] extParsedEnt ::= TextDecl? content
*
* Returns 0 if the entity is well formed, -1 in case of args problem and
* the parser error code otherwise
*/
int
xmlParseExternalEntity(xmlDocPtr doc, xmlSAXHandlerPtr sax, void *user_data,
int depth, const xmlChar *URL, const xmlChar *ID, xmlNodePtr *lst) {
return(xmlParseExternalEntityPrivate(doc, NULL, sax, user_data, depth, URL,
ID, lst));
}
/**
* xmlParseBalancedChunkMemory:
* @doc: the document the chunk pertains to
* @sax: the SAX handler bloc (possibly NULL)
* @user_data: The user data returned on SAX callbacks (possibly NULL)
* @depth: Used for loop detection, use 0
* @string: the input string in UTF8 or ISO-Latin (zero terminated)
* @lst: the return value for the set of parsed nodes
*
* Parse a well-balanced chunk of an XML document
* called by the parser
* The allowed sequence for the Well Balanced Chunk is the one defined by
* the content production in the XML grammar:
*
* [43] content ::= (element | CharData | Reference | CDSect | PI | Comment)*
*
* Returns 0 if the chunk is well balanced, -1 in case of args problem and
* the parser error code otherwise
*/
int
xmlParseBalancedChunkMemory(xmlDocPtr doc, xmlSAXHandlerPtr sax,
void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst) {
return xmlParseBalancedChunkMemoryRecover( doc, sax, user_data,
depth, string, lst, 0 );
}
#endif /* LIBXML_SAX1_ENABLED */
/**
* xmlParseBalancedChunkMemoryInternal:
* @oldctxt: the existing parsing context
* @string: the input string in UTF8 or ISO-Latin (zero terminated)
* @user_data: the user data field for the parser context
* @lst: the return value for the set of parsed nodes
*
*
* Parse a well-balanced chunk of an XML document
* called by the parser
* The allowed sequence for the Well Balanced Chunk is the one defined by
* the content production in the XML grammar:
*
* [43] content ::= (element | CharData | Reference | CDSect | PI | Comment)*
*
* Returns XML_ERR_OK if the chunk is well balanced, and the parser
* error code otherwise
*
* In case recover is set to 1, the nodelist will not be empty even if
* the parsed chunk is not well balanced.
*/
static xmlParserErrors
xmlParseBalancedChunkMemoryInternal(xmlParserCtxtPtr oldctxt,
const xmlChar *string, void *user_data, xmlNodePtr *lst) {
xmlParserCtxtPtr ctxt;
xmlDocPtr newDoc = NULL;
xmlNodePtr newRoot;
xmlSAXHandlerPtr oldsax = NULL;
xmlNodePtr content = NULL;
xmlNodePtr last = NULL;
int size;
xmlParserErrors ret = XML_ERR_OK;
#ifdef SAX2
int i;
#endif
if (((oldctxt->depth > 40) && ((oldctxt->options & XML_PARSE_HUGE) == 0)) ||
(oldctxt->depth > 1024)) {
return(XML_ERR_ENTITY_LOOP);
}
if (lst != NULL)
*lst = NULL;
if (string == NULL)
return(XML_ERR_INTERNAL_ERROR);
size = xmlStrlen(string);
ctxt = xmlCreateMemoryParserCtxt((char *) string, size);
if (ctxt == NULL) return(XML_WAR_UNDECLARED_ENTITY);
if (user_data != NULL)
ctxt->userData = user_data;
else
ctxt->userData = ctxt;
if (ctxt->dict != NULL) xmlDictFree(ctxt->dict);
ctxt->dict = oldctxt->dict;
ctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST "xml", 3);
ctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST "xmlns", 5);
ctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36);
#ifdef SAX2
/* propagate namespaces down the entity */
for (i = 0;i < oldctxt->nsNr;i += 2) {
nsPush(ctxt, oldctxt->nsTab[i], oldctxt->nsTab[i+1]);
}
#endif
oldsax = ctxt->sax;
ctxt->sax = oldctxt->sax;
xmlDetectSAX2(ctxt);
ctxt->replaceEntities = oldctxt->replaceEntities;
ctxt->options = oldctxt->options;
ctxt->_private = oldctxt->_private;
if (oldctxt->myDoc == NULL) {
newDoc = xmlNewDoc(BAD_CAST "1.0");
if (newDoc == NULL) {
ctxt->sax = oldsax;
ctxt->dict = NULL;
xmlFreeParserCtxt(ctxt);
return(XML_ERR_INTERNAL_ERROR);
}
newDoc->properties = XML_DOC_INTERNAL;
newDoc->dict = ctxt->dict;
xmlDictReference(newDoc->dict);
ctxt->myDoc = newDoc;
} else {
ctxt->myDoc = oldctxt->myDoc;
content = ctxt->myDoc->children;
last = ctxt->myDoc->last;
}
newRoot = xmlNewDocNode(ctxt->myDoc, NULL, BAD_CAST "pseudoroot", NULL);
if (newRoot == NULL) {
ctxt->sax = oldsax;
ctxt->dict = NULL;
xmlFreeParserCtxt(ctxt);
if (newDoc != NULL) {
xmlFreeDoc(newDoc);
}
return(XML_ERR_INTERNAL_ERROR);
}
ctxt->myDoc->children = NULL;
ctxt->myDoc->last = NULL;
xmlAddChild((xmlNodePtr) ctxt->myDoc, newRoot);
nodePush(ctxt, ctxt->myDoc->children);
ctxt->instate = XML_PARSER_CONTENT;
ctxt->depth = oldctxt->depth + 1;
ctxt->validate = 0;
ctxt->loadsubset = oldctxt->loadsubset;
if ((oldctxt->validate) || (oldctxt->replaceEntities != 0)) {
/*
* ID/IDREF registration will be done in xmlValidateElement below
*/
ctxt->loadsubset |= XML_SKIP_IDS;
}
ctxt->dictNames = oldctxt->dictNames;
ctxt->attsDefault = oldctxt->attsDefault;
ctxt->attsSpecial = oldctxt->attsSpecial;
xmlParseContent(ctxt);
if ((RAW == '<') && (NXT(1) == '/')) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
} else if (RAW != 0) {
xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL);
}
if (ctxt->node != ctxt->myDoc->children) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
}
if (!ctxt->wellFormed) {
if (ctxt->errNo == 0)
ret = XML_ERR_INTERNAL_ERROR;
else
ret = (xmlParserErrors)ctxt->errNo;
} else {
ret = XML_ERR_OK;
}
if ((lst != NULL) && (ret == XML_ERR_OK)) {
xmlNodePtr cur;
/*
* Return the newly created nodeset after unlinking it from
* they pseudo parent.
*/
cur = ctxt->myDoc->children->children;
*lst = cur;
while (cur != NULL) {
#ifdef LIBXML_VALID_ENABLED
if ((oldctxt->validate) && (oldctxt->wellFormed) &&
(oldctxt->myDoc) && (oldctxt->myDoc->intSubset) &&
(cur->type == XML_ELEMENT_NODE)) {
oldctxt->valid &= xmlValidateElement(&oldctxt->vctxt,
oldctxt->myDoc, cur);
}
#endif /* LIBXML_VALID_ENABLED */
cur->parent = NULL;
cur = cur->next;
}
ctxt->myDoc->children->children = NULL;
}
if (ctxt->myDoc != NULL) {
xmlFreeNode(ctxt->myDoc->children);
ctxt->myDoc->children = content;
ctxt->myDoc->last = last;
}
/*
* Record in the parent context the number of entities replacement
* done when parsing that reference.
*/
if (oldctxt != NULL)
oldctxt->nbentities += ctxt->nbentities;
/*
* Also record the last error if any
*/
if (ctxt->lastError.code != XML_ERR_OK)
xmlCopyError(&ctxt->lastError, &oldctxt->lastError);
ctxt->sax = oldsax;
ctxt->dict = NULL;
ctxt->attsDefault = NULL;
ctxt->attsSpecial = NULL;
xmlFreeParserCtxt(ctxt);
if (newDoc != NULL) {
xmlFreeDoc(newDoc);
}
return(ret);
}
/**
* xmlParseInNodeContext:
* @node: the context node
* @data: the input string
* @datalen: the input string length in bytes
* @options: a combination of xmlParserOption
* @lst: the return value for the set of parsed nodes
*
* Parse a well-balanced chunk of an XML document
* within the context (DTD, namespaces, etc ...) of the given node.
*
* The allowed sequence for the data is a Well Balanced Chunk defined by
* the content production in the XML grammar:
*
* [43] content ::= (element | CharData | Reference | CDSect | PI | Comment)*
*
* Returns XML_ERR_OK if the chunk is well balanced, and the parser
* error code otherwise
*/
xmlParserErrors
xmlParseInNodeContext(xmlNodePtr node, const char *data, int datalen,
int options, xmlNodePtr *lst) {
#ifdef SAX2
xmlParserCtxtPtr ctxt;
xmlDocPtr doc = NULL;
xmlNodePtr fake, cur;
int nsnr = 0;
xmlParserErrors ret = XML_ERR_OK;
/*
* check all input parameters, grab the document
*/
if ((lst == NULL) || (node == NULL) || (data == NULL) || (datalen < 0))
return(XML_ERR_INTERNAL_ERROR);
switch (node->type) {
case XML_ELEMENT_NODE:
case XML_ATTRIBUTE_NODE:
case XML_TEXT_NODE:
case XML_CDATA_SECTION_NODE:
case XML_ENTITY_REF_NODE:
case XML_PI_NODE:
case XML_COMMENT_NODE:
case XML_DOCUMENT_NODE:
case XML_HTML_DOCUMENT_NODE:
break;
default:
return(XML_ERR_INTERNAL_ERROR);
}
while ((node != NULL) && (node->type != XML_ELEMENT_NODE) &&
(node->type != XML_DOCUMENT_NODE) &&
(node->type != XML_HTML_DOCUMENT_NODE))
node = node->parent;
if (node == NULL)
return(XML_ERR_INTERNAL_ERROR);
if (node->type == XML_ELEMENT_NODE)
doc = node->doc;
else
doc = (xmlDocPtr) node;
if (doc == NULL)
return(XML_ERR_INTERNAL_ERROR);
/*
* allocate a context and set-up everything not related to the
* node position in the tree
*/
if (doc->type == XML_DOCUMENT_NODE)
ctxt = xmlCreateMemoryParserCtxt((char *) data, datalen);
#ifdef LIBXML_HTML_ENABLED
else if (doc->type == XML_HTML_DOCUMENT_NODE) {
ctxt = htmlCreateMemoryParserCtxt((char *) data, datalen);
/*
* When parsing in context, it makes no sense to add implied
* elements like html/body/etc...
*/
options |= HTML_PARSE_NOIMPLIED;
}
#endif
else
return(XML_ERR_INTERNAL_ERROR);
if (ctxt == NULL)
return(XML_ERR_NO_MEMORY);
/*
* Use input doc's dict if present, else assure XML_PARSE_NODICT is set.
* We need a dictionary for xmlDetectSAX2, so if there's no doc dict
* we must wait until the last moment to free the original one.
*/
if (doc->dict != NULL) {
if (ctxt->dict != NULL)
xmlDictFree(ctxt->dict);
ctxt->dict = doc->dict;
} else
options |= XML_PARSE_NODICT;
if (doc->encoding != NULL) {
xmlCharEncodingHandlerPtr hdlr;
if (ctxt->encoding != NULL)
xmlFree((xmlChar *) ctxt->encoding);
ctxt->encoding = xmlStrdup((const xmlChar *) doc->encoding);
hdlr = xmlFindCharEncodingHandler((const char *) doc->encoding);
if (hdlr != NULL) {
xmlSwitchToEncoding(ctxt, hdlr);
} else {
return(XML_ERR_UNSUPPORTED_ENCODING);
}
}
xmlCtxtUseOptionsInternal(ctxt, options, NULL);
xmlDetectSAX2(ctxt);
ctxt->myDoc = doc;
/* parsing in context, i.e. as within existing content */
ctxt->instate = XML_PARSER_CONTENT;
fake = xmlNewComment(NULL);
if (fake == NULL) {
xmlFreeParserCtxt(ctxt);
return(XML_ERR_NO_MEMORY);
}
xmlAddChild(node, fake);
if (node->type == XML_ELEMENT_NODE) {
nodePush(ctxt, node);
/*
* initialize the SAX2 namespaces stack
*/
cur = node;
while ((cur != NULL) && (cur->type == XML_ELEMENT_NODE)) {
xmlNsPtr ns = cur->nsDef;
const xmlChar *iprefix, *ihref;
while (ns != NULL) {
if (ctxt->dict) {
iprefix = xmlDictLookup(ctxt->dict, ns->prefix, -1);
ihref = xmlDictLookup(ctxt->dict, ns->href, -1);
} else {
iprefix = ns->prefix;
ihref = ns->href;
}
if (xmlGetNamespace(ctxt, iprefix) == NULL) {
nsPush(ctxt, iprefix, ihref);
nsnr++;
}
ns = ns->next;
}
cur = cur->parent;
}
}
if ((ctxt->validate) || (ctxt->replaceEntities != 0)) {
/*
* ID/IDREF registration will be done in xmlValidateElement below
*/
ctxt->loadsubset |= XML_SKIP_IDS;
}
#ifdef LIBXML_HTML_ENABLED
if (doc->type == XML_HTML_DOCUMENT_NODE)
__htmlParseContent(ctxt);
else
#endif
xmlParseContent(ctxt);
nsPop(ctxt, nsnr);
if ((RAW == '<') && (NXT(1) == '/')) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
} else if (RAW != 0) {
xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL);
}
if ((ctxt->node != NULL) && (ctxt->node != node)) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
ctxt->wellFormed = 0;
}
if (!ctxt->wellFormed) {
if (ctxt->errNo == 0)
ret = XML_ERR_INTERNAL_ERROR;
else
ret = (xmlParserErrors)ctxt->errNo;
} else {
ret = XML_ERR_OK;
}
/*
* Return the newly created nodeset after unlinking it from
* the pseudo sibling.
*/
cur = fake->next;
fake->next = NULL;
node->last = fake;
if (cur != NULL) {
cur->prev = NULL;
}
*lst = cur;
while (cur != NULL) {
cur->parent = NULL;
cur = cur->next;
}
xmlUnlinkNode(fake);
xmlFreeNode(fake);
if (ret != XML_ERR_OK) {
xmlFreeNodeList(*lst);
*lst = NULL;
}
if (doc->dict != NULL)
ctxt->dict = NULL;
xmlFreeParserCtxt(ctxt);
return(ret);
#else /* !SAX2 */
return(XML_ERR_INTERNAL_ERROR);
#endif
}
#ifdef LIBXML_SAX1_ENABLED
/**
* xmlParseBalancedChunkMemoryRecover:
* @doc: the document the chunk pertains to
* @sax: the SAX handler bloc (possibly NULL)
* @user_data: The user data returned on SAX callbacks (possibly NULL)
* @depth: Used for loop detection, use 0
* @string: the input string in UTF8 or ISO-Latin (zero terminated)
* @lst: the return value for the set of parsed nodes
* @recover: return nodes even if the data is broken (use 0)
*
*
* Parse a well-balanced chunk of an XML document
* called by the parser
* The allowed sequence for the Well Balanced Chunk is the one defined by
* the content production in the XML grammar:
*
* [43] content ::= (element | CharData | Reference | CDSect | PI | Comment)*
*
* Returns 0 if the chunk is well balanced, -1 in case of args problem and
* the parser error code otherwise
*
* In case recover is set to 1, the nodelist will not be empty even if
* the parsed chunk is not well balanced, assuming the parsing succeeded to
* some extent.
*/
int
xmlParseBalancedChunkMemoryRecover(xmlDocPtr doc, xmlSAXHandlerPtr sax,
void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst,
int recover) {
xmlParserCtxtPtr ctxt;
xmlDocPtr newDoc;
xmlSAXHandlerPtr oldsax = NULL;
xmlNodePtr content, newRoot;
int size;
int ret = 0;
if (depth > 40) {
return(XML_ERR_ENTITY_LOOP);
}
if (lst != NULL)
*lst = NULL;
if (string == NULL)
return(-1);
size = xmlStrlen(string);
ctxt = xmlCreateMemoryParserCtxt((char *) string, size);
if (ctxt == NULL) return(-1);
ctxt->userData = ctxt;
if (sax != NULL) {
oldsax = ctxt->sax;
ctxt->sax = sax;
if (user_data != NULL)
ctxt->userData = user_data;
}
newDoc = xmlNewDoc(BAD_CAST "1.0");
if (newDoc == NULL) {
xmlFreeParserCtxt(ctxt);
return(-1);
}
newDoc->properties = XML_DOC_INTERNAL;
if ((doc != NULL) && (doc->dict != NULL)) {
xmlDictFree(ctxt->dict);
ctxt->dict = doc->dict;
xmlDictReference(ctxt->dict);
ctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST "xml", 3);
ctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST "xmlns", 5);
ctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36);
ctxt->dictNames = 1;
} else {
xmlCtxtUseOptionsInternal(ctxt, XML_PARSE_NODICT, NULL);
}
if (doc != NULL) {
newDoc->intSubset = doc->intSubset;
newDoc->extSubset = doc->extSubset;
}
newRoot = xmlNewDocNode(newDoc, NULL, BAD_CAST "pseudoroot", NULL);
if (newRoot == NULL) {
if (sax != NULL)
ctxt->sax = oldsax;
xmlFreeParserCtxt(ctxt);
newDoc->intSubset = NULL;
newDoc->extSubset = NULL;
xmlFreeDoc(newDoc);
return(-1);
}
xmlAddChild((xmlNodePtr) newDoc, newRoot);
nodePush(ctxt, newRoot);
if (doc == NULL) {
ctxt->myDoc = newDoc;
} else {
ctxt->myDoc = newDoc;
newDoc->children->doc = doc;
/* Ensure that doc has XML spec namespace */
xmlSearchNsByHref(doc, (xmlNodePtr)doc, XML_XML_NAMESPACE);
newDoc->oldNs = doc->oldNs;
}
ctxt->instate = XML_PARSER_CONTENT;
ctxt->depth = depth;
/*
* Doing validity checking on chunk doesn't make sense
*/
ctxt->validate = 0;
ctxt->loadsubset = 0;
xmlDetectSAX2(ctxt);
if ( doc != NULL ){
content = doc->children;
doc->children = NULL;
xmlParseContent(ctxt);
doc->children = content;
}
else {
xmlParseContent(ctxt);
}
if ((RAW == '<') && (NXT(1) == '/')) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
} else if (RAW != 0) {
xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL);
}
if (ctxt->node != newDoc->children) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
}
if (!ctxt->wellFormed) {
if (ctxt->errNo == 0)
ret = 1;
else
ret = ctxt->errNo;
} else {
ret = 0;
}
if ((lst != NULL) && ((ret == 0) || (recover == 1))) {
xmlNodePtr cur;
/*
* Return the newly created nodeset after unlinking it from
* they pseudo parent.
*/
cur = newDoc->children->children;
*lst = cur;
while (cur != NULL) {
xmlSetTreeDoc(cur, doc);
cur->parent = NULL;
cur = cur->next;
}
newDoc->children->children = NULL;
}
if (sax != NULL)
ctxt->sax = oldsax;
xmlFreeParserCtxt(ctxt);
newDoc->intSubset = NULL;
newDoc->extSubset = NULL;
newDoc->oldNs = NULL;
xmlFreeDoc(newDoc);
return(ret);
}
/**
* xmlSAXParseEntity:
* @sax: the SAX handler block
* @filename: the filename
*
* parse an XML external entity out of context and build a tree.
* It use the given SAX function block to handle the parsing callback.
* If sax is NULL, fallback to the default DOM tree building routines.
*
* [78] extParsedEnt ::= TextDecl? content
*
* This correspond to a "Well Balanced" chunk
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlSAXParseEntity(xmlSAXHandlerPtr sax, const char *filename) {
xmlDocPtr ret;
xmlParserCtxtPtr ctxt;
ctxt = xmlCreateFileParserCtxt(filename);
if (ctxt == NULL) {
return(NULL);
}
if (sax != NULL) {
if (ctxt->sax != NULL)
xmlFree(ctxt->sax);
ctxt->sax = sax;
ctxt->userData = NULL;
}
xmlParseExtParsedEnt(ctxt);
if (ctxt->wellFormed)
ret = ctxt->myDoc;
else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
if (sax != NULL)
ctxt->sax = NULL;
xmlFreeParserCtxt(ctxt);
return(ret);
}
/**
* xmlParseEntity:
* @filename: the filename
*
* parse an XML external entity out of context and build a tree.
*
* [78] extParsedEnt ::= TextDecl? content
*
* This correspond to a "Well Balanced" chunk
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlParseEntity(const char *filename) {
return(xmlSAXParseEntity(NULL, filename));
}
#endif /* LIBXML_SAX1_ENABLED */
/**
* xmlCreateEntityParserCtxtInternal:
* @URL: the entity URL
* @ID: the entity PUBLIC ID
* @base: a possible base for the target URI
* @pctx: parser context used to set options on new context
*
* Create a parser context for an external entity
* Automatic support for ZLIB/Compress compressed document is provided
* by default if found at compile-time.
*
* Returns the new parser context or NULL
*/
static xmlParserCtxtPtr
xmlCreateEntityParserCtxtInternal(const xmlChar *URL, const xmlChar *ID,
const xmlChar *base, xmlParserCtxtPtr pctx) {
xmlParserCtxtPtr ctxt;
xmlParserInputPtr inputStream;
char *directory = NULL;
xmlChar *uri;
ctxt = xmlNewParserCtxt();
if (ctxt == NULL) {
return(NULL);
}
if (pctx != NULL) {
ctxt->options = pctx->options;
ctxt->_private = pctx->_private;
}
uri = xmlBuildURI(URL, base);
if (uri == NULL) {
inputStream = xmlLoadExternalEntity((char *)URL, (char *)ID, ctxt);
if (inputStream == NULL) {
xmlFreeParserCtxt(ctxt);
return(NULL);
}
inputPush(ctxt, inputStream);
if ((ctxt->directory == NULL) && (directory == NULL))
directory = xmlParserGetDirectory((char *)URL);
if ((ctxt->directory == NULL) && (directory != NULL))
ctxt->directory = directory;
} else {
inputStream = xmlLoadExternalEntity((char *)uri, (char *)ID, ctxt);
if (inputStream == NULL) {
xmlFree(uri);
xmlFreeParserCtxt(ctxt);
return(NULL);
}
inputPush(ctxt, inputStream);
if ((ctxt->directory == NULL) && (directory == NULL))
directory = xmlParserGetDirectory((char *)uri);
if ((ctxt->directory == NULL) && (directory != NULL))
ctxt->directory = directory;
xmlFree(uri);
}
return(ctxt);
}
/**
* xmlCreateEntityParserCtxt:
* @URL: the entity URL
* @ID: the entity PUBLIC ID
* @base: a possible base for the target URI
*
* Create a parser context for an external entity
* Automatic support for ZLIB/Compress compressed document is provided
* by default if found at compile-time.
*
* Returns the new parser context or NULL
*/
xmlParserCtxtPtr
xmlCreateEntityParserCtxt(const xmlChar *URL, const xmlChar *ID,
const xmlChar *base) {
return xmlCreateEntityParserCtxtInternal(URL, ID, base, NULL);
}
/************************************************************************
* *
* Front ends when parsing from a file *
* *
************************************************************************/
/**
* xmlCreateURLParserCtxt:
* @filename: the filename or URL
* @options: a combination of xmlParserOption
*
* Create a parser context for a file or URL content.
* Automatic support for ZLIB/Compress compressed document is provided
* by default if found at compile-time and for file accesses
*
* Returns the new parser context or NULL
*/
xmlParserCtxtPtr
xmlCreateURLParserCtxt(const char *filename, int options)
{
xmlParserCtxtPtr ctxt;
xmlParserInputPtr inputStream;
char *directory = NULL;
ctxt = xmlNewParserCtxt();
if (ctxt == NULL) {
xmlErrMemory(NULL, "cannot allocate parser context");
return(NULL);
}
if (options)
xmlCtxtUseOptionsInternal(ctxt, options, NULL);
ctxt->linenumbers = 1;
inputStream = xmlLoadExternalEntity(filename, NULL, ctxt);
if (inputStream == NULL) {
xmlFreeParserCtxt(ctxt);
return(NULL);
}
inputPush(ctxt, inputStream);
if ((ctxt->directory == NULL) && (directory == NULL))
directory = xmlParserGetDirectory(filename);
if ((ctxt->directory == NULL) && (directory != NULL))
ctxt->directory = directory;
return(ctxt);
}
/**
* xmlCreateFileParserCtxt:
* @filename: the filename
*
* Create a parser context for a file content.
* Automatic support for ZLIB/Compress compressed document is provided
* by default if found at compile-time.
*
* Returns the new parser context or NULL
*/
xmlParserCtxtPtr
xmlCreateFileParserCtxt(const char *filename)
{
return(xmlCreateURLParserCtxt(filename, 0));
}
#ifdef LIBXML_SAX1_ENABLED
/**
* xmlSAXParseFileWithData:
* @sax: the SAX handler block
* @filename: the filename
* @recovery: work in recovery mode, i.e. tries to read no Well Formed
* documents
* @data: the userdata
*
* parse an XML file and build a tree. Automatic support for ZLIB/Compress
* compressed document is provided by default if found at compile-time.
* It use the given SAX function block to handle the parsing callback.
* If sax is NULL, fallback to the default DOM tree building routines.
*
* User data (void *) is stored within the parser context in the
* context's _private member, so it is available nearly everywhere in libxml
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlSAXParseFileWithData(xmlSAXHandlerPtr sax, const char *filename,
int recovery, void *data) {
xmlDocPtr ret;
xmlParserCtxtPtr ctxt;
xmlInitParser();
ctxt = xmlCreateFileParserCtxt(filename);
if (ctxt == NULL) {
return(NULL);
}
if (sax != NULL) {
if (ctxt->sax != NULL)
xmlFree(ctxt->sax);
ctxt->sax = sax;
}
xmlDetectSAX2(ctxt);
if (data!=NULL) {
ctxt->_private = data;
}
if (ctxt->directory == NULL)
ctxt->directory = xmlParserGetDirectory(filename);
ctxt->recovery = recovery;
xmlParseDocument(ctxt);
if ((ctxt->wellFormed) || recovery) {
ret = ctxt->myDoc;
if (ret != NULL) {
if (ctxt->input->buf->compressed > 0)
ret->compression = 9;
else
ret->compression = ctxt->input->buf->compressed;
}
}
else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
if (sax != NULL)
ctxt->sax = NULL;
xmlFreeParserCtxt(ctxt);
return(ret);
}
/**
* xmlSAXParseFile:
* @sax: the SAX handler block
* @filename: the filename
* @recovery: work in recovery mode, i.e. tries to read no Well Formed
* documents
*
* parse an XML file and build a tree. Automatic support for ZLIB/Compress
* compressed document is provided by default if found at compile-time.
* It use the given SAX function block to handle the parsing callback.
* If sax is NULL, fallback to the default DOM tree building routines.
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlSAXParseFile(xmlSAXHandlerPtr sax, const char *filename,
int recovery) {
return(xmlSAXParseFileWithData(sax,filename,recovery,NULL));
}
/**
* xmlRecoverDoc:
* @cur: a pointer to an array of xmlChar
*
* parse an XML in-memory document and build a tree.
* In the case the document is not Well Formed, a attempt to build a
* tree is tried anyway
*
* Returns the resulting document tree or NULL in case of failure
*/
xmlDocPtr
xmlRecoverDoc(const xmlChar *cur) {
return(xmlSAXParseDoc(NULL, cur, 1));
}
/**
* xmlParseFile:
* @filename: the filename
*
* parse an XML file and build a tree. Automatic support for ZLIB/Compress
* compressed document is provided by default if found at compile-time.
*
* Returns the resulting document tree if the file was wellformed,
* NULL otherwise.
*/
xmlDocPtr
xmlParseFile(const char *filename) {
return(xmlSAXParseFile(NULL, filename, 0));
}
/**
* xmlRecoverFile:
* @filename: the filename
*
* parse an XML file and build a tree. Automatic support for ZLIB/Compress
* compressed document is provided by default if found at compile-time.
* In the case the document is not Well Formed, it attempts to build
* a tree anyway
*
* Returns the resulting document tree or NULL in case of failure
*/
xmlDocPtr
xmlRecoverFile(const char *filename) {
return(xmlSAXParseFile(NULL, filename, 1));
}
/**
* xmlSetupParserForBuffer:
* @ctxt: an XML parser context
* @buffer: a xmlChar * buffer
* @filename: a file name
*
* Setup the parser context to parse a new buffer; Clears any prior
* contents from the parser context. The buffer parameter must not be
* NULL, but the filename parameter can be
*/
void
xmlSetupParserForBuffer(xmlParserCtxtPtr ctxt, const xmlChar* buffer,
const char* filename)
{
xmlParserInputPtr input;
if ((ctxt == NULL) || (buffer == NULL))
return;
input = xmlNewInputStream(ctxt);
if (input == NULL) {
xmlErrMemory(NULL, "parsing new buffer: out of memory\n");
xmlClearParserCtxt(ctxt);
return;
}
xmlClearParserCtxt(ctxt);
if (filename != NULL)
input->filename = (char *) xmlCanonicPath((const xmlChar *)filename);
input->base = buffer;
input->cur = buffer;
input->end = &buffer[xmlStrlen(buffer)];
inputPush(ctxt, input);
}
/**
* xmlSAXUserParseFile:
* @sax: a SAX handler
* @user_data: The user data returned on SAX callbacks
* @filename: a file name
*
* parse an XML file and call the given SAX handler routines.
* Automatic support for ZLIB/Compress compressed document is provided
*
* Returns 0 in case of success or a error number otherwise
*/
int
xmlSAXUserParseFile(xmlSAXHandlerPtr sax, void *user_data,
const char *filename) {
int ret = 0;
xmlParserCtxtPtr ctxt;
ctxt = xmlCreateFileParserCtxt(filename);
if (ctxt == NULL) return -1;
if (ctxt->sax != (xmlSAXHandlerPtr) &xmlDefaultSAXHandler)
xmlFree(ctxt->sax);
ctxt->sax = sax;
xmlDetectSAX2(ctxt);
if (user_data != NULL)
ctxt->userData = user_data;
xmlParseDocument(ctxt);
if (ctxt->wellFormed)
ret = 0;
else {
if (ctxt->errNo != 0)
ret = ctxt->errNo;
else
ret = -1;
}
if (sax != NULL)
ctxt->sax = NULL;
if (ctxt->myDoc != NULL) {
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
return ret;
}
#endif /* LIBXML_SAX1_ENABLED */
/************************************************************************
* *
* Front ends when parsing from memory *
* *
************************************************************************/
/**
* xmlCreateMemoryParserCtxt:
* @buffer: a pointer to a char array
* @size: the size of the array
*
* Create a parser context for an XML in-memory document.
*
* Returns the new parser context or NULL
*/
xmlParserCtxtPtr
xmlCreateMemoryParserCtxt(const char *buffer, int size) {
xmlParserCtxtPtr ctxt;
xmlParserInputPtr input;
xmlParserInputBufferPtr buf;
if (buffer == NULL)
return(NULL);
if (size <= 0)
return(NULL);
ctxt = xmlNewParserCtxt();
if (ctxt == NULL)
return(NULL);
/* TODO: xmlParserInputBufferCreateStatic, requires some serious changes */
buf = xmlParserInputBufferCreateMem(buffer, size, XML_CHAR_ENCODING_NONE);
if (buf == NULL) {
xmlFreeParserCtxt(ctxt);
return(NULL);
}
input = xmlNewInputStream(ctxt);
if (input == NULL) {
xmlFreeParserInputBuffer(buf);
xmlFreeParserCtxt(ctxt);
return(NULL);
}
input->filename = NULL;
input->buf = buf;
xmlBufResetInput(input->buf->buffer, input);
inputPush(ctxt, input);
return(ctxt);
}
#ifdef LIBXML_SAX1_ENABLED
/**
* xmlSAXParseMemoryWithData:
* @sax: the SAX handler block
* @buffer: an pointer to a char array
* @size: the size of the array
* @recovery: work in recovery mode, i.e. tries to read no Well Formed
* documents
* @data: the userdata
*
* parse an XML in-memory block and use the given SAX function block
* to handle the parsing callback. If sax is NULL, fallback to the default
* DOM tree building routines.
*
* User data (void *) is stored within the parser context in the
* context's _private member, so it is available nearly everywhere in libxml
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlSAXParseMemoryWithData(xmlSAXHandlerPtr sax, const char *buffer,
int size, int recovery, void *data) {
xmlDocPtr ret;
xmlParserCtxtPtr ctxt;
xmlInitParser();
ctxt = xmlCreateMemoryParserCtxt(buffer, size);
if (ctxt == NULL) return(NULL);
if (sax != NULL) {
if (ctxt->sax != NULL)
xmlFree(ctxt->sax);
ctxt->sax = sax;
}
xmlDetectSAX2(ctxt);
if (data!=NULL) {
ctxt->_private=data;
}
ctxt->recovery = recovery;
xmlParseDocument(ctxt);
if ((ctxt->wellFormed) || recovery) ret = ctxt->myDoc;
else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
if (sax != NULL)
ctxt->sax = NULL;
xmlFreeParserCtxt(ctxt);
return(ret);
}
/**
* xmlSAXParseMemory:
* @sax: the SAX handler block
* @buffer: an pointer to a char array
* @size: the size of the array
* @recovery: work in recovery mode, i.e. tries to read not Well Formed
* documents
*
* parse an XML in-memory block and use the given SAX function block
* to handle the parsing callback. If sax is NULL, fallback to the default
* DOM tree building routines.
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlSAXParseMemory(xmlSAXHandlerPtr sax, const char *buffer,
int size, int recovery) {
return xmlSAXParseMemoryWithData(sax, buffer, size, recovery, NULL);
}
/**
* xmlParseMemory:
* @buffer: an pointer to a char array
* @size: the size of the array
*
* parse an XML in-memory block and build a tree.
*
* Returns the resulting document tree
*/
xmlDocPtr xmlParseMemory(const char *buffer, int size) {
return(xmlSAXParseMemory(NULL, buffer, size, 0));
}
/**
* xmlRecoverMemory:
* @buffer: an pointer to a char array
* @size: the size of the array
*
* parse an XML in-memory block and build a tree.
* In the case the document is not Well Formed, an attempt to
* build a tree is tried anyway
*
* Returns the resulting document tree or NULL in case of error
*/
xmlDocPtr xmlRecoverMemory(const char *buffer, int size) {
return(xmlSAXParseMemory(NULL, buffer, size, 1));
}
/**
* xmlSAXUserParseMemory:
* @sax: a SAX handler
* @user_data: The user data returned on SAX callbacks
* @buffer: an in-memory XML document input
* @size: the length of the XML document in bytes
*
* A better SAX parsing routine.
* parse an XML in-memory buffer and call the given SAX handler routines.
*
* Returns 0 in case of success or a error number otherwise
*/
int xmlSAXUserParseMemory(xmlSAXHandlerPtr sax, void *user_data,
const char *buffer, int size) {
int ret = 0;
xmlParserCtxtPtr ctxt;
xmlInitParser();
ctxt = xmlCreateMemoryParserCtxt(buffer, size);
if (ctxt == NULL) return -1;
if (ctxt->sax != (xmlSAXHandlerPtr) &xmlDefaultSAXHandler)
xmlFree(ctxt->sax);
ctxt->sax = sax;
xmlDetectSAX2(ctxt);
if (user_data != NULL)
ctxt->userData = user_data;
xmlParseDocument(ctxt);
if (ctxt->wellFormed)
ret = 0;
else {
if (ctxt->errNo != 0)
ret = ctxt->errNo;
else
ret = -1;
}
if (sax != NULL)
ctxt->sax = NULL;
if (ctxt->myDoc != NULL) {
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
return ret;
}
#endif /* LIBXML_SAX1_ENABLED */
/**
* xmlCreateDocParserCtxt:
* @cur: a pointer to an array of xmlChar
*
* Creates a parser context for an XML in-memory document.
*
* Returns the new parser context or NULL
*/
xmlParserCtxtPtr
xmlCreateDocParserCtxt(const xmlChar *cur) {
int len;
if (cur == NULL)
return(NULL);
len = xmlStrlen(cur);
return(xmlCreateMemoryParserCtxt((const char *)cur, len));
}
#ifdef LIBXML_SAX1_ENABLED
/**
* xmlSAXParseDoc:
* @sax: the SAX handler block
* @cur: a pointer to an array of xmlChar
* @recovery: work in recovery mode, i.e. tries to read no Well Formed
* documents
*
* parse an XML in-memory document and build a tree.
* It use the given SAX function block to handle the parsing callback.
* If sax is NULL, fallback to the default DOM tree building routines.
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlSAXParseDoc(xmlSAXHandlerPtr sax, const xmlChar *cur, int recovery) {
xmlDocPtr ret;
xmlParserCtxtPtr ctxt;
xmlSAXHandlerPtr oldsax = NULL;
if (cur == NULL) return(NULL);
ctxt = xmlCreateDocParserCtxt(cur);
if (ctxt == NULL) return(NULL);
if (sax != NULL) {
oldsax = ctxt->sax;
ctxt->sax = sax;
ctxt->userData = NULL;
}
xmlDetectSAX2(ctxt);
xmlParseDocument(ctxt);
if ((ctxt->wellFormed) || recovery) ret = ctxt->myDoc;
else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
if (sax != NULL)
ctxt->sax = oldsax;
xmlFreeParserCtxt(ctxt);
return(ret);
}
/**
* xmlParseDoc:
* @cur: a pointer to an array of xmlChar
*
* parse an XML in-memory document and build a tree.
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlParseDoc(const xmlChar *cur) {
return(xmlSAXParseDoc(NULL, cur, 0));
}
#endif /* LIBXML_SAX1_ENABLED */
#ifdef LIBXML_LEGACY_ENABLED
/************************************************************************
* *
* Specific function to keep track of entities references *
* and used by the XSLT debugger *
* *
************************************************************************/
static xmlEntityReferenceFunc xmlEntityRefFunc = NULL;
/**
* xmlAddEntityReference:
* @ent : A valid entity
* @firstNode : A valid first node for children of entity
* @lastNode : A valid last node of children entity
*
* Notify of a reference to an entity of type XML_EXTERNAL_GENERAL_PARSED_ENTITY
*/
static void
xmlAddEntityReference(xmlEntityPtr ent, xmlNodePtr firstNode,
xmlNodePtr lastNode)
{
if (xmlEntityRefFunc != NULL) {
(*xmlEntityRefFunc) (ent, firstNode, lastNode);
}
}
/**
* xmlSetEntityReferenceFunc:
* @func: A valid function
*
* Set the function to call call back when a xml reference has been made
*/
void
xmlSetEntityReferenceFunc(xmlEntityReferenceFunc func)
{
xmlEntityRefFunc = func;
}
#endif /* LIBXML_LEGACY_ENABLED */
/************************************************************************
* *
* Miscellaneous *
* *
************************************************************************/
#ifdef LIBXML_XPATH_ENABLED
#include <libxml/xpath.h>
#endif
extern void XMLCDECL xmlGenericErrorDefaultFunc(void *ctx, const char *msg, ...);
static int xmlParserInitialized = 0;
/**
* xmlInitParser:
*
* Initialization function for the XML parser.
* This is not reentrant. Call once before processing in case of
* use in multithreaded programs.
*/
void
xmlInitParser(void) {
if (xmlParserInitialized != 0)
return;
#ifdef LIBXML_THREAD_ENABLED
__xmlGlobalInitMutexLock();
if (xmlParserInitialized == 0) {
#endif
xmlInitThreads();
xmlInitGlobals();
if ((xmlGenericError == xmlGenericErrorDefaultFunc) ||
(xmlGenericError == NULL))
initGenericErrorDefaultFunc(NULL);
xmlInitMemory();
xmlInitializeDict();
xmlInitCharEncodingHandlers();
xmlDefaultSAXHandlerInit();
xmlRegisterDefaultInputCallbacks();
#ifdef LIBXML_OUTPUT_ENABLED
xmlRegisterDefaultOutputCallbacks();
#endif /* LIBXML_OUTPUT_ENABLED */
#ifdef LIBXML_HTML_ENABLED
htmlInitAutoClose();
htmlDefaultSAXHandlerInit();
#endif
#ifdef LIBXML_XPATH_ENABLED
xmlXPathInit();
#endif
xmlParserInitialized = 1;
#ifdef LIBXML_THREAD_ENABLED
}
__xmlGlobalInitMutexUnlock();
#endif
}
/**
* xmlCleanupParser:
*
* This function name is somewhat misleading. It does not clean up
* parser state, it cleans up memory allocated by the library itself.
* It is a cleanup function for the XML library. It tries to reclaim all
* related global memory allocated for the library processing.
* It doesn't deallocate any document related memory. One should
* call xmlCleanupParser() only when the process has finished using
* the library and all XML/HTML documents built with it.
* See also xmlInitParser() which has the opposite function of preparing
* the library for operations.
*
* WARNING: if your application is multithreaded or has plugin support
* calling this may crash the application if another thread or
* a plugin is still using libxml2. It's sometimes very hard to
* guess if libxml2 is in use in the application, some libraries
* or plugins may use it without notice. In case of doubt abstain
* from calling this function or do it just before calling exit()
* to avoid leak reports from valgrind !
*/
void
xmlCleanupParser(void) {
if (!xmlParserInitialized)
return;
xmlCleanupCharEncodingHandlers();
#ifdef LIBXML_CATALOG_ENABLED
xmlCatalogCleanup();
#endif
xmlDictCleanup();
xmlCleanupInputCallbacks();
#ifdef LIBXML_OUTPUT_ENABLED
xmlCleanupOutputCallbacks();
#endif
#ifdef LIBXML_SCHEMAS_ENABLED
xmlSchemaCleanupTypes();
xmlRelaxNGCleanupTypes();
#endif
xmlResetLastError();
xmlCleanupGlobals();
xmlCleanupThreads(); /* must be last if called not from the main thread */
xmlCleanupMemory();
xmlParserInitialized = 0;
}
/************************************************************************
* *
* New set (2.6.0) of simpler and more flexible APIs *
* *
************************************************************************/
/**
* DICT_FREE:
* @str: a string
*
* Free a string if it is not owned by the "dict" dictionary in the
* current scope
*/
#define DICT_FREE(str) \
if ((str) && ((!dict) || \
(xmlDictOwns(dict, (const xmlChar *)(str)) == 0))) \
xmlFree((char *)(str));
/**
* xmlCtxtReset:
* @ctxt: an XML parser context
*
* Reset a parser context
*/
void
xmlCtxtReset(xmlParserCtxtPtr ctxt)
{
xmlParserInputPtr input;
xmlDictPtr dict;
if (ctxt == NULL)
return;
dict = ctxt->dict;
while ((input = inputPop(ctxt)) != NULL) { /* Non consuming */
xmlFreeInputStream(input);
}
ctxt->inputNr = 0;
ctxt->input = NULL;
ctxt->spaceNr = 0;
if (ctxt->spaceTab != NULL) {
ctxt->spaceTab[0] = -1;
ctxt->space = &ctxt->spaceTab[0];
} else {
ctxt->space = NULL;
}
ctxt->nodeNr = 0;
ctxt->node = NULL;
ctxt->nameNr = 0;
ctxt->name = NULL;
DICT_FREE(ctxt->version);
ctxt->version = NULL;
DICT_FREE(ctxt->encoding);
ctxt->encoding = NULL;
DICT_FREE(ctxt->directory);
ctxt->directory = NULL;
DICT_FREE(ctxt->extSubURI);
ctxt->extSubURI = NULL;
DICT_FREE(ctxt->extSubSystem);
ctxt->extSubSystem = NULL;
if (ctxt->myDoc != NULL)
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
ctxt->standalone = -1;
ctxt->hasExternalSubset = 0;
ctxt->hasPErefs = 0;
ctxt->html = 0;
ctxt->external = 0;
ctxt->instate = XML_PARSER_START;
ctxt->token = 0;
ctxt->wellFormed = 1;
ctxt->nsWellFormed = 1;
ctxt->disableSAX = 0;
ctxt->valid = 1;
#if 0
ctxt->vctxt.userData = ctxt;
ctxt->vctxt.error = xmlParserValidityError;
ctxt->vctxt.warning = xmlParserValidityWarning;
#endif
ctxt->record_info = 0;
ctxt->nbChars = 0;
ctxt->checkIndex = 0;
ctxt->inSubset = 0;
ctxt->errNo = XML_ERR_OK;
ctxt->depth = 0;
ctxt->charset = XML_CHAR_ENCODING_UTF8;
ctxt->catalogs = NULL;
ctxt->nbentities = 0;
ctxt->sizeentities = 0;
ctxt->sizeentcopy = 0;
xmlInitNodeInfoSeq(&ctxt->node_seq);
if (ctxt->attsDefault != NULL) {
xmlHashFree(ctxt->attsDefault, (xmlHashDeallocator) xmlFree);
ctxt->attsDefault = NULL;
}
if (ctxt->attsSpecial != NULL) {
xmlHashFree(ctxt->attsSpecial, NULL);
ctxt->attsSpecial = NULL;
}
#ifdef LIBXML_CATALOG_ENABLED
if (ctxt->catalogs != NULL)
xmlCatalogFreeLocal(ctxt->catalogs);
#endif
if (ctxt->lastError.code != XML_ERR_OK)
xmlResetError(&ctxt->lastError);
}
/**
* xmlCtxtResetPush:
* @ctxt: an XML parser context
* @chunk: a pointer to an array of chars
* @size: number of chars in the array
* @filename: an optional file name or URI
* @encoding: the document encoding, or NULL
*
* Reset a push parser context
*
* Returns 0 in case of success and 1 in case of error
*/
int
xmlCtxtResetPush(xmlParserCtxtPtr ctxt, const char *chunk,
int size, const char *filename, const char *encoding)
{
xmlParserInputPtr inputStream;
xmlParserInputBufferPtr buf;
xmlCharEncoding enc = XML_CHAR_ENCODING_NONE;
if (ctxt == NULL)
return(1);
if ((encoding == NULL) && (chunk != NULL) && (size >= 4))
enc = xmlDetectCharEncoding((const xmlChar *) chunk, size);
buf = xmlAllocParserInputBuffer(enc);
if (buf == NULL)
return(1);
if (ctxt == NULL) {
xmlFreeParserInputBuffer(buf);
return(1);
}
xmlCtxtReset(ctxt);
if (ctxt->pushTab == NULL) {
ctxt->pushTab = (void **) xmlMalloc(ctxt->nameMax * 3 *
sizeof(xmlChar *));
if (ctxt->pushTab == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFreeParserInputBuffer(buf);
return(1);
}
}
if (filename == NULL) {
ctxt->directory = NULL;
} else {
ctxt->directory = xmlParserGetDirectory(filename);
}
inputStream = xmlNewInputStream(ctxt);
if (inputStream == NULL) {
xmlFreeParserInputBuffer(buf);
return(1);
}
if (filename == NULL)
inputStream->filename = NULL;
else
inputStream->filename = (char *)
xmlCanonicPath((const xmlChar *) filename);
inputStream->buf = buf;
xmlBufResetInput(buf->buffer, inputStream);
inputPush(ctxt, inputStream);
if ((size > 0) && (chunk != NULL) && (ctxt->input != NULL) &&
(ctxt->input->buf != NULL)) {
size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input);
size_t cur = ctxt->input->cur - ctxt->input->base;
xmlParserInputBufferPush(ctxt->input->buf, size, chunk);
xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, cur);
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext, "PP: pushed %d\n", size);
#endif
}
if (encoding != NULL) {
xmlCharEncodingHandlerPtr hdlr;
if (ctxt->encoding != NULL)
xmlFree((xmlChar *) ctxt->encoding);
ctxt->encoding = xmlStrdup((const xmlChar *) encoding);
hdlr = xmlFindCharEncodingHandler(encoding);
if (hdlr != NULL) {
xmlSwitchToEncoding(ctxt, hdlr);
} else {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNSUPPORTED_ENCODING,
"Unsupported encoding %s\n", BAD_CAST encoding);
}
} else if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
return(0);
}
/**
* xmlCtxtUseOptionsInternal:
* @ctxt: an XML parser context
* @options: a combination of xmlParserOption
* @encoding: the user provided encoding to use
*
* Applies the options to the parser context
*
* Returns 0 in case of success, the set of unknown or unimplemented options
* in case of error.
*/
static int
xmlCtxtUseOptionsInternal(xmlParserCtxtPtr ctxt, int options, const char *encoding)
{
if (ctxt == NULL)
return(-1);
if (encoding != NULL) {
if (ctxt->encoding != NULL)
xmlFree((xmlChar *) ctxt->encoding);
ctxt->encoding = xmlStrdup((const xmlChar *) encoding);
}
if (options & XML_PARSE_RECOVER) {
ctxt->recovery = 1;
options -= XML_PARSE_RECOVER;
ctxt->options |= XML_PARSE_RECOVER;
} else
ctxt->recovery = 0;
if (options & XML_PARSE_DTDLOAD) {
ctxt->loadsubset = XML_DETECT_IDS;
options -= XML_PARSE_DTDLOAD;
ctxt->options |= XML_PARSE_DTDLOAD;
} else
ctxt->loadsubset = 0;
if (options & XML_PARSE_DTDATTR) {
ctxt->loadsubset |= XML_COMPLETE_ATTRS;
options -= XML_PARSE_DTDATTR;
ctxt->options |= XML_PARSE_DTDATTR;
}
if (options & XML_PARSE_NOENT) {
ctxt->replaceEntities = 1;
/* ctxt->loadsubset |= XML_DETECT_IDS; */
options -= XML_PARSE_NOENT;
ctxt->options |= XML_PARSE_NOENT;
} else
ctxt->replaceEntities = 0;
if (options & XML_PARSE_PEDANTIC) {
ctxt->pedantic = 1;
options -= XML_PARSE_PEDANTIC;
ctxt->options |= XML_PARSE_PEDANTIC;
} else
ctxt->pedantic = 0;
if (options & XML_PARSE_NOBLANKS) {
ctxt->keepBlanks = 0;
ctxt->sax->ignorableWhitespace = xmlSAX2IgnorableWhitespace;
options -= XML_PARSE_NOBLANKS;
ctxt->options |= XML_PARSE_NOBLANKS;
} else
ctxt->keepBlanks = 1;
if (options & XML_PARSE_DTDVALID) {
ctxt->validate = 1;
if (options & XML_PARSE_NOWARNING)
ctxt->vctxt.warning = NULL;
if (options & XML_PARSE_NOERROR)
ctxt->vctxt.error = NULL;
options -= XML_PARSE_DTDVALID;
ctxt->options |= XML_PARSE_DTDVALID;
} else
ctxt->validate = 0;
if (options & XML_PARSE_NOWARNING) {
ctxt->sax->warning = NULL;
options -= XML_PARSE_NOWARNING;
}
if (options & XML_PARSE_NOERROR) {
ctxt->sax->error = NULL;
ctxt->sax->fatalError = NULL;
options -= XML_PARSE_NOERROR;
}
#ifdef LIBXML_SAX1_ENABLED
if (options & XML_PARSE_SAX1) {
ctxt->sax->startElement = xmlSAX2StartElement;
ctxt->sax->endElement = xmlSAX2EndElement;
ctxt->sax->startElementNs = NULL;
ctxt->sax->endElementNs = NULL;
ctxt->sax->initialized = 1;
options -= XML_PARSE_SAX1;
ctxt->options |= XML_PARSE_SAX1;
}
#endif /* LIBXML_SAX1_ENABLED */
if (options & XML_PARSE_NODICT) {
ctxt->dictNames = 0;
options -= XML_PARSE_NODICT;
ctxt->options |= XML_PARSE_NODICT;
} else {
ctxt->dictNames = 1;
}
if (options & XML_PARSE_NOCDATA) {
ctxt->sax->cdataBlock = NULL;
options -= XML_PARSE_NOCDATA;
ctxt->options |= XML_PARSE_NOCDATA;
}
if (options & XML_PARSE_NSCLEAN) {
ctxt->options |= XML_PARSE_NSCLEAN;
options -= XML_PARSE_NSCLEAN;
}
if (options & XML_PARSE_NONET) {
ctxt->options |= XML_PARSE_NONET;
options -= XML_PARSE_NONET;
}
if (options & XML_PARSE_NOXXE) {
ctxt->options |= XML_PARSE_NOXXE;
options -= XML_PARSE_NOXXE;
}
if (options & XML_PARSE_COMPACT) {
ctxt->options |= XML_PARSE_COMPACT;
options -= XML_PARSE_COMPACT;
}
if (options & XML_PARSE_OLD10) {
ctxt->options |= XML_PARSE_OLD10;
options -= XML_PARSE_OLD10;
}
if (options & XML_PARSE_NOBASEFIX) {
ctxt->options |= XML_PARSE_NOBASEFIX;
options -= XML_PARSE_NOBASEFIX;
}
if (options & XML_PARSE_HUGE) {
ctxt->options |= XML_PARSE_HUGE;
options -= XML_PARSE_HUGE;
if (ctxt->dict != NULL)
xmlDictSetLimit(ctxt->dict, 0);
}
if (options & XML_PARSE_OLDSAX) {
ctxt->options |= XML_PARSE_OLDSAX;
options -= XML_PARSE_OLDSAX;
}
if (options & XML_PARSE_IGNORE_ENC) {
ctxt->options |= XML_PARSE_IGNORE_ENC;
options -= XML_PARSE_IGNORE_ENC;
}
if (options & XML_PARSE_BIG_LINES) {
ctxt->options |= XML_PARSE_BIG_LINES;
options -= XML_PARSE_BIG_LINES;
}
ctxt->linenumbers = 1;
return (options);
}
/**
* xmlCtxtUseOptions:
* @ctxt: an XML parser context
* @options: a combination of xmlParserOption
*
* Applies the options to the parser context
*
* Returns 0 in case of success, the set of unknown or unimplemented options
* in case of error.
*/
int
xmlCtxtUseOptions(xmlParserCtxtPtr ctxt, int options)
{
return(xmlCtxtUseOptionsInternal(ctxt, options, NULL));
}
/**
* xmlDoRead:
* @ctxt: an XML parser context
* @URL: the base URL to use for the document
* @encoding: the document encoding, or NULL
* @options: a combination of xmlParserOption
* @reuse: keep the context for reuse
*
* Common front-end for the xmlRead functions
*
* Returns the resulting document tree or NULL
*/
static xmlDocPtr
xmlDoRead(xmlParserCtxtPtr ctxt, const char *URL, const char *encoding,
int options, int reuse)
{
xmlDocPtr ret;
xmlCtxtUseOptionsInternal(ctxt, options, encoding);
if (encoding != NULL) {
xmlCharEncodingHandlerPtr hdlr;
hdlr = xmlFindCharEncodingHandler(encoding);
if (hdlr != NULL)
xmlSwitchToEncoding(ctxt, hdlr);
}
if ((URL != NULL) && (ctxt->input != NULL) &&
(ctxt->input->filename == NULL))
ctxt->input->filename = (char *) xmlStrdup((const xmlChar *) URL);
xmlParseDocument(ctxt);
if ((ctxt->wellFormed) || ctxt->recovery)
ret = ctxt->myDoc;
else {
ret = NULL;
if (ctxt->myDoc != NULL) {
xmlFreeDoc(ctxt->myDoc);
}
}
ctxt->myDoc = NULL;
if (!reuse) {
xmlFreeParserCtxt(ctxt);
}
return (ret);
}
/**
* xmlReadDoc:
* @cur: a pointer to a zero terminated string
* @URL: the base URL to use for the document
* @encoding: the document encoding, or NULL
* @options: a combination of xmlParserOption
*
* parse an XML in-memory document and build a tree.
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlReadDoc(const xmlChar * cur, const char *URL, const char *encoding, int options)
{
xmlParserCtxtPtr ctxt;
if (cur == NULL)
return (NULL);
xmlInitParser();
ctxt = xmlCreateDocParserCtxt(cur);
if (ctxt == NULL)
return (NULL);
return (xmlDoRead(ctxt, URL, encoding, options, 0));
}
/**
* xmlReadFile:
* @filename: a file or URL
* @encoding: the document encoding, or NULL
* @options: a combination of xmlParserOption
*
* parse an XML file from the filesystem or the network.
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlReadFile(const char *filename, const char *encoding, int options)
{
xmlParserCtxtPtr ctxt;
xmlInitParser();
ctxt = xmlCreateURLParserCtxt(filename, options);
if (ctxt == NULL)
return (NULL);
return (xmlDoRead(ctxt, NULL, encoding, options, 0));
}
/**
* xmlReadMemory:
* @buffer: a pointer to a char array
* @size: the size of the array
* @URL: the base URL to use for the document
* @encoding: the document encoding, or NULL
* @options: a combination of xmlParserOption
*
* parse an XML in-memory document and build a tree.
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlReadMemory(const char *buffer, int size, const char *URL, const char *encoding, int options)
{
xmlParserCtxtPtr ctxt;
xmlInitParser();
ctxt = xmlCreateMemoryParserCtxt(buffer, size);
if (ctxt == NULL)
return (NULL);
return (xmlDoRead(ctxt, URL, encoding, options, 0));
}
/**
* xmlReadFd:
* @fd: an open file descriptor
* @URL: the base URL to use for the document
* @encoding: the document encoding, or NULL
* @options: a combination of xmlParserOption
*
* parse an XML from a file descriptor and build a tree.
* NOTE that the file descriptor will not be closed when the
* reader is closed or reset.
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlReadFd(int fd, const char *URL, const char *encoding, int options)
{
xmlParserCtxtPtr ctxt;
xmlParserInputBufferPtr input;
xmlParserInputPtr stream;
if (fd < 0)
return (NULL);
xmlInitParser();
input = xmlParserInputBufferCreateFd(fd, XML_CHAR_ENCODING_NONE);
if (input == NULL)
return (NULL);
input->closecallback = NULL;
ctxt = xmlNewParserCtxt();
if (ctxt == NULL) {
xmlFreeParserInputBuffer(input);
return (NULL);
}
stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
if (stream == NULL) {
xmlFreeParserInputBuffer(input);
xmlFreeParserCtxt(ctxt);
return (NULL);
}
inputPush(ctxt, stream);
return (xmlDoRead(ctxt, URL, encoding, options, 0));
}
/**
* xmlReadIO:
* @ioread: an I/O read function
* @ioclose: an I/O close function
* @ioctx: an I/O handler
* @URL: the base URL to use for the document
* @encoding: the document encoding, or NULL
* @options: a combination of xmlParserOption
*
* parse an XML document from I/O functions and source and build a tree.
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlReadIO(xmlInputReadCallback ioread, xmlInputCloseCallback ioclose,
void *ioctx, const char *URL, const char *encoding, int options)
{
xmlParserCtxtPtr ctxt;
xmlParserInputBufferPtr input;
xmlParserInputPtr stream;
if (ioread == NULL)
return (NULL);
xmlInitParser();
input = xmlParserInputBufferCreateIO(ioread, ioclose, ioctx,
XML_CHAR_ENCODING_NONE);
if (input == NULL) {
if (ioclose != NULL)
ioclose(ioctx);
return (NULL);
}
ctxt = xmlNewParserCtxt();
if (ctxt == NULL) {
xmlFreeParserInputBuffer(input);
return (NULL);
}
stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
if (stream == NULL) {
xmlFreeParserInputBuffer(input);
xmlFreeParserCtxt(ctxt);
return (NULL);
}
inputPush(ctxt, stream);
return (xmlDoRead(ctxt, URL, encoding, options, 0));
}
/**
* xmlCtxtReadDoc:
* @ctxt: an XML parser context
* @cur: a pointer to a zero terminated string
* @URL: the base URL to use for the document
* @encoding: the document encoding, or NULL
* @options: a combination of xmlParserOption
*
* parse an XML in-memory document and build a tree.
* This reuses the existing @ctxt parser context
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlCtxtReadDoc(xmlParserCtxtPtr ctxt, const xmlChar * cur,
const char *URL, const char *encoding, int options)
{
xmlParserInputPtr stream;
if (cur == NULL)
return (NULL);
if (ctxt == NULL)
return (NULL);
xmlInitParser();
xmlCtxtReset(ctxt);
stream = xmlNewStringInputStream(ctxt, cur);
if (stream == NULL) {
return (NULL);
}
inputPush(ctxt, stream);
return (xmlDoRead(ctxt, URL, encoding, options, 1));
}
/**
* xmlCtxtReadFile:
* @ctxt: an XML parser context
* @filename: a file or URL
* @encoding: the document encoding, or NULL
* @options: a combination of xmlParserOption
*
* parse an XML file from the filesystem or the network.
* This reuses the existing @ctxt parser context
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlCtxtReadFile(xmlParserCtxtPtr ctxt, const char *filename,
const char *encoding, int options)
{
xmlParserInputPtr stream;
if (filename == NULL)
return (NULL);
if (ctxt == NULL)
return (NULL);
xmlInitParser();
xmlCtxtReset(ctxt);
stream = xmlLoadExternalEntity(filename, NULL, ctxt);
if (stream == NULL) {
return (NULL);
}
inputPush(ctxt, stream);
return (xmlDoRead(ctxt, NULL, encoding, options, 1));
}
/**
* xmlCtxtReadMemory:
* @ctxt: an XML parser context
* @buffer: a pointer to a char array
* @size: the size of the array
* @URL: the base URL to use for the document
* @encoding: the document encoding, or NULL
* @options: a combination of xmlParserOption
*
* parse an XML in-memory document and build a tree.
* This reuses the existing @ctxt parser context
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlCtxtReadMemory(xmlParserCtxtPtr ctxt, const char *buffer, int size,
const char *URL, const char *encoding, int options)
{
xmlParserInputBufferPtr input;
xmlParserInputPtr stream;
if (ctxt == NULL)
return (NULL);
if (buffer == NULL)
return (NULL);
xmlInitParser();
xmlCtxtReset(ctxt);
input = xmlParserInputBufferCreateMem(buffer, size, XML_CHAR_ENCODING_NONE);
if (input == NULL) {
return(NULL);
}
stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
if (stream == NULL) {
xmlFreeParserInputBuffer(input);
return(NULL);
}
inputPush(ctxt, stream);
return (xmlDoRead(ctxt, URL, encoding, options, 1));
}
/**
* xmlCtxtReadFd:
* @ctxt: an XML parser context
* @fd: an open file descriptor
* @URL: the base URL to use for the document
* @encoding: the document encoding, or NULL
* @options: a combination of xmlParserOption
*
* parse an XML from a file descriptor and build a tree.
* This reuses the existing @ctxt parser context
* NOTE that the file descriptor will not be closed when the
* reader is closed or reset.
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlCtxtReadFd(xmlParserCtxtPtr ctxt, int fd,
const char *URL, const char *encoding, int options)
{
xmlParserInputBufferPtr input;
xmlParserInputPtr stream;
if (fd < 0)
return (NULL);
if (ctxt == NULL)
return (NULL);
xmlInitParser();
xmlCtxtReset(ctxt);
input = xmlParserInputBufferCreateFd(fd, XML_CHAR_ENCODING_NONE);
if (input == NULL)
return (NULL);
input->closecallback = NULL;
stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
if (stream == NULL) {
xmlFreeParserInputBuffer(input);
return (NULL);
}
inputPush(ctxt, stream);
return (xmlDoRead(ctxt, URL, encoding, options, 1));
}
/**
* xmlCtxtReadIO:
* @ctxt: an XML parser context
* @ioread: an I/O read function
* @ioclose: an I/O close function
* @ioctx: an I/O handler
* @URL: the base URL to use for the document
* @encoding: the document encoding, or NULL
* @options: a combination of xmlParserOption
*
* parse an XML document from I/O functions and source and build a tree.
* This reuses the existing @ctxt parser context
*
* Returns the resulting document tree
*/
xmlDocPtr
xmlCtxtReadIO(xmlParserCtxtPtr ctxt, xmlInputReadCallback ioread,
xmlInputCloseCallback ioclose, void *ioctx,
const char *URL,
const char *encoding, int options)
{
xmlParserInputBufferPtr input;
xmlParserInputPtr stream;
if (ioread == NULL)
return (NULL);
if (ctxt == NULL)
return (NULL);
xmlInitParser();
xmlCtxtReset(ctxt);
input = xmlParserInputBufferCreateIO(ioread, ioclose, ioctx,
XML_CHAR_ENCODING_NONE);
if (input == NULL) {
if (ioclose != NULL)
ioclose(ioctx);
return (NULL);
}
stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
if (stream == NULL) {
xmlFreeParserInputBuffer(input);
return (NULL);
}
inputPush(ctxt, stream);
return (xmlDoRead(ctxt, URL, encoding, options, 1));
}
#define bottom_parser
#include "elfgcchack.h"
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2947_1 |
crossvul-cpp_data_bad_1536_0 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* lib/krb5/krb/bld_princ.c - Build a principal from a list of strings */
/*
* Copyright 1991 by the Massachusetts Institute of Technology.
* All Rights Reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*/
#include "k5-int.h"
static krb5_error_code
build_principal_va(krb5_context context, krb5_principal princ,
unsigned int rlen, const char *realm, va_list ap)
{
krb5_error_code retval = 0;
char *r = NULL;
krb5_data *data = NULL;
krb5_int32 count = 0;
krb5_int32 size = 2; /* initial guess at needed space */
char *component = NULL;
data = malloc(size * sizeof(krb5_data));
if (!data) { retval = ENOMEM; }
if (!retval) {
r = strdup(realm);
if (!r) { retval = ENOMEM; }
}
while (!retval && (component = va_arg(ap, char *))) {
if (count == size) {
krb5_data *new_data = NULL;
size *= 2;
new_data = realloc(data, size * sizeof(krb5_data));
if (new_data) {
data = new_data;
} else {
retval = ENOMEM;
}
}
if (!retval) {
data[count].length = strlen(component);
data[count].data = strdup(component);
if (!data[count].data) { retval = ENOMEM; }
count++;
}
}
if (!retval) {
princ->type = KRB5_NT_UNKNOWN;
princ->magic = KV5M_PRINCIPAL;
princ->realm = make_data(r, rlen);
princ->data = data;
princ->length = count;
r = NULL; /* take ownership */
data = NULL; /* take ownership */
}
if (data) {
while (--count >= 0) {
free(data[count].data);
}
free(data);
}
free(r);
return retval;
}
krb5_error_code KRB5_CALLCONV
krb5_build_principal_va(krb5_context context,
krb5_principal princ,
unsigned int rlen,
const char *realm,
va_list ap)
{
return build_principal_va(context, princ, rlen, realm, ap);
}
krb5_error_code KRB5_CALLCONV
krb5_build_principal_alloc_va(krb5_context context,
krb5_principal *princ,
unsigned int rlen,
const char *realm,
va_list ap)
{
krb5_error_code retval = 0;
krb5_principal p;
p = malloc(sizeof(krb5_principal_data));
if (p == NULL)
return ENOMEM;
retval = build_principal_va(context, p, rlen, realm, ap);
if (retval) {
free(p);
return retval;
}
*princ = p;
return 0;
}
krb5_error_code KRB5_CALLCONV_C
krb5_build_principal(krb5_context context,
krb5_principal * princ,
unsigned int rlen,
const char * realm, ...)
{
krb5_error_code retval = 0;
va_list ap;
va_start(ap, realm);
retval = krb5_build_principal_alloc_va(context, princ, rlen, realm, ap);
va_end(ap);
return retval;
}
/*Anonymous and well known principals*/
static const char anon_realm_str[] = KRB5_ANONYMOUS_REALMSTR;
static const krb5_data anon_realm_data = {
KV5M_DATA, sizeof(anon_realm_str) - 1, (char *) anon_realm_str
};
static const char wellknown_str[] = KRB5_WELLKNOWN_NAMESTR;
static const char anon_str[] = KRB5_ANONYMOUS_PRINCSTR;
static const krb5_data anon_princ_data[] = {
{ KV5M_DATA, sizeof(wellknown_str) - 1, (char *) wellknown_str },
{ KV5M_DATA, sizeof(anon_str) - 1, (char *) anon_str }
};
const krb5_principal_data anon_princ = {
KV5M_PRINCIPAL,
{ KV5M_DATA, sizeof(anon_realm_str) - 1, (char *) anon_realm_str },
(krb5_data *) anon_princ_data, 2, KRB5_NT_WELLKNOWN
};
const krb5_data * KRB5_CALLCONV
krb5_anonymous_realm()
{
return &anon_realm_data;
}
krb5_const_principal KRB5_CALLCONV
krb5_anonymous_principal()
{
return &anon_princ;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1536_0 |
crossvul-cpp_data_bad_4787_6 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC IIIII N N %
% C I NN N %
% C I N N N %
% C I N NN %
% CCCC IIIII N N %
% %
% %
% Read/Write Kodak Cineon Image Format %
% Cineon Image Format is a subset of SMTPE CIN %
% %
% %
% Software Design %
% Cristy %
% Kelly Bergougnoux %
% October 2003 %
% %
% %
% 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. %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Cineon image file format draft is available at
% http://www.cineon.com/ff_draft.php.
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colorspace.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
/*
Typedef declaration.
*/
typedef struct _CINDataFormatInfo
{
unsigned char
interleave,
packing,
sign,
sense;
size_t
line_pad,
channel_pad;
unsigned char
reserve[20];
} CINDataFormatInfo;
typedef struct _CINFileInfo
{
size_t
magic,
image_offset,
generic_length,
industry_length,
user_length,
file_size;
char
version[8],
filename[100],
create_date[12],
create_time[12],
reserve[36];
} CINFileInfo;
typedef struct _CINFilmInfo
{
char
id,
type,
offset,
reserve1;
size_t
prefix,
count;
char
format[32];
size_t
frame_position;
float
frame_rate;
char
frame_id[32],
slate_info[200],
reserve[740];
} CINFilmInfo;
typedef struct _CINImageChannel
{
unsigned char
designator[2],
bits_per_pixel,
reserve;
size_t
pixels_per_line,
lines_per_image;
float
min_data,
min_quantity,
max_data,
max_quantity;
} CINImageChannel;
typedef struct _CINImageInfo
{
unsigned char
orientation,
number_channels,
reserve1[2];
CINImageChannel
channel[8];
float
white_point[2],
red_primary_chromaticity[2],
green_primary_chromaticity[2],
blue_primary_chromaticity[2];
char
label[200],
reserve[28];
} CINImageInfo;
typedef struct _CINOriginationInfo
{
ssize_t
x_offset,
y_offset;
char
filename[100],
create_date[12],
create_time[12],
device[64],
model[32],
serial[32];
float
x_pitch,
y_pitch,
gamma;
char
reserve[40];
} CINOriginationInfo;
typedef struct _CINUserInfo
{
char
id[32];
} CINUserInfo;
typedef struct CINInfo
{
CINFileInfo
file;
CINImageInfo
image;
CINDataFormatInfo
data_format;
CINOriginationInfo
origination;
CINFilmInfo
film;
CINUserInfo
user;
} CINInfo;
/*
Forward declaractions.
*/
static MagickBooleanType
WriteCINImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s C I N E O N %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsCIN() returns MagickTrue if the image format type, identified by the magick
% string, is CIN.
%
% The format of the IsCIN method is:
%
% MagickBooleanType IsCIN(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 IsCIN(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\200\052\137\327",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d C I N E O N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadCINImage() reads an CIN X image file and returns it. It allocates
% the memory necessary for the new Image structure and returns a point to the
% new image.
%
% The format of the ReadCINImage method is:
%
% Image *ReadCINImage(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 size_t GetBytesPerRow(size_t columns,
size_t samples_per_pixel,size_t bits_per_pixel,
MagickBooleanType pad)
{
size_t
bytes_per_row;
switch (bits_per_pixel)
{
case 1:
{
bytes_per_row=4*(((size_t) samples_per_pixel*columns*
bits_per_pixel+31)/32);
break;
}
case 8:
default:
{
bytes_per_row=4*(((size_t) samples_per_pixel*columns*
bits_per_pixel+31)/32);
break;
}
case 10:
{
if (pad == MagickFalse)
{
bytes_per_row=4*(((size_t) samples_per_pixel*columns*
bits_per_pixel+31)/32);
break;
}
bytes_per_row=4*(((size_t) (32*((samples_per_pixel*columns+2)/3))+31)/32);
break;
}
case 12:
{
if (pad == MagickFalse)
{
bytes_per_row=4*(((size_t) samples_per_pixel*columns*
bits_per_pixel+31)/32);
break;
}
bytes_per_row=2*(((size_t) (16*samples_per_pixel*columns)+15)/16);
break;
}
case 16:
{
bytes_per_row=2*(((size_t) samples_per_pixel*columns*
bits_per_pixel+8)/16);
break;
}
case 32:
{
bytes_per_row=4*(((size_t) samples_per_pixel*columns*
bits_per_pixel+31)/32);
break;
}
case 64:
{
bytes_per_row=8*(((size_t) samples_per_pixel*columns*
bits_per_pixel+63)/64);
break;
}
}
return(bytes_per_row);
}
static inline MagickBooleanType IsFloatDefined(const float value)
{
union
{
unsigned int
unsigned_value;
double
float_value;
} quantum;
quantum.unsigned_value=0U;
quantum.float_value=value;
if (quantum.unsigned_value == 0U)
return(MagickFalse);
return(MagickTrue);
}
static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define MonoColorType 1
#define RGBColorType 3
char
property[MaxTextExtent];
CINInfo
cin;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
offset;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
register PixelPacket
*q;
size_t
length;
ssize_t
count,
y;
unsigned char
magick[4],
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
File information.
*/
offset=0;
count=ReadBlob(image,4,magick);
offset+=count;
if ((count != 4) ||
((LocaleNCompare((char *) magick,"\200\052\137\327",4) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) &&
(magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian;
cin.file.image_offset=ReadBlobLong(image);
offset+=4;
cin.file.generic_length=ReadBlobLong(image);
offset+=4;
cin.file.industry_length=ReadBlobLong(image);
offset+=4;
cin.file.user_length=ReadBlobLong(image);
offset+=4;
cin.file.file_size=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *)
cin.file.version);
(void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version));
(void) SetImageProperty(image,"dpx:file.version",property);
offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *)
cin.file.filename);
(void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename));
(void) SetImageProperty(image,"dpx:file.filename",property);
offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *)
cin.file.create_date);
(void) CopyMagickString(property,cin.file.create_date,
sizeof(cin.file.create_date));
(void) SetImageProperty(image,"dpx:file.create_date",property);
offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *)
cin.file.create_time);
(void) CopyMagickString(property,cin.file.create_time,
sizeof(cin.file.create_time));
(void) SetImageProperty(image,"dpx:file.create_time",property);
offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *)
cin.file.reserve);
/*
Image information.
*/
cin.image.orientation=(unsigned char) ReadBlobByte(image);
offset++;
if (cin.image.orientation != (unsigned char) (~0))
(void) FormatImageProperty(image,"dpx:image.orientation","%d",
cin.image.orientation);
switch (cin.image.orientation)
{
default:
case 0: image->orientation=TopLeftOrientation; break;
case 1: image->orientation=TopRightOrientation; break;
case 2: image->orientation=BottomLeftOrientation; break;
case 3: image->orientation=BottomRightOrientation; break;
case 4: image->orientation=LeftTopOrientation; break;
case 5: image->orientation=RightTopOrientation; break;
case 6: image->orientation=LeftBottomOrientation; break;
case 7: image->orientation=RightBottomOrientation; break;
}
cin.image.number_channels=(unsigned char) ReadBlobByte(image);
offset++;
offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *)
cin.image.reserve1);
for (i=0; i < 8; i++)
{
cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].pixels_per_line=ReadBlobLong(image);
offset+=4;
cin.image.channel[i].lines_per_image=ReadBlobLong(image);
offset+=4;
cin.image.channel[i].min_data=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].min_quantity=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].max_data=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].max_quantity=ReadBlobFloat(image);
offset+=4;
}
cin.image.white_point[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse)
image->chromaticity.white_point.x=cin.image.white_point[0];
cin.image.white_point[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse)
image->chromaticity.white_point.y=cin.image.white_point[1];
cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0];
cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1];
cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0];
cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1];
cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0];
cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1];
offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *)
cin.image.label);
(void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label));
(void) SetImageProperty(image,"dpx:image.label",property);
offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *)
cin.image.reserve);
/*
Image data format information.
*/
cin.data_format.interleave=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.packing=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.sign=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.sense=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.line_pad=ReadBlobLong(image);
offset+=4;
cin.data_format.channel_pad=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)
cin.data_format.reserve);
/*
Image origination information.
*/
cin.origination.x_offset=(int) ReadBlobLong(image);
offset+=4;
if ((size_t) cin.origination.x_offset != ~0UL)
(void) FormatImageProperty(image,"dpx:origination.x_offset","%.20g",
(double) cin.origination.x_offset);
cin.origination.y_offset=(ssize_t) ReadBlobLong(image);
offset+=4;
if ((size_t) cin.origination.y_offset != ~0UL)
(void) FormatImageProperty(image,"dpx:origination.y_offset","%.20g",
(double) cin.origination.y_offset);
offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *)
cin.origination.filename);
(void) CopyMagickString(property,cin.origination.filename,
sizeof(cin.origination.filename));
(void) SetImageProperty(image,"dpx:origination.filename",property);
offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *)
cin.origination.create_date);
(void) CopyMagickString(property,cin.origination.create_date,
sizeof(cin.origination.create_date));
(void) SetImageProperty(image,"dpx:origination.create_date",property);
offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *)
cin.origination.create_time);
(void) CopyMagickString(property,cin.origination.create_time,
sizeof(cin.origination.create_time));
(void) SetImageProperty(image,"dpx:origination.create_time",property);
offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *)
cin.origination.device);
(void) CopyMagickString(property,cin.origination.device,
sizeof(cin.origination.device));
(void) SetImageProperty(image,"dpx:origination.device",property);
offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *)
cin.origination.model);
(void) CopyMagickString(property,cin.origination.model,
sizeof(cin.origination.model));
(void) SetImageProperty(image,"dpx:origination.model",property);
(void) ResetMagickMemory(cin.origination.serial,0,
sizeof(cin.origination.serial));
offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *)
cin.origination.serial);
(void) CopyMagickString(property,cin.origination.serial,
sizeof(cin.origination.serial));
(void) SetImageProperty(image,"dpx:origination.serial",property);
cin.origination.x_pitch=ReadBlobFloat(image);
offset+=4;
cin.origination.y_pitch=ReadBlobFloat(image);
offset+=4;
cin.origination.gamma=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.origination.gamma) != MagickFalse)
image->gamma=cin.origination.gamma;
offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *)
cin.origination.reserve);
if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
{
int
c;
/*
Image film information.
*/
cin.film.id=ReadBlobByte(image);
offset++;
c=cin.film.id;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.id","%d",cin.film.id);
cin.film.type=ReadBlobByte(image);
offset++;
c=cin.film.type;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.type","%d",cin.film.type);
cin.film.offset=ReadBlobByte(image);
offset++;
c=cin.film.offset;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.offset","%d",
cin.film.offset);
cin.film.reserve1=ReadBlobByte(image);
offset++;
cin.film.prefix=ReadBlobLong(image);
offset+=4;
if (cin.film.prefix != ~0UL)
(void) FormatImageProperty(image,"dpx:film.prefix","%.20g",(double)
cin.film.prefix);
cin.film.count=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *)
cin.film.format);
(void) CopyMagickString(property,cin.film.format,
sizeof(cin.film.format));
(void) SetImageProperty(image,"dpx:film.format",property);
cin.film.frame_position=ReadBlobLong(image);
offset+=4;
if (cin.film.frame_position != ~0UL)
(void) FormatImageProperty(image,"dpx:film.frame_position","%.20g",
(double) cin.film.frame_position);
cin.film.frame_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.film.frame_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:film.frame_rate","%g",
cin.film.frame_rate);
offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *)
cin.film.frame_id);
(void) CopyMagickString(property,cin.film.frame_id,
sizeof(cin.film.frame_id));
(void) SetImageProperty(image,"dpx:film.frame_id",property);
offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *)
cin.film.slate_info);
(void) CopyMagickString(property,cin.film.slate_info,
sizeof(cin.film.slate_info));
(void) SetImageProperty(image,"dpx:film.slate_info",property);
offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *)
cin.film.reserve);
}
if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
{
StringInfo
*profile;
/*
User defined data.
*/
profile=BlobToStringInfo((const void *) NULL,cin.file.user_length);
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
offset+=ReadBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) SetImageProfile(image,"dpx:user.data",profile);
profile=DestroyStringInfo(profile);
}
for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++)
(void) ReadBlobByte(image);
image->depth=cin.image.channel[0].bits_per_pixel;
image->columns=cin.image.channel[0].pixels_per_line;
image->rows=cin.image.channel[0].lines_per_image;
if (image_info->ping)
{
(void) CloseBlob(image);
return(image);
}
/*
Convert CIN raster image to pixel packets.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->quantum=32;
quantum_info->pack=MagickFalse;
quantum_type=RGBQuantum;
pixels=GetQuantumPixels(quantum_info);
length=GetQuantumExtent(image,quantum_info,quantum_type);
length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);
if (cin.image.number_channels == 1)
{
quantum_type=GrayQuantum;
length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue);
}
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
count=ReadBlob(image,length,pixels);
if ((size_t) count != length)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
SetImageColorspace(image,LogColorspace);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r C I N E O N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterCINImage() adds attributes for the CIN image format to the list of
% 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 RegisterCINImage method is:
%
% size_t RegisterCINImage(void)
%
*/
ModuleExport size_t RegisterCINImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CIN");
entry->decoder=(DecodeImageHandler *) ReadCINImage;
entry->encoder=(EncodeImageHandler *) WriteCINImage;
entry->magick=(IsImageFormatHandler *) IsCIN;
entry->adjoin=MagickFalse;
entry->description=ConstantString("Cineon Image File");
entry->module=ConstantString("CIN");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r C I N E O N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterCINImage() removes format registrations made by the CIN module
% from the list of supported formats.
%
% The format of the UnregisterCINImage method is:
%
% UnregisterCINImage(void)
%
*/
ModuleExport void UnregisterCINImage(void)
{
(void) UnregisterMagickInfo("CINEON");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e C I N E O N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteCINImage() writes an image in CIN encoded image format.
%
% The format of the WriteCINImage method is:
%
% MagickBooleanType WriteCINImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static inline const char *GetCINProperty(const ImageInfo *image_info,
const Image *image,const char *property)
{
const char
*value;
value=GetImageOption(image_info,property);
if (value != (const char *) NULL)
return(value);
return(GetImageProperty(image,property));
}
static MagickBooleanType WriteCINImage(const ImageInfo *image_info,Image *image)
{
char
timestamp[MaxTextExtent];
const char
*value;
CINInfo
cin;
const StringInfo
*profile;
MagickBooleanType
status;
MagickOffsetType
offset;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register const PixelPacket
*p;
register ssize_t
i;
size_t
length;
ssize_t
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 == 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);
if (image->colorspace != LogColorspace)
(void) TransformImageColorspace(image,LogColorspace);
/*
Write image information.
*/
(void) ResetMagickMemory(&cin,0,sizeof(cin));
offset=0;
cin.file.magic=0x802A5FD7UL;
offset+=WriteBlobLong(image,(unsigned int) cin.file.magic);
cin.file.image_offset=0x800;
offset+=WriteBlobLong(image,(unsigned int) cin.file.image_offset);
cin.file.generic_length=0x400;
offset+=WriteBlobLong(image,(unsigned int) cin.file.generic_length);
cin.file.industry_length=0x400;
offset+=WriteBlobLong(image,(unsigned int) cin.file.industry_length);
cin.file.user_length=0x00;
profile=GetImageProfile(image,"dpx:user.data");
if (profile != (StringInfo *) NULL)
{
cin.file.user_length+=(size_t) GetStringInfoLength(profile);
cin.file.user_length=(((cin.file.user_length+0x2000-1)/0x2000)*0x2000);
}
offset+=WriteBlobLong(image,(unsigned int) cin.file.user_length);
cin.file.file_size=4*image->columns*image->rows+0x2000;
offset+=WriteBlobLong(image,(unsigned int) cin.file.file_size);
(void) CopyMagickString(cin.file.version,"V4.5",sizeof(cin.file.version));
offset+=WriteBlob(image,sizeof(cin.file.version),(unsigned char *)
cin.file.version);
value=GetCINProperty(image_info,image,"dpx:file.filename");
if (value != (const char *) NULL)
(void) CopyMagickString(cin.file.filename,value,sizeof(cin.file.filename));
else
(void) CopyMagickString(cin.file.filename,image->filename,
sizeof(cin.file.filename));
offset+=WriteBlob(image,sizeof(cin.file.filename),(unsigned char *)
cin.file.filename);
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) memset(timestamp,0,sizeof(timestamp));
(void) strftime(timestamp,MaxTextExtent,"%Y:%m:%d:%H:%M:%S%Z",&local_time);
(void) memset(cin.file.create_date,0,sizeof(cin.file.create_date));
(void) CopyMagickString(cin.file.create_date,timestamp,11);
offset+=WriteBlob(image,sizeof(cin.file.create_date),(unsigned char *)
cin.file.create_date);
(void) memset(cin.file.create_time,0,sizeof(cin.file.create_time));
(void) CopyMagickString(cin.file.create_time,timestamp+11,11);
offset+=WriteBlob(image,sizeof(cin.file.create_time),(unsigned char *)
cin.file.create_time);
offset+=WriteBlob(image,sizeof(cin.file.reserve),(unsigned char *)
cin.file.reserve);
cin.image.orientation=0x00;
offset+=WriteBlobByte(image,cin.image.orientation);
cin.image.number_channels=3;
offset+=WriteBlobByte(image,cin.image.number_channels);
offset+=WriteBlob(image,sizeof(cin.image.reserve1),(unsigned char *)
cin.image.reserve1);
for (i=0; i < 8; i++)
{
cin.image.channel[i].designator[0]=0; /* universal metric */
offset+=WriteBlobByte(image,cin.image.channel[0].designator[0]);
cin.image.channel[i].designator[1]=(unsigned char) (i > 3 ? 0 : i+1); /* channel color */;
offset+=WriteBlobByte(image,cin.image.channel[1].designator[0]);
cin.image.channel[i].bits_per_pixel=(unsigned char) image->depth;
offset+=WriteBlobByte(image,cin.image.channel[0].bits_per_pixel);
offset+=WriteBlobByte(image,cin.image.channel[0].reserve);
cin.image.channel[i].pixels_per_line=image->columns;
offset+=WriteBlobLong(image,(unsigned int)
cin.image.channel[0].pixels_per_line);
cin.image.channel[i].lines_per_image=image->rows;
offset+=WriteBlobLong(image,(unsigned int)
cin.image.channel[0].lines_per_image);
cin.image.channel[i].min_data=0;
offset+=WriteBlobFloat(image,cin.image.channel[0].min_data);
cin.image.channel[i].min_quantity=0.0;
offset+=WriteBlobFloat(image,cin.image.channel[0].min_quantity);
cin.image.channel[i].max_data=(float) ((MagickOffsetType)
GetQuantumRange(image->depth));
offset+=WriteBlobFloat(image,cin.image.channel[0].max_data);
cin.image.channel[i].max_quantity=2.048f;
offset+=WriteBlobFloat(image,cin.image.channel[0].max_quantity);
}
offset+=WriteBlobFloat(image,image->chromaticity.white_point.x);
offset+=WriteBlobFloat(image,image->chromaticity.white_point.y);
offset+=WriteBlobFloat(image,image->chromaticity.red_primary.x);
offset+=WriteBlobFloat(image,image->chromaticity.red_primary.y);
offset+=WriteBlobFloat(image,image->chromaticity.green_primary.x);
offset+=WriteBlobFloat(image,image->chromaticity.green_primary.y);
offset+=WriteBlobFloat(image,image->chromaticity.blue_primary.x);
offset+=WriteBlobFloat(image,image->chromaticity.blue_primary.y);
value=GetCINProperty(image_info,image,"dpx:image.label");
if (value != (const char *) NULL)
(void) CopyMagickString(cin.image.label,value,sizeof(cin.image.label));
offset+=WriteBlob(image,sizeof(cin.image.label),(unsigned char *)
cin.image.label);
offset+=WriteBlob(image,sizeof(cin.image.reserve),(unsigned char *)
cin.image.reserve);
/*
Write data format information.
*/
cin.data_format.interleave=0; /* pixel interleave (rgbrgbr...) */
offset+=WriteBlobByte(image,cin.data_format.interleave);
cin.data_format.packing=5; /* packing ssize_tword (32bit) boundaries */
offset+=WriteBlobByte(image,cin.data_format.packing);
cin.data_format.sign=0; /* unsigned data */
offset+=WriteBlobByte(image,cin.data_format.sign);
cin.data_format.sense=0; /* image sense: positive image */
offset+=WriteBlobByte(image,cin.data_format.sense);
cin.data_format.line_pad=0;
offset+=WriteBlobLong(image,(unsigned int) cin.data_format.line_pad);
cin.data_format.channel_pad=0;
offset+=WriteBlobLong(image,(unsigned int) cin.data_format.channel_pad);
offset+=WriteBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)
cin.data_format.reserve);
/*
Write origination information.
*/
cin.origination.x_offset=0UL;
value=GetCINProperty(image_info,image,"dpx:origination.x_offset");
if (value != (const char *) NULL)
cin.origination.x_offset=(ssize_t) StringToLong(value);
offset+=WriteBlobLong(image,(unsigned int) cin.origination.x_offset);
cin.origination.y_offset=0UL;
value=GetCINProperty(image_info,image,"dpx:origination.y_offset");
if (value != (const char *) NULL)
cin.origination.y_offset=(ssize_t) StringToLong(value);
offset+=WriteBlobLong(image,(unsigned int) cin.origination.y_offset);
value=GetCINProperty(image_info,image,"dpx:origination.filename");
if (value != (const char *) NULL)
(void) CopyMagickString(cin.origination.filename,value,
sizeof(cin.origination.filename));
else
(void) CopyMagickString(cin.origination.filename,image->filename,
sizeof(cin.origination.filename));
offset+=WriteBlob(image,sizeof(cin.origination.filename),(unsigned char *)
cin.origination.filename);
seconds=time((time_t *) NULL);
(void) memset(timestamp,0,sizeof(timestamp));
(void) strftime(timestamp,MaxTextExtent,"%Y:%m:%d:%H:%M:%S%Z",&local_time);
(void) memset(cin.origination.create_date,0,
sizeof(cin.origination.create_date));
(void) CopyMagickString(cin.origination.create_date,timestamp,11);
offset+=WriteBlob(image,sizeof(cin.origination.create_date),(unsigned char *)
cin.origination.create_date);
(void) memset(cin.origination.create_time,0,
sizeof(cin.origination.create_time));
(void) CopyMagickString(cin.origination.create_time,timestamp+11,15);
offset+=WriteBlob(image,sizeof(cin.origination.create_time),(unsigned char *)
cin.origination.create_time);
value=GetCINProperty(image_info,image,"dpx:origination.device");
if (value != (const char *) NULL)
(void) CopyMagickString(cin.origination.device,value,
sizeof(cin.origination.device));
offset+=WriteBlob(image,sizeof(cin.origination.device),(unsigned char *)
cin.origination.device);
value=GetCINProperty(image_info,image,"dpx:origination.model");
if (value != (const char *) NULL)
(void) CopyMagickString(cin.origination.model,value,
sizeof(cin.origination.model));
offset+=WriteBlob(image,sizeof(cin.origination.model),(unsigned char *)
cin.origination.model);
value=GetCINProperty(image_info,image,"dpx:origination.serial");
if (value != (const char *) NULL)
(void) CopyMagickString(cin.origination.serial,value,
sizeof(cin.origination.serial));
offset+=WriteBlob(image,sizeof(cin.origination.serial),(unsigned char *)
cin.origination.serial);
cin.origination.x_pitch=0.0f;
value=GetCINProperty(image_info,image,"dpx:origination.x_pitch");
if (value != (const char *) NULL)
cin.origination.x_pitch=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,cin.origination.x_pitch);
cin.origination.y_pitch=0.0f;
value=GetCINProperty(image_info,image,"dpx:origination.y_pitch");
if (value != (const char *) NULL)
cin.origination.y_pitch=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,cin.origination.y_pitch);
cin.origination.gamma=image->gamma;
offset+=WriteBlobFloat(image,cin.origination.gamma);
offset+=WriteBlob(image,sizeof(cin.origination.reserve),(unsigned char *)
cin.origination.reserve);
/*
Image film information.
*/
cin.film.id=0;
value=GetCINProperty(image_info,image,"dpx:film.id");
if (value != (const char *) NULL)
cin.film.id=(char) StringToLong(value);
offset+=WriteBlobByte(image,(unsigned char) cin.film.id);
cin.film.type=0;
value=GetCINProperty(image_info,image,"dpx:film.type");
if (value != (const char *) NULL)
cin.film.type=(char) StringToLong(value);
offset+=WriteBlobByte(image,(unsigned char) cin.film.type);
cin.film.offset=0;
value=GetCINProperty(image_info,image,"dpx:film.offset");
if (value != (const char *) NULL)
cin.film.offset=(char) StringToLong(value);
offset+=WriteBlobByte(image,(unsigned char) cin.film.offset);
offset+=WriteBlobByte(image,(unsigned char) cin.film.reserve1);
cin.film.prefix=0UL;
value=GetCINProperty(image_info,image,"dpx:film.prefix");
if (value != (const char *) NULL)
cin.film.prefix=StringToUnsignedLong(value);
offset+=WriteBlobLong(image,(unsigned int) cin.film.prefix);
cin.film.count=0UL;
value=GetCINProperty(image_info,image,"dpx:film.count");
if (value != (const char *) NULL)
cin.film.count=StringToUnsignedLong(value);
offset+=WriteBlobLong(image,(unsigned int) cin.film.count);
value=GetCINProperty(image_info,image,"dpx:film.format");
if (value != (const char *) NULL)
(void) CopyMagickString(cin.film.format,value,sizeof(cin.film.format));
offset+=WriteBlob(image,sizeof(cin.film.format),(unsigned char *)
cin.film.format);
cin.film.frame_position=0UL;
value=GetCINProperty(image_info,image,"dpx:film.frame_position");
if (value != (const char *) NULL)
cin.film.frame_position=StringToUnsignedLong(value);
offset+=WriteBlobLong(image,(unsigned int) cin.film.frame_position);
cin.film.frame_rate=0.0f;
value=GetCINProperty(image_info,image,"dpx:film.frame_rate");
if (value != (const char *) NULL)
cin.film.frame_rate=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,cin.film.frame_rate);
value=GetCINProperty(image_info,image,"dpx:film.frame_id");
if (value != (const char *) NULL)
(void) CopyMagickString(cin.film.frame_id,value,sizeof(cin.film.frame_id));
offset+=WriteBlob(image,sizeof(cin.film.frame_id),(unsigned char *)
cin.film.frame_id);
value=GetCINProperty(image_info,image,"dpx:film.slate_info");
if (value != (const char *) NULL)
(void) CopyMagickString(cin.film.slate_info,value,
sizeof(cin.film.slate_info));
offset+=WriteBlob(image,sizeof(cin.film.slate_info),(unsigned char *)
cin.film.slate_info);
offset+=WriteBlob(image,sizeof(cin.film.reserve),(unsigned char *)
cin.film.reserve);
if (profile != (StringInfo *) NULL)
offset+=WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
while (offset < (MagickOffsetType) cin.file.image_offset)
offset+=WriteBlobByte(image,0x00);
/*
Convert pixel packets to CIN raster image.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->quantum=32;
quantum_info->pack=MagickFalse;
quantum_type=RGBQuantum;
pixels=GetQuantumPixels(quantum_info);
length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);
DisableMSCWarning(4127)
if (0)
RestoreMSCWarning
{
quantum_type=GrayQuantum;
length=GetBytesPerRow(image->columns,1UL,image->depth,MagickTrue);
}
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
quantum_type,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4787_6 |
crossvul-cpp_data_bad_5733_1 | /*
* Copyright (c) 2002 Jindrich Makovicka <makovick@gmail.com>
* Copyright (c) 2011 Stefano Sabatini
* Copyright (c) 2013 Jean Delvare <khali@linux-fr.org>
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with FFmpeg; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
* @file
* A very simple tv station logo remover
* Originally imported from MPlayer libmpcodecs/vf_delogo.c,
* the algorithm was later improved.
*/
#include "libavutil/common.h"
#include "libavutil/imgutils.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"
#include "avfilter.h"
#include "formats.h"
#include "internal.h"
#include "video.h"
/**
* Apply a simple delogo algorithm to the image in src and put the
* result in dst.
*
* The algorithm is only applied to the region specified by the logo
* parameters.
*
* @param w width of the input image
* @param h height of the input image
* @param logo_x x coordinate of the top left corner of the logo region
* @param logo_y y coordinate of the top left corner of the logo region
* @param logo_w width of the logo
* @param logo_h height of the logo
* @param band the size of the band around the processed area
* @param show show a rectangle around the processed area, useful for
* parameters tweaking
* @param direct if non-zero perform in-place processing
*/
static void apply_delogo(uint8_t *dst, int dst_linesize,
uint8_t *src, int src_linesize,
int w, int h, AVRational sar,
int logo_x, int logo_y, int logo_w, int logo_h,
unsigned int band, int show, int direct)
{
int x, y;
uint64_t interp, weightl, weightr, weightt, weightb;
uint8_t *xdst, *xsrc;
uint8_t *topleft, *botleft, *topright;
unsigned int left_sample, right_sample;
int xclipl, xclipr, yclipt, yclipb;
int logo_x1, logo_x2, logo_y1, logo_y2;
xclipl = FFMAX(-logo_x, 0);
xclipr = FFMAX(logo_x+logo_w-w, 0);
yclipt = FFMAX(-logo_y, 0);
yclipb = FFMAX(logo_y+logo_h-h, 0);
logo_x1 = logo_x + xclipl;
logo_x2 = logo_x + logo_w - xclipr;
logo_y1 = logo_y + yclipt;
logo_y2 = logo_y + logo_h - yclipb;
topleft = src+logo_y1 * src_linesize+logo_x1;
topright = src+logo_y1 * src_linesize+logo_x2-1;
botleft = src+(logo_y2-1) * src_linesize+logo_x1;
if (!direct)
av_image_copy_plane(dst, dst_linesize, src, src_linesize, w, h);
dst += (logo_y1 + 1) * dst_linesize;
src += (logo_y1 + 1) * src_linesize;
for (y = logo_y1+1; y < logo_y2-1; y++) {
left_sample = topleft[src_linesize*(y-logo_y1)] +
topleft[src_linesize*(y-logo_y1-1)] +
topleft[src_linesize*(y-logo_y1+1)];
right_sample = topright[src_linesize*(y-logo_y1)] +
topright[src_linesize*(y-logo_y1-1)] +
topright[src_linesize*(y-logo_y1+1)];
for (x = logo_x1+1,
xdst = dst+logo_x1+1,
xsrc = src+logo_x1+1; x < logo_x2-1; x++, xdst++, xsrc++) {
/* Weighted interpolation based on relative distances, taking SAR into account */
weightl = (uint64_t) (logo_x2-1-x) * (y-logo_y1) * (logo_y2-1-y) * sar.den;
weightr = (uint64_t)(x-logo_x1) * (y-logo_y1) * (logo_y2-1-y) * sar.den;
weightt = (uint64_t)(x-logo_x1) * (logo_x2-1-x) * (logo_y2-1-y) * sar.num;
weightb = (uint64_t)(x-logo_x1) * (logo_x2-1-x) * (y-logo_y1) * sar.num;
interp =
left_sample * weightl
+
right_sample * weightr
+
(topleft[x-logo_x1] +
topleft[x-logo_x1-1] +
topleft[x-logo_x1+1]) * weightt
+
(botleft[x-logo_x1] +
botleft[x-logo_x1-1] +
botleft[x-logo_x1+1]) * weightb;
interp /= (weightl + weightr + weightt + weightb) * 3U;
if (y >= logo_y+band && y < logo_y+logo_h-band &&
x >= logo_x+band && x < logo_x+logo_w-band) {
*xdst = interp;
} else {
unsigned dist = 0;
if (x < logo_x+band)
dist = FFMAX(dist, logo_x-x+band);
else if (x >= logo_x+logo_w-band)
dist = FFMAX(dist, x-(logo_x+logo_w-1-band));
if (y < logo_y+band)
dist = FFMAX(dist, logo_y-y+band);
else if (y >= logo_y+logo_h-band)
dist = FFMAX(dist, y-(logo_y+logo_h-1-band));
*xdst = (*xsrc*dist + interp*(band-dist))/band;
if (show && (dist == band-1))
*xdst = 0;
}
}
dst += dst_linesize;
src += src_linesize;
}
}
typedef struct {
const AVClass *class;
int x, y, w, h, band, show;
} DelogoContext;
#define OFFSET(x) offsetof(DelogoContext, x)
#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
static const AVOption delogo_options[]= {
{ "x", "set logo x position", OFFSET(x), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS },
{ "y", "set logo y position", OFFSET(y), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS },
{ "w", "set logo width", OFFSET(w), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS },
{ "h", "set logo height", OFFSET(h), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS },
{ "band", "set delogo area band size", OFFSET(band), AV_OPT_TYPE_INT, { .i64 = 4 }, 1, INT_MAX, FLAGS },
{ "t", "set delogo area band size", OFFSET(band), AV_OPT_TYPE_INT, { .i64 = 4 }, 1, INT_MAX, FLAGS },
{ "show", "show delogo area", OFFSET(show), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
{ NULL },
};
AVFILTER_DEFINE_CLASS(delogo);
static int query_formats(AVFilterContext *ctx)
{
static const enum AVPixelFormat pix_fmts[] = {
AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV420P,
AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV440P,
AV_PIX_FMT_YUVA420P, AV_PIX_FMT_GRAY8,
AV_PIX_FMT_NONE
};
ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
return 0;
}
static av_cold int init(AVFilterContext *ctx)
{
DelogoContext *s = ctx->priv;
#define CHECK_UNSET_OPT(opt) \
if (s->opt == -1) { \
av_log(s, AV_LOG_ERROR, "Option %s was not set.\n", #opt); \
return AVERROR(EINVAL); \
}
CHECK_UNSET_OPT(x);
CHECK_UNSET_OPT(y);
CHECK_UNSET_OPT(w);
CHECK_UNSET_OPT(h);
av_log(ctx, AV_LOG_VERBOSE, "x:%d y:%d, w:%d h:%d band:%d show:%d\n",
s->x, s->y, s->w, s->h, s->band, s->show);
s->w += s->band*2;
s->h += s->band*2;
s->x -= s->band;
s->y -= s->band;
return 0;
}
static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
DelogoContext *s = inlink->dst->priv;
AVFilterLink *outlink = inlink->dst->outputs[0];
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
AVFrame *out;
int hsub0 = desc->log2_chroma_w;
int vsub0 = desc->log2_chroma_h;
int direct = 0;
int plane;
AVRational sar;
if (av_frame_is_writable(in)) {
direct = 1;
out = in;
} else {
out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
}
sar = in->sample_aspect_ratio;
/* Assume square pixels if SAR is unknown */
if (!sar.num)
sar.num = sar.den = 1;
for (plane = 0; plane < 4 && in->data[plane]; plane++) {
int hsub = plane == 1 || plane == 2 ? hsub0 : 0;
int vsub = plane == 1 || plane == 2 ? vsub0 : 0;
apply_delogo(out->data[plane], out->linesize[plane],
in ->data[plane], in ->linesize[plane],
FF_CEIL_RSHIFT(inlink->w, hsub),
FF_CEIL_RSHIFT(inlink->h, vsub),
sar, s->x>>hsub, s->y>>vsub,
/* Up and left borders were rounded down, inject lost bits
* into width and height to avoid error accumulation */
FF_CEIL_RSHIFT(s->w + (s->x & ((1<<hsub)-1)), hsub),
FF_CEIL_RSHIFT(s->h + (s->y & ((1<<vsub)-1)), vsub),
s->band>>FFMIN(hsub, vsub),
s->show, direct);
}
if (!direct)
av_frame_free(&in);
return ff_filter_frame(outlink, out);
}
static const AVFilterPad avfilter_vf_delogo_inputs[] = {
{
.name = "default",
.type = AVMEDIA_TYPE_VIDEO,
.get_video_buffer = ff_null_get_video_buffer,
.filter_frame = filter_frame,
},
{ NULL }
};
static const AVFilterPad avfilter_vf_delogo_outputs[] = {
{
.name = "default",
.type = AVMEDIA_TYPE_VIDEO,
},
{ NULL }
};
AVFilter avfilter_vf_delogo = {
.name = "delogo",
.description = NULL_IF_CONFIG_SMALL("Remove logo from input video."),
.priv_size = sizeof(DelogoContext),
.priv_class = &delogo_class,
.init = init,
.query_formats = query_formats,
.inputs = avfilter_vf_delogo_inputs,
.outputs = avfilter_vf_delogo_outputs,
.flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5733_1 |
crossvul-cpp_data_good_4945_0 | /* Alternative malloc implementation for multiple threads without
lock contention based on dlmalloc. (C) 2005-2006 Niall Douglas
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifdef _MSC_VER
/* Enable full aliasing on MSVC */
/*#pragma optimize("a", on)*/
#endif
/*#define FULLSANITYCHECKS*/
#include "nedmalloc.h"
#if defined(WIN32)
#include <malloc.h>
#endif
#define MSPACES 1
#define ONLY_MSPACES 1
#ifndef USE_LOCKS
#define USE_LOCKS 1
#endif
#define FOOTERS 1 /* Need to enable footers so frees lock the right mspace */
#undef DEBUG /* dlmalloc wants DEBUG either 0 or 1 */
#ifdef _DEBUG
#define DEBUG 1
#else
#define DEBUG 0
#endif
#ifdef NDEBUG /* Disable assert checking on release builds */
#undef DEBUG
#endif
/* The default of 64Kb means we spend too much time kernel-side */
#ifndef DEFAULT_GRANULARITY
#define DEFAULT_GRANULARITY (1*1024*1024)
#endif
/*#define USE_SPIN_LOCKS 0*/
/*#define FORCEINLINE*/
#include "malloc.c.h"
#ifdef NDEBUG /* Disable assert checking on release builds */
#undef DEBUG
#endif
/* The maximum concurrent threads in a pool possible */
#ifndef MAXTHREADSINPOOL
#define MAXTHREADSINPOOL 16
#endif
/* The maximum number of threadcaches which can be allocated */
#ifndef THREADCACHEMAXCACHES
#define THREADCACHEMAXCACHES 256
#endif
/* The maximum size to be allocated from the thread cache */
#ifndef THREADCACHEMAX
#define THREADCACHEMAX 8192
#endif
#if 0
/* The number of cache entries for finer grained bins. This is (topbitpos(THREADCACHEMAX)-4)*2 */
#define THREADCACHEMAXBINS ((13-4)*2)
#else
/* The number of cache entries. This is (topbitpos(THREADCACHEMAX)-4) */
#define THREADCACHEMAXBINS (13-4)
#endif
/* Point at which the free space in a thread cache is garbage collected */
#ifndef THREADCACHEMAXFREESPACE
#define THREADCACHEMAXFREESPACE (512*1024)
#endif
#ifdef WIN32
#define TLSVAR DWORD
#define TLSALLOC(k) (*(k)=TlsAlloc(), TLS_OUT_OF_INDEXES==*(k))
#define TLSFREE(k) (!TlsFree(k))
#define TLSGET(k) TlsGetValue(k)
#define TLSSET(k, a) (!TlsSetValue(k, a))
#ifdef DEBUG
static LPVOID ChkedTlsGetValue(DWORD idx)
{
LPVOID ret=TlsGetValue(idx);
assert(S_OK==GetLastError());
return ret;
}
#undef TLSGET
#define TLSGET(k) ChkedTlsGetValue(k)
#endif
#else
#define TLSVAR pthread_key_t
#define TLSALLOC(k) pthread_key_create(k, 0)
#define TLSFREE(k) pthread_key_delete(k)
#define TLSGET(k) pthread_getspecific(k)
#define TLSSET(k, a) pthread_setspecific(k, a)
#endif
#if 0
/* Only enable if testing with valgrind. Causes misoperation */
#define mspace_malloc(p, s) malloc(s)
#define mspace_realloc(p, m, s) realloc(m, s)
#define mspace_calloc(p, n, s) calloc(n, s)
#define mspace_free(p, m) free(m)
#endif
#if defined(__cplusplus)
#if !defined(NO_NED_NAMESPACE)
namespace nedalloc {
#else
extern "C" {
#endif
#endif
size_t nedblksize(void *mem) THROWSPEC
{
#if 0
/* Only enable if testing with valgrind. Causes misoperation */
return THREADCACHEMAX;
#else
if(mem)
{
mchunkptr p=mem2chunk(mem);
assert(cinuse(p)); /* If this fails, someone tried to free a block twice */
if(cinuse(p))
return chunksize(p)-overhead_for(p);
}
return 0;
#endif
}
void nedsetvalue(void *v) THROWSPEC { nedpsetvalue(0, v); }
void * nedmalloc(size_t size) THROWSPEC { return nedpmalloc(0, size); }
void * nedcalloc(size_t no, size_t size) THROWSPEC { return nedpcalloc(0, no, size); }
void * nedrealloc(void *mem, size_t size) THROWSPEC { return nedprealloc(0, mem, size); }
void nedfree(void *mem) THROWSPEC { nedpfree(0, mem); }
void * nedmemalign(size_t alignment, size_t bytes) THROWSPEC { return nedpmemalign(0, alignment, bytes); }
#if !NO_MALLINFO
struct mallinfo nedmallinfo(void) THROWSPEC { return nedpmallinfo(0); }
#endif
int nedmallopt(int parno, int value) THROWSPEC { return nedpmallopt(0, parno, value); }
int nedmalloc_trim(size_t pad) THROWSPEC { return nedpmalloc_trim(0, pad); }
void nedmalloc_stats(void) THROWSPEC { nedpmalloc_stats(0); }
size_t nedmalloc_footprint(void) THROWSPEC { return nedpmalloc_footprint(0); }
void **nedindependent_calloc(size_t elemsno, size_t elemsize, void **chunks) THROWSPEC { return nedpindependent_calloc(0, elemsno, elemsize, chunks); }
void **nedindependent_comalloc(size_t elems, size_t *sizes, void **chunks) THROWSPEC { return nedpindependent_comalloc(0, elems, sizes, chunks); }
struct threadcacheblk_t;
typedef struct threadcacheblk_t threadcacheblk;
struct threadcacheblk_t
{ /* Keep less than 16 bytes on 32 bit systems and 32 bytes on 64 bit systems */
#ifdef FULLSANITYCHECKS
unsigned int magic;
#endif
unsigned int lastUsed, size;
threadcacheblk *next, *prev;
};
typedef struct threadcache_t
{
#ifdef FULLSANITYCHECKS
unsigned int magic1;
#endif
int mymspace; /* Last mspace entry this thread used */
long threadid;
unsigned int mallocs, frees, successes;
size_t freeInCache; /* How much free space is stored in this cache */
threadcacheblk *bins[(THREADCACHEMAXBINS+1)*2];
#ifdef FULLSANITYCHECKS
unsigned int magic2;
#endif
} threadcache;
struct nedpool_t
{
MLOCK_T mutex;
void *uservalue;
int threads; /* Max entries in m to use */
threadcache *caches[THREADCACHEMAXCACHES];
TLSVAR mycache; /* Thread cache for this thread. 0 for unset, negative for use mspace-1 directly, otherwise is cache-1 */
mstate m[MAXTHREADSINPOOL+1]; /* mspace entries for this pool */
};
static nedpool syspool;
static FORCEINLINE unsigned int size2binidx(size_t _size) THROWSPEC
{ /* 8=1000 16=10000 20=10100 24=11000 32=100000 48=110000 4096=1000000000000 */
unsigned int topbit, size=(unsigned int)(_size>>4);
/* 16=1 20=1 24=1 32=10 48=11 64=100 96=110 128=1000 4096=100000000 */
#if defined(__GNUC__)
topbit = sizeof(size)*__CHAR_BIT__ - 1 - __builtin_clz(size);
#elif defined(_MSC_VER) && _MSC_VER>=1300
{
unsigned long bsrTopBit;
_BitScanReverse(&bsrTopBit, size);
topbit = bsrTopBit;
}
#else
#if 0
union {
unsigned asInt[2];
double asDouble;
};
int n;
asDouble = (double)size + 0.5;
topbit = (asInt[!FOX_BIGENDIAN] >> 20) - 1023;
#else
{
unsigned int x=size;
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >>16);
x = ~x;
x = x - ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x + (x >> 4)) & 0x0F0F0F0F;
x = x + (x << 8);
x = x + (x << 16);
topbit=31 - (x >> 24);
}
#endif
#endif
return topbit;
}
#ifdef FULLSANITYCHECKS
static void tcsanitycheck(threadcacheblk **ptr) THROWSPEC
{
assert((ptr[0] && ptr[1]) || (!ptr[0] && !ptr[1]));
if(ptr[0] && ptr[1])
{
assert(nedblksize(ptr[0])>=sizeof(threadcacheblk));
assert(nedblksize(ptr[1])>=sizeof(threadcacheblk));
assert(*(unsigned int *) "NEDN"==ptr[0]->magic);
assert(*(unsigned int *) "NEDN"==ptr[1]->magic);
assert(!ptr[0]->prev);
assert(!ptr[1]->next);
if(ptr[0]==ptr[1])
{
assert(!ptr[0]->next);
assert(!ptr[1]->prev);
}
}
}
static void tcfullsanitycheck(threadcache *tc) THROWSPEC
{
threadcacheblk **tcbptr=tc->bins;
int n;
for(n=0; n<=THREADCACHEMAXBINS; n++, tcbptr+=2)
{
threadcacheblk *b, *ob=0;
tcsanitycheck(tcbptr);
for(b=tcbptr[0]; b; ob=b, b=b->next)
{
assert(*(unsigned int *) "NEDN"==b->magic);
assert(!ob || ob->next==b);
assert(!ob || b->prev==ob);
}
}
}
#endif
static NOINLINE void RemoveCacheEntries(nedpool *p, threadcache *tc, unsigned int age) THROWSPEC
{
#ifdef FULLSANITYCHECKS
tcfullsanitycheck(tc);
#endif
if(tc->freeInCache)
{
threadcacheblk **tcbptr=tc->bins;
int n;
for(n=0; n<=THREADCACHEMAXBINS; n++, tcbptr+=2)
{
threadcacheblk **tcb=tcbptr+1; /* come from oldest end of list */
/*tcsanitycheck(tcbptr);*/
for(; *tcb && tc->frees-(*tcb)->lastUsed>=age; )
{
threadcacheblk *f=*tcb;
size_t blksize=f->size; /*nedblksize(f);*/
assert(blksize<=nedblksize(f));
assert(blksize);
#ifdef FULLSANITYCHECKS
assert(*(unsigned int *) "NEDN"==(*tcb)->magic);
#endif
*tcb=(*tcb)->prev;
if(*tcb)
(*tcb)->next=0;
else
*tcbptr=0;
tc->freeInCache-=blksize;
assert((long) tc->freeInCache>=0);
mspace_free(0, f);
/*tcsanitycheck(tcbptr);*/
}
}
}
#ifdef FULLSANITYCHECKS
tcfullsanitycheck(tc);
#endif
}
static void DestroyCaches(nedpool *p) THROWSPEC
{
if(p->caches)
{
threadcache *tc;
int n;
for(n=0; n<THREADCACHEMAXCACHES; n++)
{
if((tc=p->caches[n]))
{
tc->frees++;
RemoveCacheEntries(p, tc, 0);
assert(!tc->freeInCache);
tc->mymspace=-1;
tc->threadid=0;
mspace_free(0, tc);
p->caches[n]=0;
}
}
}
}
static NOINLINE threadcache *AllocCache(nedpool *p) THROWSPEC
{
threadcache *tc=0;
int n, end;
ACQUIRE_LOCK(&p->mutex);
for(n=0; n<THREADCACHEMAXCACHES && p->caches[n]; n++);
if(THREADCACHEMAXCACHES==n)
{ /* List exhausted, so disable for this thread */
RELEASE_LOCK(&p->mutex);
return 0;
}
tc=p->caches[n]=(threadcache *) mspace_calloc(p->m[0], 1, sizeof(threadcache));
if(!tc)
{
RELEASE_LOCK(&p->mutex);
return 0;
}
#ifdef FULLSANITYCHECKS
tc->magic1=*(unsigned int *)"NEDMALC1";
tc->magic2=*(unsigned int *)"NEDMALC2";
#endif
tc->threadid=(long)(size_t)CURRENT_THREAD;
for(end=0; p->m[end]; end++);
tc->mymspace=tc->threadid % end;
RELEASE_LOCK(&p->mutex);
if(TLSSET(p->mycache, (void *)(size_t)(n+1))) abort();
return tc;
}
static void *threadcache_malloc(nedpool *p, threadcache *tc, size_t *size) THROWSPEC
{
void *ret=0;
unsigned int bestsize;
unsigned int idx=size2binidx(*size);
size_t blksize=0;
threadcacheblk *blk, **binsptr;
#ifdef FULLSANITYCHECKS
tcfullsanitycheck(tc);
#endif
/* Calculate best fit bin size */
bestsize=1<<(idx+4);
#if 0
/* Finer grained bin fit */
idx<<=1;
if(*size>bestsize)
{
idx++;
bestsize+=bestsize>>1;
}
if(*size>bestsize)
{
idx++;
bestsize=1<<(4+(idx>>1));
}
#else
if(*size>bestsize)
{
idx++;
bestsize<<=1;
}
#endif
assert(bestsize>=*size);
if(*size<bestsize) *size=bestsize;
assert(*size<=THREADCACHEMAX);
assert(idx<=THREADCACHEMAXBINS);
binsptr=&tc->bins[idx*2];
/* Try to match close, but move up a bin if necessary */
blk=*binsptr;
if(!blk || blk->size<*size)
{ /* Bump it up a bin */
if(idx<THREADCACHEMAXBINS)
{
idx++;
binsptr+=2;
blk=*binsptr;
}
}
if(blk)
{
blksize=blk->size; /*nedblksize(blk);*/
assert(nedblksize(blk)>=blksize);
assert(blksize>=*size);
if(blk->next)
blk->next->prev=0;
*binsptr=blk->next;
if(!*binsptr)
binsptr[1]=0;
#ifdef FULLSANITYCHECKS
blk->magic=0;
#endif
assert(binsptr[0]!=blk && binsptr[1]!=blk);
assert(nedblksize(blk)>=sizeof(threadcacheblk) && nedblksize(blk)<=THREADCACHEMAX+CHUNK_OVERHEAD);
/*printf("malloc: %p, %p, %p, %lu\n", p, tc, blk, (long) size);*/
ret=(void *) blk;
}
++tc->mallocs;
if(ret)
{
assert(blksize>=*size);
++tc->successes;
tc->freeInCache-=blksize;
assert((long) tc->freeInCache>=0);
}
#if defined(DEBUG) && 0
if(!(tc->mallocs & 0xfff))
{
printf("*** threadcache=%u, mallocs=%u (%f), free=%u (%f), freeInCache=%u\n", (unsigned int) tc->threadid, tc->mallocs,
(float) tc->successes/tc->mallocs, tc->frees, (float) tc->successes/tc->frees, (unsigned int) tc->freeInCache);
}
#endif
#ifdef FULLSANITYCHECKS
tcfullsanitycheck(tc);
#endif
return ret;
}
static NOINLINE void ReleaseFreeInCache(nedpool *p, threadcache *tc, int mymspace) THROWSPEC
{
unsigned int age=THREADCACHEMAXFREESPACE/8192;
/*ACQUIRE_LOCK(&p->m[mymspace]->mutex);*/
while(age && tc->freeInCache>=THREADCACHEMAXFREESPACE)
{
RemoveCacheEntries(p, tc, age);
/*printf("*** Removing cache entries older than %u (%u)\n", age, (unsigned int) tc->freeInCache);*/
age>>=1;
}
/*RELEASE_LOCK(&p->m[mymspace]->mutex);*/
}
static void threadcache_free(nedpool *p, threadcache *tc, int mymspace, void *mem, size_t size) THROWSPEC
{
unsigned int bestsize;
unsigned int idx=size2binidx(size);
threadcacheblk **binsptr, *tck=(threadcacheblk *) mem;
assert(size>=sizeof(threadcacheblk) && size<=THREADCACHEMAX+CHUNK_OVERHEAD);
#ifdef DEBUG
{ /* Make sure this is a valid memory block */
mchunkptr p = mem2chunk(mem);
mstate fm = get_mstate_for(p);
if (!ok_magic(fm)) {
USAGE_ERROR_ACTION(fm, p);
return;
}
}
#endif
#ifdef FULLSANITYCHECKS
tcfullsanitycheck(tc);
#endif
/* Calculate best fit bin size */
bestsize=1<<(idx+4);
#if 0
/* Finer grained bin fit */
idx<<=1;
if(size>bestsize)
{
unsigned int biggerbestsize=bestsize+bestsize<<1;
if(size>=biggerbestsize)
{
idx++;
bestsize=biggerbestsize;
}
}
#endif
if(bestsize!=size) /* dlmalloc can round up, so we round down to preserve indexing */
size=bestsize;
binsptr=&tc->bins[idx*2];
assert(idx<=THREADCACHEMAXBINS);
if(tck==*binsptr)
{
fprintf(stderr, "Attempt to free already freed memory block %p - aborting!\n", tck);
abort();
}
#ifdef FULLSANITYCHECKS
tck->magic=*(unsigned int *) "NEDN";
#endif
tck->lastUsed=++tc->frees;
tck->size=(unsigned int) size;
tck->next=*binsptr;
tck->prev=0;
if(tck->next)
tck->next->prev=tck;
else
binsptr[1]=tck;
assert(!*binsptr || (*binsptr)->size==tck->size);
*binsptr=tck;
assert(tck==tc->bins[idx*2]);
assert(tc->bins[idx*2+1]==tck || binsptr[0]->next->prev==tck);
/*printf("free: %p, %p, %p, %lu\n", p, tc, mem, (long) size);*/
tc->freeInCache+=size;
#ifdef FULLSANITYCHECKS
tcfullsanitycheck(tc);
#endif
#if 1
if(tc->freeInCache>=THREADCACHEMAXFREESPACE)
ReleaseFreeInCache(p, tc, mymspace);
#endif
}
static NOINLINE int InitPool(nedpool *p, size_t capacity, int threads) THROWSPEC
{ /* threads is -1 for system pool */
ensure_initialization();
ACQUIRE_MALLOC_GLOBAL_LOCK();
if(p->threads) goto done;
if(INITIAL_LOCK(&p->mutex)) goto err;
if(TLSALLOC(&p->mycache)) goto err;
if(!(p->m[0]=(mstate) create_mspace(capacity, 1))) goto err;
p->m[0]->extp=p;
p->threads=(threads<1 || threads>MAXTHREADSINPOOL) ? MAXTHREADSINPOOL : threads;
done:
RELEASE_MALLOC_GLOBAL_LOCK();
return 1;
err:
if(threads<0)
abort(); /* If you can't allocate for system pool, we're screwed */
DestroyCaches(p);
if(p->m[0])
{
destroy_mspace(p->m[0]);
p->m[0]=0;
}
if(p->mycache)
{
if(TLSFREE(p->mycache)) abort();
p->mycache=0;
}
RELEASE_MALLOC_GLOBAL_LOCK();
return 0;
}
static NOINLINE mstate FindMSpace(nedpool *p, threadcache *tc, int *lastUsed, size_t size) THROWSPEC
{ /* Gets called when thread's last used mspace is in use. The strategy
is to run through the list of all available mspaces looking for an
unlocked one and if we fail, we create a new one so long as we don't
exceed p->threads */
int n, end;
for(n=end=*lastUsed+1; p->m[n]; end=++n)
{
if(TRY_LOCK(&p->m[n]->mutex)) goto found;
}
for(n=0; n<*lastUsed && p->m[n]; n++)
{
if(TRY_LOCK(&p->m[n]->mutex)) goto found;
}
if(end<p->threads)
{
mstate temp;
if(!(temp=(mstate) create_mspace(size, 1)))
goto badexit;
/* Now we're ready to modify the lists, we lock */
ACQUIRE_LOCK(&p->mutex);
while(p->m[end] && end<p->threads)
end++;
if(end>=p->threads)
{ /* Drat, must destroy it now */
RELEASE_LOCK(&p->mutex);
destroy_mspace((mspace) temp);
goto badexit;
}
/* We really want to make sure this goes into memory now but we
have to be careful of breaking aliasing rules, so write it twice */
{
volatile struct malloc_state **_m=(volatile struct malloc_state **) &p->m[end];
*_m=(p->m[end]=temp);
}
ACQUIRE_LOCK(&p->m[end]->mutex);
/*printf("Created mspace idx %d\n", end);*/
RELEASE_LOCK(&p->mutex);
n=end;
goto found;
}
/* Let it lock on the last one it used */
badexit:
ACQUIRE_LOCK(&p->m[*lastUsed]->mutex);
return p->m[*lastUsed];
found:
*lastUsed=n;
if(tc)
tc->mymspace=n;
else
{
if(TLSSET(p->mycache, (void *)(size_t)(-(n+1)))) abort();
}
return p->m[n];
}
nedpool *nedcreatepool(size_t capacity, int threads) THROWSPEC
{
nedpool *ret;
if(!(ret=(nedpool *) nedpcalloc(0, 1, sizeof(nedpool)))) return 0;
if(!InitPool(ret, capacity, threads))
{
nedpfree(0, ret);
return 0;
}
return ret;
}
void neddestroypool(nedpool *p) THROWSPEC
{
int n;
ACQUIRE_LOCK(&p->mutex);
DestroyCaches(p);
for(n=0; p->m[n]; n++)
{
destroy_mspace(p->m[n]);
p->m[n]=0;
}
RELEASE_LOCK(&p->mutex);
if(TLSFREE(p->mycache)) abort();
nedpfree(0, p);
}
void nedpsetvalue(nedpool *p, void *v) THROWSPEC
{
if(!p) { p=&syspool; if(!syspool.threads) InitPool(&syspool, 0, -1); }
p->uservalue=v;
}
void *nedgetvalue(nedpool **p, void *mem) THROWSPEC
{
nedpool *np=0;
mchunkptr mcp=mem2chunk(mem);
mstate fm;
if(!(is_aligned(chunk2mem(mcp))) && mcp->head != FENCEPOST_HEAD) return 0;
if(!cinuse(mcp)) return 0;
if(!next_pinuse(mcp)) return 0;
if(!is_mmapped(mcp) && !pinuse(mcp))
{
if(next_chunk(prev_chunk(mcp))!=mcp) return 0;
}
fm=get_mstate_for(mcp);
if(!ok_magic(fm)) return 0;
if(!ok_address(fm, mcp)) return 0;
if(!fm->extp) return 0;
np=(nedpool *) fm->extp;
if(p) *p=np;
return np->uservalue;
}
void neddisablethreadcache(nedpool *p) THROWSPEC
{
int mycache;
if(!p)
{
p=&syspool;
if(!syspool.threads) InitPool(&syspool, 0, -1);
}
mycache=(int)(size_t) TLSGET(p->mycache);
if(!mycache)
{ /* Set to mspace 0 */
if(TLSSET(p->mycache, (void *)-1)) abort();
}
else if(mycache>0)
{ /* Set to last used mspace */
threadcache *tc=p->caches[mycache-1];
#if defined(DEBUG)
printf("Threadcache utilisation: %lf%% in cache with %lf%% lost to other threads\n",
100.0*tc->successes/tc->mallocs, 100.0*((double) tc->mallocs-tc->frees)/tc->mallocs);
#endif
if(TLSSET(p->mycache, (void *)(size_t)(-tc->mymspace))) abort();
tc->frees++;
RemoveCacheEntries(p, tc, 0);
assert(!tc->freeInCache);
tc->mymspace=-1;
tc->threadid=0;
mspace_free(0, p->caches[mycache-1]);
p->caches[mycache-1]=0;
}
}
#define GETMSPACE(m,p,tc,ms,s,action) \
do \
{ \
mstate m = GetMSpace((p),(tc),(ms),(s)); \
action; \
RELEASE_LOCK(&m->mutex); \
} while (0)
static FORCEINLINE mstate GetMSpace(nedpool *p, threadcache *tc, int mymspace, size_t size) THROWSPEC
{ /* Returns a locked and ready for use mspace */
mstate m=p->m[mymspace];
assert(m);
if(!TRY_LOCK(&p->m[mymspace]->mutex)) m=FindMSpace(p, tc, &mymspace, size);\
/*assert(IS_LOCKED(&p->m[mymspace]->mutex));*/
return m;
}
static FORCEINLINE void GetThreadCache(nedpool **p, threadcache **tc, int *mymspace, size_t *size) THROWSPEC
{
int mycache;
if(size && *size<sizeof(threadcacheblk)) *size=sizeof(threadcacheblk);
if(!*p)
{
*p=&syspool;
if(!syspool.threads) InitPool(&syspool, 0, -1);
}
mycache=(int)(size_t) TLSGET((*p)->mycache);
if(mycache>0)
{
*tc=(*p)->caches[mycache-1];
*mymspace=(*tc)->mymspace;
}
else if(!mycache)
{
*tc=AllocCache(*p);
if(!*tc)
{ /* Disable */
if(TLSSET((*p)->mycache, (void *)-1)) abort();
*mymspace=0;
}
else
*mymspace=(*tc)->mymspace;
}
else
{
*tc=0;
*mymspace=-mycache-1;
}
assert(*mymspace>=0);
assert((long)(size_t)CURRENT_THREAD==(*tc)->threadid);
#ifdef FULLSANITYCHECKS
if(*tc)
{
if(*(unsigned int *)"NEDMALC1"!=(*tc)->magic1 || *(unsigned int *)"NEDMALC2"!=(*tc)->magic2)
{
abort();
}
}
#endif
}
void * nedpmalloc(nedpool *p, size_t size) THROWSPEC
{
void *ret=0;
threadcache *tc;
int mymspace;
GetThreadCache(&p, &tc, &mymspace, &size);
#if THREADCACHEMAX
if(tc && size<=THREADCACHEMAX)
{ /* Use the thread cache */
ret=threadcache_malloc(p, tc, &size);
}
#endif
if(!ret)
{ /* Use this thread's mspace */
GETMSPACE(m, p, tc, mymspace, size,
ret=mspace_malloc(m, size));
}
return ret;
}
void * nedpcalloc(nedpool *p, size_t no, size_t size) THROWSPEC
{
size_t rsize=size*no;
void *ret=0;
threadcache *tc;
int mymspace;
GetThreadCache(&p, &tc, &mymspace, &rsize);
#if THREADCACHEMAX
if(tc && rsize<=THREADCACHEMAX)
{ /* Use the thread cache */
if((ret=threadcache_malloc(p, tc, &rsize)))
memset(ret, 0, rsize);
}
#endif
if(!ret)
{ /* Use this thread's mspace */
GETMSPACE(m, p, tc, mymspace, rsize,
ret=mspace_calloc(m, 1, rsize));
}
return ret;
}
void * nedprealloc(nedpool *p, void *mem, size_t size) THROWSPEC
{
void *ret=0;
threadcache *tc;
int mymspace;
if(!mem) return nedpmalloc(p, size);
GetThreadCache(&p, &tc, &mymspace, &size);
#if THREADCACHEMAX
if(tc && size && size<=THREADCACHEMAX)
{ /* Use the thread cache */
size_t memsize=nedblksize(mem);
assert(memsize);
if((ret=threadcache_malloc(p, tc, &size)))
{
memcpy(ret, mem, memsize<size ? memsize : size);
if(memsize<=THREADCACHEMAX)
threadcache_free(p, tc, mymspace, mem, memsize);
else
mspace_free(0, mem);
}
}
#endif
if(!ret)
{ /* Reallocs always happen in the mspace they happened in, so skip
locking the preferred mspace for this thread */
ret=mspace_realloc(0, mem, size);
}
return ret;
}
void nedpfree(nedpool *p, void *mem) THROWSPEC
{ /* Frees always happen in the mspace they happened in, so skip
locking the preferred mspace for this thread */
threadcache *tc;
int mymspace;
size_t memsize;
assert(mem);
GetThreadCache(&p, &tc, &mymspace, 0);
#if THREADCACHEMAX
memsize=nedblksize(mem);
assert(memsize);
if(mem && tc && memsize<=(THREADCACHEMAX+CHUNK_OVERHEAD))
threadcache_free(p, tc, mymspace, mem, memsize);
else
#endif
mspace_free(0, mem);
}
void * nedpmemalign(nedpool *p, size_t alignment, size_t bytes) THROWSPEC
{
void *ret;
threadcache *tc;
int mymspace;
GetThreadCache(&p, &tc, &mymspace, &bytes);
{ /* Use this thread's mspace */
GETMSPACE(m, p, tc, mymspace, bytes,
ret=mspace_memalign(m, alignment, bytes));
}
return ret;
}
#if !NO_MALLINFO
struct mallinfo nedpmallinfo(nedpool *p) THROWSPEC
{
int n;
struct mallinfo ret={0};
if(!p) { p=&syspool; if(!syspool.threads) InitPool(&syspool, 0, -1); }
for(n=0; p->m[n]; n++)
{
struct mallinfo t=mspace_mallinfo(p->m[n]);
ret.arena+=t.arena;
ret.ordblks+=t.ordblks;
ret.hblkhd+=t.hblkhd;
ret.usmblks+=t.usmblks;
ret.uordblks+=t.uordblks;
ret.fordblks+=t.fordblks;
ret.keepcost+=t.keepcost;
}
return ret;
}
#endif
int nedpmallopt(nedpool *p, int parno, int value) THROWSPEC
{
return mspace_mallopt(parno, value);
}
int nedpmalloc_trim(nedpool *p, size_t pad) THROWSPEC
{
int n, ret=0;
if(!p) { p=&syspool; if(!syspool.threads) InitPool(&syspool, 0, -1); }
for(n=0; p->m[n]; n++)
{
ret+=mspace_trim(p->m[n], pad);
}
return ret;
}
void nedpmalloc_stats(nedpool *p) THROWSPEC
{
int n;
if(!p) { p=&syspool; if(!syspool.threads) InitPool(&syspool, 0, -1); }
for(n=0; p->m[n]; n++)
{
mspace_malloc_stats(p->m[n]);
}
}
size_t nedpmalloc_footprint(nedpool *p) THROWSPEC
{
size_t ret=0;
int n;
if(!p) { p=&syspool; if(!syspool.threads) InitPool(&syspool, 0, -1); }
for(n=0; p->m[n]; n++)
{
ret+=mspace_footprint(p->m[n]);
}
return ret;
}
void **nedpindependent_calloc(nedpool *p, size_t elemsno, size_t elemsize, void **chunks) THROWSPEC
{
void **ret;
threadcache *tc;
int mymspace;
GetThreadCache(&p, &tc, &mymspace, &elemsize);
GETMSPACE(m, p, tc, mymspace, elemsno*elemsize,
ret=mspace_independent_calloc(m, elemsno, elemsize, chunks));
return ret;
}
void **nedpindependent_comalloc(nedpool *p, size_t elems, size_t *sizes, void **chunks) THROWSPEC
{
void **ret;
threadcache *tc;
int mymspace;
size_t i, *adjustedsizes=(size_t *) alloca(elems*sizeof(size_t));
if(!adjustedsizes) return 0;
for(i=0; i<elems; i++)
adjustedsizes[i]=sizes[i]<sizeof(threadcacheblk) ? sizeof(threadcacheblk) : sizes[i];
GetThreadCache(&p, &tc, &mymspace, 0);
GETMSPACE(m, p, tc, mymspace, 0,
ret=mspace_independent_comalloc(m, elems, adjustedsizes, chunks));
return ret;
}
#ifdef OVERRIDE_STRDUP
/*
* This implementation is purely there to override the libc version, to
* avoid a crash due to allocation and free on different 'heaps'.
*/
char *strdup(const char *s1)
{
char *s2 = 0;
if (s1) {
size_t len = strlen(s1) + 1;
s2 = malloc(len);
memcpy(s2, s1, len);
}
return s2;
}
#endif
#if defined(__cplusplus)
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4945_0 |
crossvul-cpp_data_good_4787_11 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% 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/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
#include "magick/transform.h"
/*
Definitions
*/
#define DDSD_CAPS 0x00000001
#define DDSD_HEIGHT 0x00000002
#define DDSD_WIDTH 0x00000004
#define DDSD_PITCH 0x00000008
#define DDSD_PIXELFORMAT 0x00001000
#define DDSD_MIPMAPCOUNT 0x00020000
#define DDSD_LINEARSIZE 0x00080000
#define DDSD_DEPTH 0x00800000
#define DDPF_ALPHAPIXELS 0x00000001
#define DDPF_FOURCC 0x00000004
#define DDPF_RGB 0x00000040
#define DDPF_LUMINANCE 0x00020000
#define FOURCC_DXT1 0x31545844
#define FOURCC_DXT3 0x33545844
#define FOURCC_DXT5 0x35545844
#define DDSCAPS_COMPLEX 0x00000008
#define DDSCAPS_TEXTURE 0x00001000
#define DDSCAPS_MIPMAP 0x00400000
#define DDSCAPS2_CUBEMAP 0x00000200
#define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400
#define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800
#define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000
#define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000
#define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000
#define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000
#define DDSCAPS2_VOLUME 0x00200000
#ifndef SIZE_MAX
#define SIZE_MAX ((size_t) -1)
#endif
/*
Structure declarations.
*/
typedef struct _DDSPixelFormat
{
size_t
flags,
fourcc,
rgb_bitcount,
r_bitmask,
g_bitmask,
b_bitmask,
alpha_bitmask;
} DDSPixelFormat;
typedef struct _DDSInfo
{
size_t
flags,
height,
width,
pitchOrLinearSize,
depth,
mipmapcount,
ddscaps1,
ddscaps2;
DDSPixelFormat
pixelformat;
} DDSInfo;
typedef struct _DDSColors
{
unsigned char
r[4],
g[4],
b[4],
a[4];
} DDSColors;
typedef struct _DDSVector4
{
float
x,
y,
z,
w;
} DDSVector4;
typedef struct _DDSVector3
{
float
x,
y,
z;
} DDSVector3;
typedef struct _DDSSourceBlock
{
unsigned char
start,
end,
error;
} DDSSourceBlock;
typedef struct _DDSSingleColourLookup
{
DDSSourceBlock sources[2];
} DDSSingleColourLookup;
typedef MagickBooleanType
DDSDecoder(Image *, DDSInfo *, ExceptionInfo *);
static const DDSSingleColourLookup DDSLookup_5_4[] =
{
{ { { 0, 0, 0 }, { 0, 0, 0 } } },
{ { { 0, 0, 1 }, { 0, 1, 1 } } },
{ { { 0, 0, 2 }, { 0, 1, 0 } } },
{ { { 0, 0, 3 }, { 0, 1, 1 } } },
{ { { 0, 0, 4 }, { 0, 2, 1 } } },
{ { { 1, 0, 3 }, { 0, 2, 0 } } },
{ { { 1, 0, 2 }, { 0, 2, 1 } } },
{ { { 1, 0, 1 }, { 0, 3, 1 } } },
{ { { 1, 0, 0 }, { 0, 3, 0 } } },
{ { { 1, 0, 1 }, { 1, 2, 1 } } },
{ { { 1, 0, 2 }, { 1, 2, 0 } } },
{ { { 1, 0, 3 }, { 0, 4, 0 } } },
{ { { 1, 0, 4 }, { 0, 5, 1 } } },
{ { { 2, 0, 3 }, { 0, 5, 0 } } },
{ { { 2, 0, 2 }, { 0, 5, 1 } } },
{ { { 2, 0, 1 }, { 0, 6, 1 } } },
{ { { 2, 0, 0 }, { 0, 6, 0 } } },
{ { { 2, 0, 1 }, { 2, 3, 1 } } },
{ { { 2, 0, 2 }, { 2, 3, 0 } } },
{ { { 2, 0, 3 }, { 0, 7, 0 } } },
{ { { 2, 0, 4 }, { 1, 6, 1 } } },
{ { { 3, 0, 3 }, { 1, 6, 0 } } },
{ { { 3, 0, 2 }, { 0, 8, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 0 }, { 0, 9, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 2 }, { 0, 10, 1 } } },
{ { { 3, 0, 3 }, { 0, 10, 0 } } },
{ { { 3, 0, 4 }, { 2, 7, 1 } } },
{ { { 4, 0, 4 }, { 2, 7, 0 } } },
{ { { 4, 0, 3 }, { 0, 11, 0 } } },
{ { { 4, 0, 2 }, { 1, 10, 1 } } },
{ { { 4, 0, 1 }, { 1, 10, 0 } } },
{ { { 4, 0, 0 }, { 0, 12, 0 } } },
{ { { 4, 0, 1 }, { 0, 13, 1 } } },
{ { { 4, 0, 2 }, { 0, 13, 0 } } },
{ { { 4, 0, 3 }, { 0, 13, 1 } } },
{ { { 4, 0, 4 }, { 0, 14, 1 } } },
{ { { 5, 0, 3 }, { 0, 14, 0 } } },
{ { { 5, 0, 2 }, { 2, 11, 1 } } },
{ { { 5, 0, 1 }, { 2, 11, 0 } } },
{ { { 5, 0, 0 }, { 0, 15, 0 } } },
{ { { 5, 0, 1 }, { 1, 14, 1 } } },
{ { { 5, 0, 2 }, { 1, 14, 0 } } },
{ { { 5, 0, 3 }, { 0, 16, 0 } } },
{ { { 5, 0, 4 }, { 0, 17, 1 } } },
{ { { 6, 0, 3 }, { 0, 17, 0 } } },
{ { { 6, 0, 2 }, { 0, 17, 1 } } },
{ { { 6, 0, 1 }, { 0, 18, 1 } } },
{ { { 6, 0, 0 }, { 0, 18, 0 } } },
{ { { 6, 0, 1 }, { 2, 15, 1 } } },
{ { { 6, 0, 2 }, { 2, 15, 0 } } },
{ { { 6, 0, 3 }, { 0, 19, 0 } } },
{ { { 6, 0, 4 }, { 1, 18, 1 } } },
{ { { 7, 0, 3 }, { 1, 18, 0 } } },
{ { { 7, 0, 2 }, { 0, 20, 0 } } },
{ { { 7, 0, 1 }, { 0, 21, 1 } } },
{ { { 7, 0, 0 }, { 0, 21, 0 } } },
{ { { 7, 0, 1 }, { 0, 21, 1 } } },
{ { { 7, 0, 2 }, { 0, 22, 1 } } },
{ { { 7, 0, 3 }, { 0, 22, 0 } } },
{ { { 7, 0, 4 }, { 2, 19, 1 } } },
{ { { 8, 0, 4 }, { 2, 19, 0 } } },
{ { { 8, 0, 3 }, { 0, 23, 0 } } },
{ { { 8, 0, 2 }, { 1, 22, 1 } } },
{ { { 8, 0, 1 }, { 1, 22, 0 } } },
{ { { 8, 0, 0 }, { 0, 24, 0 } } },
{ { { 8, 0, 1 }, { 0, 25, 1 } } },
{ { { 8, 0, 2 }, { 0, 25, 0 } } },
{ { { 8, 0, 3 }, { 0, 25, 1 } } },
{ { { 8, 0, 4 }, { 0, 26, 1 } } },
{ { { 9, 0, 3 }, { 0, 26, 0 } } },
{ { { 9, 0, 2 }, { 2, 23, 1 } } },
{ { { 9, 0, 1 }, { 2, 23, 0 } } },
{ { { 9, 0, 0 }, { 0, 27, 0 } } },
{ { { 9, 0, 1 }, { 1, 26, 1 } } },
{ { { 9, 0, 2 }, { 1, 26, 0 } } },
{ { { 9, 0, 3 }, { 0, 28, 0 } } },
{ { { 9, 0, 4 }, { 0, 29, 1 } } },
{ { { 10, 0, 3 }, { 0, 29, 0 } } },
{ { { 10, 0, 2 }, { 0, 29, 1 } } },
{ { { 10, 0, 1 }, { 0, 30, 1 } } },
{ { { 10, 0, 0 }, { 0, 30, 0 } } },
{ { { 10, 0, 1 }, { 2, 27, 1 } } },
{ { { 10, 0, 2 }, { 2, 27, 0 } } },
{ { { 10, 0, 3 }, { 0, 31, 0 } } },
{ { { 10, 0, 4 }, { 1, 30, 1 } } },
{ { { 11, 0, 3 }, { 1, 30, 0 } } },
{ { { 11, 0, 2 }, { 4, 24, 0 } } },
{ { { 11, 0, 1 }, { 1, 31, 1 } } },
{ { { 11, 0, 0 }, { 1, 31, 0 } } },
{ { { 11, 0, 1 }, { 1, 31, 1 } } },
{ { { 11, 0, 2 }, { 2, 30, 1 } } },
{ { { 11, 0, 3 }, { 2, 30, 0 } } },
{ { { 11, 0, 4 }, { 2, 31, 1 } } },
{ { { 12, 0, 4 }, { 2, 31, 0 } } },
{ { { 12, 0, 3 }, { 4, 27, 0 } } },
{ { { 12, 0, 2 }, { 3, 30, 1 } } },
{ { { 12, 0, 1 }, { 3, 30, 0 } } },
{ { { 12, 0, 0 }, { 4, 28, 0 } } },
{ { { 12, 0, 1 }, { 3, 31, 1 } } },
{ { { 12, 0, 2 }, { 3, 31, 0 } } },
{ { { 12, 0, 3 }, { 3, 31, 1 } } },
{ { { 12, 0, 4 }, { 4, 30, 1 } } },
{ { { 13, 0, 3 }, { 4, 30, 0 } } },
{ { { 13, 0, 2 }, { 6, 27, 1 } } },
{ { { 13, 0, 1 }, { 6, 27, 0 } } },
{ { { 13, 0, 0 }, { 4, 31, 0 } } },
{ { { 13, 0, 1 }, { 5, 30, 1 } } },
{ { { 13, 0, 2 }, { 5, 30, 0 } } },
{ { { 13, 0, 3 }, { 8, 24, 0 } } },
{ { { 13, 0, 4 }, { 5, 31, 1 } } },
{ { { 14, 0, 3 }, { 5, 31, 0 } } },
{ { { 14, 0, 2 }, { 5, 31, 1 } } },
{ { { 14, 0, 1 }, { 6, 30, 1 } } },
{ { { 14, 0, 0 }, { 6, 30, 0 } } },
{ { { 14, 0, 1 }, { 6, 31, 1 } } },
{ { { 14, 0, 2 }, { 6, 31, 0 } } },
{ { { 14, 0, 3 }, { 8, 27, 0 } } },
{ { { 14, 0, 4 }, { 7, 30, 1 } } },
{ { { 15, 0, 3 }, { 7, 30, 0 } } },
{ { { 15, 0, 2 }, { 8, 28, 0 } } },
{ { { 15, 0, 1 }, { 7, 31, 1 } } },
{ { { 15, 0, 0 }, { 7, 31, 0 } } },
{ { { 15, 0, 1 }, { 7, 31, 1 } } },
{ { { 15, 0, 2 }, { 8, 30, 1 } } },
{ { { 15, 0, 3 }, { 8, 30, 0 } } },
{ { { 15, 0, 4 }, { 10, 27, 1 } } },
{ { { 16, 0, 4 }, { 10, 27, 0 } } },
{ { { 16, 0, 3 }, { 8, 31, 0 } } },
{ { { 16, 0, 2 }, { 9, 30, 1 } } },
{ { { 16, 0, 1 }, { 9, 30, 0 } } },
{ { { 16, 0, 0 }, { 12, 24, 0 } } },
{ { { 16, 0, 1 }, { 9, 31, 1 } } },
{ { { 16, 0, 2 }, { 9, 31, 0 } } },
{ { { 16, 0, 3 }, { 9, 31, 1 } } },
{ { { 16, 0, 4 }, { 10, 30, 1 } } },
{ { { 17, 0, 3 }, { 10, 30, 0 } } },
{ { { 17, 0, 2 }, { 10, 31, 1 } } },
{ { { 17, 0, 1 }, { 10, 31, 0 } } },
{ { { 17, 0, 0 }, { 12, 27, 0 } } },
{ { { 17, 0, 1 }, { 11, 30, 1 } } },
{ { { 17, 0, 2 }, { 11, 30, 0 } } },
{ { { 17, 0, 3 }, { 12, 28, 0 } } },
{ { { 17, 0, 4 }, { 11, 31, 1 } } },
{ { { 18, 0, 3 }, { 11, 31, 0 } } },
{ { { 18, 0, 2 }, { 11, 31, 1 } } },
{ { { 18, 0, 1 }, { 12, 30, 1 } } },
{ { { 18, 0, 0 }, { 12, 30, 0 } } },
{ { { 18, 0, 1 }, { 14, 27, 1 } } },
{ { { 18, 0, 2 }, { 14, 27, 0 } } },
{ { { 18, 0, 3 }, { 12, 31, 0 } } },
{ { { 18, 0, 4 }, { 13, 30, 1 } } },
{ { { 19, 0, 3 }, { 13, 30, 0 } } },
{ { { 19, 0, 2 }, { 16, 24, 0 } } },
{ { { 19, 0, 1 }, { 13, 31, 1 } } },
{ { { 19, 0, 0 }, { 13, 31, 0 } } },
{ { { 19, 0, 1 }, { 13, 31, 1 } } },
{ { { 19, 0, 2 }, { 14, 30, 1 } } },
{ { { 19, 0, 3 }, { 14, 30, 0 } } },
{ { { 19, 0, 4 }, { 14, 31, 1 } } },
{ { { 20, 0, 4 }, { 14, 31, 0 } } },
{ { { 20, 0, 3 }, { 16, 27, 0 } } },
{ { { 20, 0, 2 }, { 15, 30, 1 } } },
{ { { 20, 0, 1 }, { 15, 30, 0 } } },
{ { { 20, 0, 0 }, { 16, 28, 0 } } },
{ { { 20, 0, 1 }, { 15, 31, 1 } } },
{ { { 20, 0, 2 }, { 15, 31, 0 } } },
{ { { 20, 0, 3 }, { 15, 31, 1 } } },
{ { { 20, 0, 4 }, { 16, 30, 1 } } },
{ { { 21, 0, 3 }, { 16, 30, 0 } } },
{ { { 21, 0, 2 }, { 18, 27, 1 } } },
{ { { 21, 0, 1 }, { 18, 27, 0 } } },
{ { { 21, 0, 0 }, { 16, 31, 0 } } },
{ { { 21, 0, 1 }, { 17, 30, 1 } } },
{ { { 21, 0, 2 }, { 17, 30, 0 } } },
{ { { 21, 0, 3 }, { 20, 24, 0 } } },
{ { { 21, 0, 4 }, { 17, 31, 1 } } },
{ { { 22, 0, 3 }, { 17, 31, 0 } } },
{ { { 22, 0, 2 }, { 17, 31, 1 } } },
{ { { 22, 0, 1 }, { 18, 30, 1 } } },
{ { { 22, 0, 0 }, { 18, 30, 0 } } },
{ { { 22, 0, 1 }, { 18, 31, 1 } } },
{ { { 22, 0, 2 }, { 18, 31, 0 } } },
{ { { 22, 0, 3 }, { 20, 27, 0 } } },
{ { { 22, 0, 4 }, { 19, 30, 1 } } },
{ { { 23, 0, 3 }, { 19, 30, 0 } } },
{ { { 23, 0, 2 }, { 20, 28, 0 } } },
{ { { 23, 0, 1 }, { 19, 31, 1 } } },
{ { { 23, 0, 0 }, { 19, 31, 0 } } },
{ { { 23, 0, 1 }, { 19, 31, 1 } } },
{ { { 23, 0, 2 }, { 20, 30, 1 } } },
{ { { 23, 0, 3 }, { 20, 30, 0 } } },
{ { { 23, 0, 4 }, { 22, 27, 1 } } },
{ { { 24, 0, 4 }, { 22, 27, 0 } } },
{ { { 24, 0, 3 }, { 20, 31, 0 } } },
{ { { 24, 0, 2 }, { 21, 30, 1 } } },
{ { { 24, 0, 1 }, { 21, 30, 0 } } },
{ { { 24, 0, 0 }, { 24, 24, 0 } } },
{ { { 24, 0, 1 }, { 21, 31, 1 } } },
{ { { 24, 0, 2 }, { 21, 31, 0 } } },
{ { { 24, 0, 3 }, { 21, 31, 1 } } },
{ { { 24, 0, 4 }, { 22, 30, 1 } } },
{ { { 25, 0, 3 }, { 22, 30, 0 } } },
{ { { 25, 0, 2 }, { 22, 31, 1 } } },
{ { { 25, 0, 1 }, { 22, 31, 0 } } },
{ { { 25, 0, 0 }, { 24, 27, 0 } } },
{ { { 25, 0, 1 }, { 23, 30, 1 } } },
{ { { 25, 0, 2 }, { 23, 30, 0 } } },
{ { { 25, 0, 3 }, { 24, 28, 0 } } },
{ { { 25, 0, 4 }, { 23, 31, 1 } } },
{ { { 26, 0, 3 }, { 23, 31, 0 } } },
{ { { 26, 0, 2 }, { 23, 31, 1 } } },
{ { { 26, 0, 1 }, { 24, 30, 1 } } },
{ { { 26, 0, 0 }, { 24, 30, 0 } } },
{ { { 26, 0, 1 }, { 26, 27, 1 } } },
{ { { 26, 0, 2 }, { 26, 27, 0 } } },
{ { { 26, 0, 3 }, { 24, 31, 0 } } },
{ { { 26, 0, 4 }, { 25, 30, 1 } } },
{ { { 27, 0, 3 }, { 25, 30, 0 } } },
{ { { 27, 0, 2 }, { 28, 24, 0 } } },
{ { { 27, 0, 1 }, { 25, 31, 1 } } },
{ { { 27, 0, 0 }, { 25, 31, 0 } } },
{ { { 27, 0, 1 }, { 25, 31, 1 } } },
{ { { 27, 0, 2 }, { 26, 30, 1 } } },
{ { { 27, 0, 3 }, { 26, 30, 0 } } },
{ { { 27, 0, 4 }, { 26, 31, 1 } } },
{ { { 28, 0, 4 }, { 26, 31, 0 } } },
{ { { 28, 0, 3 }, { 28, 27, 0 } } },
{ { { 28, 0, 2 }, { 27, 30, 1 } } },
{ { { 28, 0, 1 }, { 27, 30, 0 } } },
{ { { 28, 0, 0 }, { 28, 28, 0 } } },
{ { { 28, 0, 1 }, { 27, 31, 1 } } },
{ { { 28, 0, 2 }, { 27, 31, 0 } } },
{ { { 28, 0, 3 }, { 27, 31, 1 } } },
{ { { 28, 0, 4 }, { 28, 30, 1 } } },
{ { { 29, 0, 3 }, { 28, 30, 0 } } },
{ { { 29, 0, 2 }, { 30, 27, 1 } } },
{ { { 29, 0, 1 }, { 30, 27, 0 } } },
{ { { 29, 0, 0 }, { 28, 31, 0 } } },
{ { { 29, 0, 1 }, { 29, 30, 1 } } },
{ { { 29, 0, 2 }, { 29, 30, 0 } } },
{ { { 29, 0, 3 }, { 29, 30, 1 } } },
{ { { 29, 0, 4 }, { 29, 31, 1 } } },
{ { { 30, 0, 3 }, { 29, 31, 0 } } },
{ { { 30, 0, 2 }, { 29, 31, 1 } } },
{ { { 30, 0, 1 }, { 30, 30, 1 } } },
{ { { 30, 0, 0 }, { 30, 30, 0 } } },
{ { { 30, 0, 1 }, { 30, 31, 1 } } },
{ { { 30, 0, 2 }, { 30, 31, 0 } } },
{ { { 30, 0, 3 }, { 30, 31, 1 } } },
{ { { 30, 0, 4 }, { 31, 30, 1 } } },
{ { { 31, 0, 3 }, { 31, 30, 0 } } },
{ { { 31, 0, 2 }, { 31, 30, 1 } } },
{ { { 31, 0, 1 }, { 31, 31, 1 } } },
{ { { 31, 0, 0 }, { 31, 31, 0 } } }
};
static const DDSSingleColourLookup DDSLookup_6_4[] =
{
{ { { 0, 0, 0 }, { 0, 0, 0 } } },
{ { { 0, 0, 1 }, { 0, 1, 0 } } },
{ { { 0, 0, 2 }, { 0, 2, 0 } } },
{ { { 1, 0, 1 }, { 0, 3, 1 } } },
{ { { 1, 0, 0 }, { 0, 3, 0 } } },
{ { { 1, 0, 1 }, { 0, 4, 0 } } },
{ { { 1, 0, 2 }, { 0, 5, 0 } } },
{ { { 2, 0, 1 }, { 0, 6, 1 } } },
{ { { 2, 0, 0 }, { 0, 6, 0 } } },
{ { { 2, 0, 1 }, { 0, 7, 0 } } },
{ { { 2, 0, 2 }, { 0, 8, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 0 }, { 0, 9, 0 } } },
{ { { 3, 0, 1 }, { 0, 10, 0 } } },
{ { { 3, 0, 2 }, { 0, 11, 0 } } },
{ { { 4, 0, 1 }, { 0, 12, 1 } } },
{ { { 4, 0, 0 }, { 0, 12, 0 } } },
{ { { 4, 0, 1 }, { 0, 13, 0 } } },
{ { { 4, 0, 2 }, { 0, 14, 0 } } },
{ { { 5, 0, 1 }, { 0, 15, 1 } } },
{ { { 5, 0, 0 }, { 0, 15, 0 } } },
{ { { 5, 0, 1 }, { 0, 16, 0 } } },
{ { { 5, 0, 2 }, { 1, 15, 0 } } },
{ { { 6, 0, 1 }, { 0, 17, 0 } } },
{ { { 6, 0, 0 }, { 0, 18, 0 } } },
{ { { 6, 0, 1 }, { 0, 19, 0 } } },
{ { { 6, 0, 2 }, { 3, 14, 0 } } },
{ { { 7, 0, 1 }, { 0, 20, 0 } } },
{ { { 7, 0, 0 }, { 0, 21, 0 } } },
{ { { 7, 0, 1 }, { 0, 22, 0 } } },
{ { { 7, 0, 2 }, { 4, 15, 0 } } },
{ { { 8, 0, 1 }, { 0, 23, 0 } } },
{ { { 8, 0, 0 }, { 0, 24, 0 } } },
{ { { 8, 0, 1 }, { 0, 25, 0 } } },
{ { { 8, 0, 2 }, { 6, 14, 0 } } },
{ { { 9, 0, 1 }, { 0, 26, 0 } } },
{ { { 9, 0, 0 }, { 0, 27, 0 } } },
{ { { 9, 0, 1 }, { 0, 28, 0 } } },
{ { { 9, 0, 2 }, { 7, 15, 0 } } },
{ { { 10, 0, 1 }, { 0, 29, 0 } } },
{ { { 10, 0, 0 }, { 0, 30, 0 } } },
{ { { 10, 0, 1 }, { 0, 31, 0 } } },
{ { { 10, 0, 2 }, { 9, 14, 0 } } },
{ { { 11, 0, 1 }, { 0, 32, 0 } } },
{ { { 11, 0, 0 }, { 0, 33, 0 } } },
{ { { 11, 0, 1 }, { 2, 30, 0 } } },
{ { { 11, 0, 2 }, { 0, 34, 0 } } },
{ { { 12, 0, 1 }, { 0, 35, 0 } } },
{ { { 12, 0, 0 }, { 0, 36, 0 } } },
{ { { 12, 0, 1 }, { 3, 31, 0 } } },
{ { { 12, 0, 2 }, { 0, 37, 0 } } },
{ { { 13, 0, 1 }, { 0, 38, 0 } } },
{ { { 13, 0, 0 }, { 0, 39, 0 } } },
{ { { 13, 0, 1 }, { 5, 30, 0 } } },
{ { { 13, 0, 2 }, { 0, 40, 0 } } },
{ { { 14, 0, 1 }, { 0, 41, 0 } } },
{ { { 14, 0, 0 }, { 0, 42, 0 } } },
{ { { 14, 0, 1 }, { 6, 31, 0 } } },
{ { { 14, 0, 2 }, { 0, 43, 0 } } },
{ { { 15, 0, 1 }, { 0, 44, 0 } } },
{ { { 15, 0, 0 }, { 0, 45, 0 } } },
{ { { 15, 0, 1 }, { 8, 30, 0 } } },
{ { { 15, 0, 2 }, { 0, 46, 0 } } },
{ { { 16, 0, 2 }, { 0, 47, 0 } } },
{ { { 16, 0, 1 }, { 1, 46, 0 } } },
{ { { 16, 0, 0 }, { 0, 48, 0 } } },
{ { { 16, 0, 1 }, { 0, 49, 0 } } },
{ { { 16, 0, 2 }, { 0, 50, 0 } } },
{ { { 17, 0, 1 }, { 2, 47, 0 } } },
{ { { 17, 0, 0 }, { 0, 51, 0 } } },
{ { { 17, 0, 1 }, { 0, 52, 0 } } },
{ { { 17, 0, 2 }, { 0, 53, 0 } } },
{ { { 18, 0, 1 }, { 4, 46, 0 } } },
{ { { 18, 0, 0 }, { 0, 54, 0 } } },
{ { { 18, 0, 1 }, { 0, 55, 0 } } },
{ { { 18, 0, 2 }, { 0, 56, 0 } } },
{ { { 19, 0, 1 }, { 5, 47, 0 } } },
{ { { 19, 0, 0 }, { 0, 57, 0 } } },
{ { { 19, 0, 1 }, { 0, 58, 0 } } },
{ { { 19, 0, 2 }, { 0, 59, 0 } } },
{ { { 20, 0, 1 }, { 7, 46, 0 } } },
{ { { 20, 0, 0 }, { 0, 60, 0 } } },
{ { { 20, 0, 1 }, { 0, 61, 0 } } },
{ { { 20, 0, 2 }, { 0, 62, 0 } } },
{ { { 21, 0, 1 }, { 8, 47, 0 } } },
{ { { 21, 0, 0 }, { 0, 63, 0 } } },
{ { { 21, 0, 1 }, { 1, 62, 0 } } },
{ { { 21, 0, 2 }, { 1, 63, 0 } } },
{ { { 22, 0, 1 }, { 10, 46, 0 } } },
{ { { 22, 0, 0 }, { 2, 62, 0 } } },
{ { { 22, 0, 1 }, { 2, 63, 0 } } },
{ { { 22, 0, 2 }, { 3, 62, 0 } } },
{ { { 23, 0, 1 }, { 11, 47, 0 } } },
{ { { 23, 0, 0 }, { 3, 63, 0 } } },
{ { { 23, 0, 1 }, { 4, 62, 0 } } },
{ { { 23, 0, 2 }, { 4, 63, 0 } } },
{ { { 24, 0, 1 }, { 13, 46, 0 } } },
{ { { 24, 0, 0 }, { 5, 62, 0 } } },
{ { { 24, 0, 1 }, { 5, 63, 0 } } },
{ { { 24, 0, 2 }, { 6, 62, 0 } } },
{ { { 25, 0, 1 }, { 14, 47, 0 } } },
{ { { 25, 0, 0 }, { 6, 63, 0 } } },
{ { { 25, 0, 1 }, { 7, 62, 0 } } },
{ { { 25, 0, 2 }, { 7, 63, 0 } } },
{ { { 26, 0, 1 }, { 16, 45, 0 } } },
{ { { 26, 0, 0 }, { 8, 62, 0 } } },
{ { { 26, 0, 1 }, { 8, 63, 0 } } },
{ { { 26, 0, 2 }, { 9, 62, 0 } } },
{ { { 27, 0, 1 }, { 16, 48, 0 } } },
{ { { 27, 0, 0 }, { 9, 63, 0 } } },
{ { { 27, 0, 1 }, { 10, 62, 0 } } },
{ { { 27, 0, 2 }, { 10, 63, 0 } } },
{ { { 28, 0, 1 }, { 16, 51, 0 } } },
{ { { 28, 0, 0 }, { 11, 62, 0 } } },
{ { { 28, 0, 1 }, { 11, 63, 0 } } },
{ { { 28, 0, 2 }, { 12, 62, 0 } } },
{ { { 29, 0, 1 }, { 16, 54, 0 } } },
{ { { 29, 0, 0 }, { 12, 63, 0 } } },
{ { { 29, 0, 1 }, { 13, 62, 0 } } },
{ { { 29, 0, 2 }, { 13, 63, 0 } } },
{ { { 30, 0, 1 }, { 16, 57, 0 } } },
{ { { 30, 0, 0 }, { 14, 62, 0 } } },
{ { { 30, 0, 1 }, { 14, 63, 0 } } },
{ { { 30, 0, 2 }, { 15, 62, 0 } } },
{ { { 31, 0, 1 }, { 16, 60, 0 } } },
{ { { 31, 0, 0 }, { 15, 63, 0 } } },
{ { { 31, 0, 1 }, { 24, 46, 0 } } },
{ { { 31, 0, 2 }, { 16, 62, 0 } } },
{ { { 32, 0, 2 }, { 16, 63, 0 } } },
{ { { 32, 0, 1 }, { 17, 62, 0 } } },
{ { { 32, 0, 0 }, { 25, 47, 0 } } },
{ { { 32, 0, 1 }, { 17, 63, 0 } } },
{ { { 32, 0, 2 }, { 18, 62, 0 } } },
{ { { 33, 0, 1 }, { 18, 63, 0 } } },
{ { { 33, 0, 0 }, { 27, 46, 0 } } },
{ { { 33, 0, 1 }, { 19, 62, 0 } } },
{ { { 33, 0, 2 }, { 19, 63, 0 } } },
{ { { 34, 0, 1 }, { 20, 62, 0 } } },
{ { { 34, 0, 0 }, { 28, 47, 0 } } },
{ { { 34, 0, 1 }, { 20, 63, 0 } } },
{ { { 34, 0, 2 }, { 21, 62, 0 } } },
{ { { 35, 0, 1 }, { 21, 63, 0 } } },
{ { { 35, 0, 0 }, { 30, 46, 0 } } },
{ { { 35, 0, 1 }, { 22, 62, 0 } } },
{ { { 35, 0, 2 }, { 22, 63, 0 } } },
{ { { 36, 0, 1 }, { 23, 62, 0 } } },
{ { { 36, 0, 0 }, { 31, 47, 0 } } },
{ { { 36, 0, 1 }, { 23, 63, 0 } } },
{ { { 36, 0, 2 }, { 24, 62, 0 } } },
{ { { 37, 0, 1 }, { 24, 63, 0 } } },
{ { { 37, 0, 0 }, { 32, 47, 0 } } },
{ { { 37, 0, 1 }, { 25, 62, 0 } } },
{ { { 37, 0, 2 }, { 25, 63, 0 } } },
{ { { 38, 0, 1 }, { 26, 62, 0 } } },
{ { { 38, 0, 0 }, { 32, 50, 0 } } },
{ { { 38, 0, 1 }, { 26, 63, 0 } } },
{ { { 38, 0, 2 }, { 27, 62, 0 } } },
{ { { 39, 0, 1 }, { 27, 63, 0 } } },
{ { { 39, 0, 0 }, { 32, 53, 0 } } },
{ { { 39, 0, 1 }, { 28, 62, 0 } } },
{ { { 39, 0, 2 }, { 28, 63, 0 } } },
{ { { 40, 0, 1 }, { 29, 62, 0 } } },
{ { { 40, 0, 0 }, { 32, 56, 0 } } },
{ { { 40, 0, 1 }, { 29, 63, 0 } } },
{ { { 40, 0, 2 }, { 30, 62, 0 } } },
{ { { 41, 0, 1 }, { 30, 63, 0 } } },
{ { { 41, 0, 0 }, { 32, 59, 0 } } },
{ { { 41, 0, 1 }, { 31, 62, 0 } } },
{ { { 41, 0, 2 }, { 31, 63, 0 } } },
{ { { 42, 0, 1 }, { 32, 61, 0 } } },
{ { { 42, 0, 0 }, { 32, 62, 0 } } },
{ { { 42, 0, 1 }, { 32, 63, 0 } } },
{ { { 42, 0, 2 }, { 41, 46, 0 } } },
{ { { 43, 0, 1 }, { 33, 62, 0 } } },
{ { { 43, 0, 0 }, { 33, 63, 0 } } },
{ { { 43, 0, 1 }, { 34, 62, 0 } } },
{ { { 43, 0, 2 }, { 42, 47, 0 } } },
{ { { 44, 0, 1 }, { 34, 63, 0 } } },
{ { { 44, 0, 0 }, { 35, 62, 0 } } },
{ { { 44, 0, 1 }, { 35, 63, 0 } } },
{ { { 44, 0, 2 }, { 44, 46, 0 } } },
{ { { 45, 0, 1 }, { 36, 62, 0 } } },
{ { { 45, 0, 0 }, { 36, 63, 0 } } },
{ { { 45, 0, 1 }, { 37, 62, 0 } } },
{ { { 45, 0, 2 }, { 45, 47, 0 } } },
{ { { 46, 0, 1 }, { 37, 63, 0 } } },
{ { { 46, 0, 0 }, { 38, 62, 0 } } },
{ { { 46, 0, 1 }, { 38, 63, 0 } } },
{ { { 46, 0, 2 }, { 47, 46, 0 } } },
{ { { 47, 0, 1 }, { 39, 62, 0 } } },
{ { { 47, 0, 0 }, { 39, 63, 0 } } },
{ { { 47, 0, 1 }, { 40, 62, 0 } } },
{ { { 47, 0, 2 }, { 48, 46, 0 } } },
{ { { 48, 0, 2 }, { 40, 63, 0 } } },
{ { { 48, 0, 1 }, { 41, 62, 0 } } },
{ { { 48, 0, 0 }, { 41, 63, 0 } } },
{ { { 48, 0, 1 }, { 48, 49, 0 } } },
{ { { 48, 0, 2 }, { 42, 62, 0 } } },
{ { { 49, 0, 1 }, { 42, 63, 0 } } },
{ { { 49, 0, 0 }, { 43, 62, 0 } } },
{ { { 49, 0, 1 }, { 48, 52, 0 } } },
{ { { 49, 0, 2 }, { 43, 63, 0 } } },
{ { { 50, 0, 1 }, { 44, 62, 0 } } },
{ { { 50, 0, 0 }, { 44, 63, 0 } } },
{ { { 50, 0, 1 }, { 48, 55, 0 } } },
{ { { 50, 0, 2 }, { 45, 62, 0 } } },
{ { { 51, 0, 1 }, { 45, 63, 0 } } },
{ { { 51, 0, 0 }, { 46, 62, 0 } } },
{ { { 51, 0, 1 }, { 48, 58, 0 } } },
{ { { 51, 0, 2 }, { 46, 63, 0 } } },
{ { { 52, 0, 1 }, { 47, 62, 0 } } },
{ { { 52, 0, 0 }, { 47, 63, 0 } } },
{ { { 52, 0, 1 }, { 48, 61, 0 } } },
{ { { 52, 0, 2 }, { 48, 62, 0 } } },
{ { { 53, 0, 1 }, { 56, 47, 0 } } },
{ { { 53, 0, 0 }, { 48, 63, 0 } } },
{ { { 53, 0, 1 }, { 49, 62, 0 } } },
{ { { 53, 0, 2 }, { 49, 63, 0 } } },
{ { { 54, 0, 1 }, { 58, 46, 0 } } },
{ { { 54, 0, 0 }, { 50, 62, 0 } } },
{ { { 54, 0, 1 }, { 50, 63, 0 } } },
{ { { 54, 0, 2 }, { 51, 62, 0 } } },
{ { { 55, 0, 1 }, { 59, 47, 0 } } },
{ { { 55, 0, 0 }, { 51, 63, 0 } } },
{ { { 55, 0, 1 }, { 52, 62, 0 } } },
{ { { 55, 0, 2 }, { 52, 63, 0 } } },
{ { { 56, 0, 1 }, { 61, 46, 0 } } },
{ { { 56, 0, 0 }, { 53, 62, 0 } } },
{ { { 56, 0, 1 }, { 53, 63, 0 } } },
{ { { 56, 0, 2 }, { 54, 62, 0 } } },
{ { { 57, 0, 1 }, { 62, 47, 0 } } },
{ { { 57, 0, 0 }, { 54, 63, 0 } } },
{ { { 57, 0, 1 }, { 55, 62, 0 } } },
{ { { 57, 0, 2 }, { 55, 63, 0 } } },
{ { { 58, 0, 1 }, { 56, 62, 1 } } },
{ { { 58, 0, 0 }, { 56, 62, 0 } } },
{ { { 58, 0, 1 }, { 56, 63, 0 } } },
{ { { 58, 0, 2 }, { 57, 62, 0 } } },
{ { { 59, 0, 1 }, { 57, 63, 1 } } },
{ { { 59, 0, 0 }, { 57, 63, 0 } } },
{ { { 59, 0, 1 }, { 58, 62, 0 } } },
{ { { 59, 0, 2 }, { 58, 63, 0 } } },
{ { { 60, 0, 1 }, { 59, 62, 1 } } },
{ { { 60, 0, 0 }, { 59, 62, 0 } } },
{ { { 60, 0, 1 }, { 59, 63, 0 } } },
{ { { 60, 0, 2 }, { 60, 62, 0 } } },
{ { { 61, 0, 1 }, { 60, 63, 1 } } },
{ { { 61, 0, 0 }, { 60, 63, 0 } } },
{ { { 61, 0, 1 }, { 61, 62, 0 } } },
{ { { 61, 0, 2 }, { 61, 63, 0 } } },
{ { { 62, 0, 1 }, { 62, 62, 1 } } },
{ { { 62, 0, 0 }, { 62, 62, 0 } } },
{ { { 62, 0, 1 }, { 62, 63, 0 } } },
{ { { 62, 0, 2 }, { 63, 62, 0 } } },
{ { { 63, 0, 1 }, { 63, 63, 1 } } },
{ { { 63, 0, 0 }, { 63, 63, 0 } } }
};
static const DDSSingleColourLookup*
DDS_LOOKUP[] =
{
DDSLookup_5_4,
DDSLookup_6_4,
DDSLookup_5_4
};
/*
Macros
*/
#define C565_r(x) (((x) & 0xF800) >> 11)
#define C565_g(x) (((x) & 0x07E0) >> 5)
#define C565_b(x) ((x) & 0x001F)
#define C565_red(x) ( (C565_r(x) << 3 | C565_r(x) >> 2))
#define C565_green(x) ( (C565_g(x) << 2 | C565_g(x) >> 4))
#define C565_blue(x) ( (C565_b(x) << 3 | C565_b(x) >> 2))
#define DIV2(x) ((x) > 1 ? ((x) >> 1) : 1)
#define FixRange(min, max, steps) \
if (min > max) \
min = max; \
if (max - min < steps) \
max = Min(min + steps, 255); \
if (max - min < steps) \
min = Max(min - steps, 0)
#define Dot(left, right) (left.x*right.x) + (left.y*right.y) + (left.z*right.z)
#define VectorInit(vector, value) vector.x = vector.y = vector.z = vector.w \
= value
#define VectorInit3(vector, value) vector.x = vector.y = vector.z = value
#define IsBitMask(mask, r, g, b, a) (mask.r_bitmask == r && mask.g_bitmask == \
g && mask.b_bitmask == b && mask.alpha_bitmask == a)
/*
Forward declarations
*/
static MagickBooleanType
ConstructOrdering(const size_t, const DDSVector4 *, const DDSVector3,
DDSVector4 *, DDSVector4 *, unsigned char *, size_t);
static MagickBooleanType
ReadDDSInfo(Image *, DDSInfo *);
static MagickBooleanType
ReadDXT1(Image *, DDSInfo *, ExceptionInfo *);
static MagickBooleanType
ReadDXT3(Image *, DDSInfo *, ExceptionInfo *);
static MagickBooleanType
ReadDXT5(Image *, DDSInfo *, ExceptionInfo *);
static MagickBooleanType
ReadUncompressedRGB(Image *, DDSInfo *, ExceptionInfo *);
static MagickBooleanType
ReadUncompressedRGBA(Image *, DDSInfo *, ExceptionInfo *);
static void
RemapIndices(const ssize_t *, const unsigned char *, unsigned char *);
static void
SkipDXTMipmaps(Image *, DDSInfo *, int);
static void
SkipRGBMipmaps(Image *, DDSInfo *, int);
static
MagickBooleanType WriteDDSImage(const ImageInfo *, Image *);
static void
WriteDDSInfo(Image *, const size_t, const size_t, const size_t);
static void
WriteFourCC(Image *, const size_t, const MagickBooleanType,
const MagickBooleanType, ExceptionInfo *);
static void
WriteImageData(Image *, const size_t, const size_t, const MagickBooleanType,
const MagickBooleanType, ExceptionInfo *);
static void
WriteIndices(Image *, const DDSVector3, const DDSVector3, unsigned char *);
static MagickBooleanType
WriteMipmaps(Image *, const size_t, const size_t, const size_t,
const MagickBooleanType, const MagickBooleanType, ExceptionInfo *);
static void
WriteSingleColorFit(Image *, const DDSVector4 *, const ssize_t *);
static void
WriteUncompressed(Image *, ExceptionInfo *);
static inline size_t Max(size_t one, size_t two)
{
if (one > two)
return one;
return two;
}
static inline float MaxF(float one, float two)
{
if (one > two)
return one;
return two;
}
static inline size_t Min(size_t one, size_t two)
{
if (one < two)
return one;
return two;
}
static inline float MinF(float one, float two)
{
if (one < two)
return one;
return two;
}
static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right,
DDSVector4 *destination)
{
destination->x = left.x + right.x;
destination->y = left.y + right.y;
destination->z = left.z + right.z;
destination->w = left.w + right.w;
}
static inline void VectorClamp(DDSVector4 *value)
{
value->x = MinF(1.0f,MaxF(0.0f,value->x));
value->y = MinF(1.0f,MaxF(0.0f,value->y));
value->z = MinF(1.0f,MaxF(0.0f,value->z));
value->w = MinF(1.0f,MaxF(0.0f,value->w));
}
static inline void VectorClamp3(DDSVector3 *value)
{
value->x = MinF(1.0f,MaxF(0.0f,value->x));
value->y = MinF(1.0f,MaxF(0.0f,value->y));
value->z = MinF(1.0f,MaxF(0.0f,value->z));
}
static inline void VectorCopy43(const DDSVector4 source,
DDSVector3 *destination)
{
destination->x = source.x;
destination->y = source.y;
destination->z = source.z;
}
static inline void VectorCopy44(const DDSVector4 source,
DDSVector4 *destination)
{
destination->x = source.x;
destination->y = source.y;
destination->z = source.z;
destination->w = source.w;
}
static inline void VectorNegativeMultiplySubtract(const DDSVector4 a,
const DDSVector4 b, const DDSVector4 c, DDSVector4 *destination)
{
destination->x = c.x - (a.x * b.x);
destination->y = c.y - (a.y * b.y);
destination->z = c.z - (a.z * b.z);
destination->w = c.w - (a.w * b.w);
}
static inline void VectorMultiply(const DDSVector4 left,
const DDSVector4 right, DDSVector4 *destination)
{
destination->x = left.x * right.x;
destination->y = left.y * right.y;
destination->z = left.z * right.z;
destination->w = left.w * right.w;
}
static inline void VectorMultiply3(const DDSVector3 left,
const DDSVector3 right, DDSVector3 *destination)
{
destination->x = left.x * right.x;
destination->y = left.y * right.y;
destination->z = left.z * right.z;
}
static inline void VectorMultiplyAdd(const DDSVector4 a, const DDSVector4 b,
const DDSVector4 c, DDSVector4 *destination)
{
destination->x = (a.x * b.x) + c.x;
destination->y = (a.y * b.y) + c.y;
destination->z = (a.z * b.z) + c.z;
destination->w = (a.w * b.w) + c.w;
}
static inline void VectorMultiplyAdd3(const DDSVector3 a, const DDSVector3 b,
const DDSVector3 c, DDSVector3 *destination)
{
destination->x = (a.x * b.x) + c.x;
destination->y = (a.y * b.y) + c.y;
destination->z = (a.z * b.z) + c.z;
}
static inline void VectorReciprocal(const DDSVector4 value,
DDSVector4 *destination)
{
destination->x = 1.0f / value.x;
destination->y = 1.0f / value.y;
destination->z = 1.0f / value.z;
destination->w = 1.0f / value.w;
}
static inline void VectorSubtract(const DDSVector4 left,
const DDSVector4 right, DDSVector4 *destination)
{
destination->x = left.x - right.x;
destination->y = left.y - right.y;
destination->z = left.z - right.z;
destination->w = left.w - right.w;
}
static inline void VectorSubtract3(const DDSVector3 left,
const DDSVector3 right, DDSVector3 *destination)
{
destination->x = left.x - right.x;
destination->y = left.y - right.y;
destination->z = left.z - right.z;
}
static inline void VectorTruncate(DDSVector4 *value)
{
value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
value->w = value->w > 0.0f ? floor(value->w) : ceil(value->w);
}
static inline void VectorTruncate3(DDSVector3 *value)
{
value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
}
static void CalculateColors(unsigned short c0, unsigned short c1,
DDSColors *c, MagickBooleanType ignoreAlpha)
{
c->a[0] = c->a[1] = c->a[2] = c->a[3] = 0;
c->r[0] = (unsigned char) C565_red(c0);
c->g[0] = (unsigned char) C565_green(c0);
c->b[0] = (unsigned char) C565_blue(c0);
c->r[1] = (unsigned char) C565_red(c1);
c->g[1] = (unsigned char) C565_green(c1);
c->b[1] = (unsigned char) C565_blue(c1);
if (ignoreAlpha != MagickFalse || c0 > c1)
{
c->r[2] = (unsigned char) ((2 * c->r[0] + c->r[1]) / 3);
c->g[2] = (unsigned char) ((2 * c->g[0] + c->g[1]) / 3);
c->b[2] = (unsigned char) ((2 * c->b[0] + c->b[1]) / 3);
c->r[3] = (unsigned char) ((c->r[0] + 2 * c->r[1]) / 3);
c->g[3] = (unsigned char) ((c->g[0] + 2 * c->g[1]) / 3);
c->b[3] = (unsigned char) ((c->b[0] + 2 * c->b[1]) / 3);
}
else
{
c->r[2] = (unsigned char) ((c->r[0] + c->r[1]) / 2);
c->g[2] = (unsigned char) ((c->g[0] + c->g[1]) / 2);
c->b[2] = (unsigned char) ((c->b[0] + c->b[1]) / 2);
c->r[3] = c->g[3] = c->b[3] = 0;
c->a[3] = 255;
}
}
static size_t CompressAlpha(const size_t min, const size_t max,
const size_t steps, const ssize_t *alphas, unsigned char* indices)
{
unsigned char
codes[8];
register ssize_t
i;
size_t
error,
index,
j,
least,
value;
codes[0] = (unsigned char) min;
codes[1] = (unsigned char) max;
codes[6] = 0;
codes[7] = 255;
for (i=1; i < (ssize_t) steps; i++)
codes[i+1] = (unsigned char) (((steps-i)*min + i*max) / steps);
error = 0;
for (i=0; i<16; i++)
{
if (alphas[i] == -1)
{
indices[i] = 0;
continue;
}
value = alphas[i];
least = SIZE_MAX;
index = 0;
for (j=0; j<8; j++)
{
size_t
dist;
dist = value - (size_t)codes[j];
dist *= dist;
if (dist < least)
{
least = dist;
index = j;
}
}
indices[i] = (unsigned char)index;
error += least;
}
return error;
}
static void CompressClusterFit(const size_t count,
const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle,
const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end,
unsigned char *indices)
{
DDSVector3
axis;
DDSVector4
grid,
gridrcp,
half,
onethird_onethird2,
part0,
part1,
part2,
part3,
pointsWeights[16],
two,
twonineths,
twothirds_twothirds2,
xSumwSum;
float
bestError = 1e+37f;
size_t
bestIteration = 0,
besti = 0,
bestj = 0,
bestk = 0,
iterationIndex,
i,
j,
k,
kmin;
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;;)
{
VectorInit(part0,0.0f);
for (i=0; i < count; i++)
{
VectorInit(part1,0.0f);
for (j=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;
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)
{
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++;
}
VectorAdd(pointsWeights[i],part0,&part0);
}
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 < besti; i++)
unordered[o[i]] = 0;
for (i=besti; i < bestj; i++)
unordered[o[i]] = 2;
for (i=bestj; i < bestk; i++)
unordered[o[i]] = 3;
for (i=bestk; i < count; i++)
unordered[o[i]] = 1;
RemapIndices(map,unordered,indices);
}
static void CompressRangeFit(const size_t count,
const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle,
const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end,
unsigned char *indices)
{
float
d,
bestDist,
max,
min,
val;
DDSVector3
codes[4],
grid,
gridrcp,
half,
dist;
register ssize_t
i;
size_t
bestj,
j;
unsigned char
closest[16];
VectorInit3(half,0.5f);
grid.x = 31.0f;
grid.y = 63.0f;
grid.z = 31.0f;
gridrcp.x = 1.0f/31.0f;
gridrcp.y = 1.0f/63.0f;
gridrcp.z = 1.0f/31.0f;
if (count > 0)
{
VectorCopy43(points[0],start);
VectorCopy43(points[0],end);
min = max = Dot(points[0],principle);
for (i=1; i < (ssize_t) count; i++)
{
val = Dot(points[i],principle);
if (val < min)
{
VectorCopy43(points[i],start);
min = val;
}
else if (val > max)
{
VectorCopy43(points[i],end);
max = val;
}
}
}
VectorClamp3(start);
VectorMultiplyAdd3(grid,*start,half,start);
VectorTruncate3(start);
VectorMultiply3(*start,gridrcp,start);
VectorClamp3(end);
VectorMultiplyAdd3(grid,*end,half,end);
VectorTruncate3(end);
VectorMultiply3(*end,gridrcp,end);
codes[0] = *start;
codes[1] = *end;
codes[2].x = (start->x * (2.0f/3.0f)) + (end->x * (1.0f/3.0f));
codes[2].y = (start->y * (2.0f/3.0f)) + (end->y * (1.0f/3.0f));
codes[2].z = (start->z * (2.0f/3.0f)) + (end->z * (1.0f/3.0f));
codes[3].x = (start->x * (1.0f/3.0f)) + (end->x * (2.0f/3.0f));
codes[3].y = (start->y * (1.0f/3.0f)) + (end->y * (2.0f/3.0f));
codes[3].z = (start->z * (1.0f/3.0f)) + (end->z * (2.0f/3.0f));
for (i=0; i < (ssize_t) count; i++)
{
bestDist = 1e+37f;
bestj = 0;
for (j=0; j < 4; j++)
{
dist.x = (points[i].x - codes[j].x) * metric.x;
dist.y = (points[i].y - codes[j].y) * metric.y;
dist.z = (points[i].z - codes[j].z) * metric.z;
d = Dot(dist,dist);
if (d < bestDist)
{
bestDist = d;
bestj = j;
}
}
closest[i] = (unsigned char) bestj;
}
RemapIndices(map, closest, indices);
}
static void ComputeEndPoints(const DDSSingleColourLookup *lookup[],
const unsigned char *color, DDSVector3 *start, DDSVector3 *end,
unsigned char *index)
{
register ssize_t
i;
size_t
c,
maxError = SIZE_MAX;
for (i=0; i < 2; i++)
{
const DDSSourceBlock*
sources[3];
size_t
error = 0;
for (c=0; c < 3; c++)
{
sources[c] = &lookup[c][color[c]].sources[i];
error += ((size_t) sources[c]->error) * ((size_t) sources[c]->error);
}
if (error > maxError)
continue;
start->x = (float) sources[0]->start / 31.0f;
start->y = (float) sources[1]->start / 63.0f;
start->z = (float) sources[2]->start / 31.0f;
end->x = (float) sources[0]->end / 31.0f;
end->y = (float) sources[1]->end / 63.0f;
end->z = (float) sources[2]->end / 31.0f;
*index = (unsigned char) (2*i);
maxError = error;
}
}
static void ComputePrincipleComponent(const float *covariance,
DDSVector3 *principle)
{
DDSVector4
row0,
row1,
row2,
v;
register ssize_t
i;
row0.x = covariance[0];
row0.y = covariance[1];
row0.z = covariance[2];
row0.w = 0.0f;
row1.x = covariance[1];
row1.y = covariance[3];
row1.z = covariance[4];
row1.w = 0.0f;
row2.x = covariance[2];
row2.y = covariance[4];
row2.z = covariance[5];
row2.w = 0.0f;
VectorInit(v,1.0f);
for (i=0; i < 8; i++)
{
DDSVector4
w;
float
a;
w.x = row0.x * v.x;
w.y = row0.y * v.x;
w.z = row0.z * v.x;
w.w = row0.w * v.x;
w.x = (row1.x * v.y) + w.x;
w.y = (row1.y * v.y) + w.y;
w.z = (row1.z * v.y) + w.z;
w.w = (row1.w * v.y) + w.w;
w.x = (row2.x * v.z) + w.x;
w.y = (row2.y * v.z) + w.y;
w.z = (row2.z * v.z) + w.z;
w.w = (row2.w * v.z) + w.w;
a = 1.0f / MaxF(w.x,MaxF(w.y,w.z));
v.x = w.x * a;
v.y = w.y * a;
v.z = w.z * a;
v.w = w.w * a;
}
VectorCopy43(v,principle);
}
static void ComputeWeightedCovariance(const size_t count,
const DDSVector4 *points, float *covariance)
{
DDSVector3
centroid;
float
total;
size_t
i;
total = 0.0f;
VectorInit3(centroid,0.0f);
for (i=0; i < count; i++)
{
total += points[i].w;
centroid.x += (points[i].x * points[i].w);
centroid.y += (points[i].y * points[i].w);
centroid.z += (points[i].z * points[i].w);
}
if( total > 1.192092896e-07F)
{
centroid.x /= total;
centroid.y /= total;
centroid.z /= total;
}
for (i=0; i < 6; i++)
covariance[i] = 0.0f;
for (i = 0; i < count; i++)
{
DDSVector3
a,
b;
a.x = points[i].x - centroid.x;
a.y = points[i].y - centroid.y;
a.z = points[i].z - centroid.z;
b.x = points[i].w * a.x;
b.y = points[i].w * a.y;
b.z = points[i].w * a.z;
covariance[0] += a.x*b.x;
covariance[1] += a.x*b.y;
covariance[2] += a.x*b.z;
covariance[3] += a.y*b.y;
covariance[4] += a.y*b.z;
covariance[5] += a.z*b.z;
}
}
static MagickBooleanType ConstructOrdering(const size_t count,
const DDSVector4 *points, const DDSVector3 axis, DDSVector4 *pointsWeights,
DDSVector4 *xSumwSum, unsigned char *order, size_t iteration)
{
float
dps[16],
f;
register ssize_t
i;
size_t
j;
unsigned char
c,
*o,
*p;
o = order + (16*iteration);
for (i=0; i < (ssize_t) count; i++)
{
dps[i] = Dot(points[i],axis);
o[i] = (unsigned char)i;
}
for (i=0; i < (ssize_t) count; i++)
{
for (j=i; j > 0 && dps[j] < dps[j - 1]; j--)
{
f = dps[j];
dps[j] = dps[j - 1];
dps[j - 1] = f;
c = o[j];
o[j] = o[j - 1];
o[j - 1] = c;
}
}
for (i=0; i < (ssize_t) iteration; i++)
{
MagickBooleanType
same;
p = order + (16*i);
same = MagickTrue;
for (j=0; j < count; j++)
{
if (o[j] != p[j])
{
same = MagickFalse;
break;
}
}
if (same != MagickFalse)
return MagickFalse;
}
xSumwSum->x = 0;
xSumwSum->y = 0;
xSumwSum->z = 0;
xSumwSum->w = 0;
for (i=0; i < (ssize_t) count; i++)
{
DDSVector4
v;
j = (size_t) o[i];
v.x = points[j].w * points[j].x;
v.y = points[j].w * points[j].y;
v.z = points[j].w * points[j].z;
v.w = points[j].w * 1.0f;
VectorCopy44(v,&pointsWeights[i]);
VectorAdd(*xSumwSum,v,xSumwSum);
}
return MagickTrue;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s D D S %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsDDS() returns MagickTrue if the image format type, identified by the
% magick string, is DDS.
%
% The format of the IsDDS method is:
%
% MagickBooleanType IsDDS(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsDDS(const unsigned char *magick, const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((char *) magick,"DDS ", 4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadDDSImage() reads a DirectDraw Surface image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadDDSImage method is:
%
% Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: The image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status,
cubemap = MagickFalse,
volume = MagickFalse,
matte;
CompressionType
compression;
DDSInfo
dds_info;
DDSDecoder
*decoder;
size_t
n,
num_images;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
if (ReadDDSInfo(image, &dds_info) != MagickTrue) {
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)
cubemap = MagickTrue;
if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)
volume = MagickTrue;
(void) SeekBlob(image, 128, SEEK_SET);
/*
Determine pixel format
*/
if (dds_info.pixelformat.flags & DDPF_RGB)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
matte = MagickTrue;
decoder = ReadUncompressedRGBA;
}
else
{
matte = MagickTrue;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_LUMINANCE)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
/* Not sure how to handle this */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
else
{
matte = MagickFalse;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_FOURCC)
{
switch (dds_info.pixelformat.fourcc)
{
case FOURCC_DXT1:
{
matte = MagickFalse;
compression = DXT1Compression;
decoder = ReadDXT1;
break;
}
case FOURCC_DXT3:
{
matte = MagickTrue;
compression = DXT3Compression;
decoder = ReadDXT3;
break;
}
case FOURCC_DXT5:
{
matte = MagickTrue;
compression = DXT5Compression;
decoder = ReadDXT5;
break;
}
default:
{
/* Unknown FOURCC */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
}
}
else
{
/* Neither compressed nor uncompressed... thus unsupported */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
num_images = 1;
if (cubemap)
{
/*
Determine number of faces defined in the cubemap
*/
num_images = 0;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++;
}
if (volume)
num_images = dds_info.depth;
for (n = 0; n < num_images; n++)
{
if (n != 0)
{
/* Start a new image */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
image->matte = matte;
image->compression = compression;
image->columns = dds_info.width;
image->rows = dds_info.height;
image->storage_class = DirectClass;
image->endian = LSBEndian;
image->depth = 8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if ((decoder)(image, &dds_info, exception) != MagickTrue)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
static MagickBooleanType ReadDDSInfo(Image *image, DDSInfo *dds_info)
{
size_t
hdr_size,
required;
/* Seek to start of header */
(void) SeekBlob(image, 4, SEEK_SET);
/* Check header field */
hdr_size = ReadBlobLSBLong(image);
if (hdr_size != 124)
return MagickFalse;
/* Fill in DDS info struct */
dds_info->flags = ReadBlobLSBLong(image);
/* Check required flags */
required=(size_t) (DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT);
if ((dds_info->flags & required) != required)
return MagickFalse;
dds_info->height = ReadBlobLSBLong(image);
dds_info->width = ReadBlobLSBLong(image);
dds_info->pitchOrLinearSize = ReadBlobLSBLong(image);
dds_info->depth = ReadBlobLSBLong(image);
dds_info->mipmapcount = ReadBlobLSBLong(image);
(void) SeekBlob(image, 44, SEEK_CUR); /* reserved region of 11 DWORDs */
/* Read pixel format structure */
hdr_size = ReadBlobLSBLong(image);
if (hdr_size != 32)
return MagickFalse;
dds_info->pixelformat.flags = ReadBlobLSBLong(image);
dds_info->pixelformat.fourcc = ReadBlobLSBLong(image);
dds_info->pixelformat.rgb_bitcount = ReadBlobLSBLong(image);
dds_info->pixelformat.r_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.g_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.b_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.alpha_bitmask = ReadBlobLSBLong(image);
dds_info->ddscaps1 = ReadBlobLSBLong(image);
dds_info->ddscaps2 = ReadBlobLSBLong(image);
(void) SeekBlob(image, 12, SEEK_CUR); /* 3 reserved DWORDs */
return MagickTrue;
}
static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
PixelPacket
*q;
register ssize_t
i,
x;
size_t
bits;
ssize_t
j,
y;
unsigned char
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),
Min(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickFalse);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (unsigned char) ((bits >> ((j*4+i)*2)) & 0x3);
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
SetPixelOpacity(q,ScaleCharToQuantum(colors.a[code]));
if (colors.a[code] && image->matte == MagickFalse)
/* Correct matte */
image->matte = MagickTrue;
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
SkipDXTMipmaps(image, dds_info, 8);
return MagickTrue;
}
static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
alpha;
size_t
a0,
a1,
bits,
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),
Min(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = ReadBlobLSBLong(image);
a1 = ReadBlobLSBLong(image);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/*
Extract alpha value: multiply 0..15 by 17 to get range 0..255
*/
if (j < 2)
alpha = 17U * (unsigned char) ((a0 >> (4*(4*j+i))) & 0xf);
else
alpha = 17U * (unsigned char) ((a1 >> (4*(4*(j-2)+i))) & 0xf);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
SkipDXTMipmaps(image, dds_info, 16);
return MagickTrue;
}
static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
MagickSizeType
alpha_bits;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
a0,
a1;
size_t
alpha,
bits,
code,
alpha_code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),
Min(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = (unsigned char) ReadBlobByte(image);
a1 = (unsigned char) ReadBlobByte(image);
alpha_bits = (MagickSizeType)ReadBlobLSBLong(image);
alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/* Extract alpha value */
alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7;
if (alpha_code == 0)
alpha = a0;
else if (alpha_code == 1)
alpha = a1;
else if (a0 > a1)
alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7;
else if (alpha_code == 6)
alpha = 0;
else if (alpha_code == 7)
alpha = 255;
else
alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
SkipDXTMipmaps(image, dds_info, 16);
return MagickTrue;
}
static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
PixelPacket
*q;
ssize_t
x, y;
unsigned short
color;
if (dds_info->pixelformat.rgb_bitcount == 8)
(void) SetImageType(image,GrayscaleType);
else if (dds_info->pixelformat.rgb_bitcount == 16 && !IsBitMask(
dds_info->pixelformat,0xf800,0x07e0,0x001f,0x0000))
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 8)
SetPixelGray(q,ScaleCharToQuantum(ReadBlobByte(image)));
else if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
(((color >> 11)/31.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 5) >> 10)/63.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)));
}
else
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
if (dds_info->pixelformat.rgb_bitcount == 32)
(void) ReadBlobByte(image);
}
SetPixelAlpha(q,QuantumRange);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
SkipRGBMipmaps(image, dds_info, 3);
return MagickTrue;
}
static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
PixelPacket
*q;
ssize_t
alphaBits,
x,
y;
unsigned short
color;
alphaBits=0;
if (dds_info->pixelformat.rgb_bitcount == 16)
{
if (IsBitMask(dds_info->pixelformat,0x7c00,0x03e0,0x001f,0x8000))
alphaBits=1;
else if (IsBitMask(dds_info->pixelformat,0x00ff,0x00ff,0x00ff,0xff00))
{
alphaBits=2;
(void) SetImageType(image,GrayscaleMatteType);
}
else if (IsBitMask(dds_info->pixelformat,0x0f00,0x00f0,0x000f,0xf000))
alphaBits=4;
else
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
}
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
if (alphaBits == 1)
{
SetPixelAlpha(q,(color & (1 << 15)) ? QuantumRange : 0);
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 1) >> 11)/31.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 6) >> 11)/31.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)));
}
else if (alphaBits == 2)
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
(color >> 8)));
SetPixelGray(q,ScaleCharToQuantum((unsigned char)color));
}
else
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
(((color >> 12)/15.0)*255)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 4) >> 12)/15.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 8) >> 12)/15.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 12) >> 12)/15.0)*255)));
}
}
else
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
SkipRGBMipmaps(image, dds_info, 4);
return MagickTrue;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterDDSImage() adds attributes for the DDS image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterDDSImage method is:
%
% RegisterDDSImage(void)
%
*/
ModuleExport size_t RegisterDDSImage(void)
{
MagickInfo
*entry;
entry = SetMagickInfo("DDS");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
entry = SetMagickInfo("DXT1");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
entry = SetMagickInfo("DXT5");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
static void RemapIndices(const ssize_t *map, const unsigned char *source,
unsigned char *target)
{
register ssize_t
i;
for (i = 0; i < 16; i++)
{
if (map[i] == -1)
target[i] = 3;
else
target[i] = source[map[i]];
}
}
/*
Skip the mipmap images for compressed (DXTn) dds files
*/
static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size)
{
register ssize_t
i;
MagickOffsetType
offset;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
}
/*
Skip the mipmap images for uncompressed (RGB or RGBA) dds files
*/
static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterDDSImage() removes format registrations made by the
% DDS module from the list of supported formats.
%
% The format of the UnregisterDDSImage method is:
%
% UnregisterDDSImage(void)
%
*/
ModuleExport void UnregisterDDSImage(void)
{
(void) UnregisterMagickInfo("DDS");
(void) UnregisterMagickInfo("DXT1");
(void) UnregisterMagickInfo("DXT5");
}
static void WriteAlphas(Image *image, const ssize_t* alphas, size_t min5,
size_t max5, size_t min7, size_t max7)
{
register ssize_t
i;
size_t
err5,
err7,
j;
unsigned char
indices5[16],
indices7[16];
FixRange(min5,max5,5);
err5 = CompressAlpha(min5,max5,5,alphas,indices5);
FixRange(min7,max7,7);
err7 = CompressAlpha(min7,max7,7,alphas,indices7);
if (err7 < err5)
{
for (i=0; i < 16; i++)
{
unsigned char
index;
index = indices7[i];
if( index == 0 )
indices5[i] = 1;
else if (index == 1)
indices5[i] = 0;
else
indices5[i] = 9 - index;
}
min5 = max7;
max5 = min7;
}
(void) WriteBlobByte(image,(unsigned char) min5);
(void) WriteBlobByte(image,(unsigned char) max5);
for(i=0; i < 2; i++)
{
size_t
value = 0;
for (j=0; j < 8; j++)
{
size_t index = (size_t) indices5[j + i*8];
value |= ( index << 3*j );
}
for (j=0; j < 3; j++)
{
size_t byte = (value >> 8*j) & 0xff;
(void) WriteBlobByte(image,(unsigned char) byte);
}
}
}
static void WriteCompressed(Image *image, const size_t count,
DDSVector4* points, const ssize_t* map, const MagickBooleanType clusterFit)
{
float
covariance[16];
DDSVector3
end,
principle,
start;
DDSVector4
metric;
unsigned char
indices[16];
VectorInit(metric,1.0f);
VectorInit3(start,0.0f);
VectorInit3(end,0.0f);
ComputeWeightedCovariance(count,points,covariance);
ComputePrincipleComponent(covariance,&principle);
if (clusterFit == MagickFalse || count == 0)
CompressRangeFit(count,points,map,principle,metric,&start,&end,indices);
else
CompressClusterFit(count,points,map,principle,metric,&start,&end,indices);
WriteIndices(image,start,end,indices);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteDDSImage() writes a DirectDraw Surface image file in the DXT5 format.
%
% The format of the WriteBMPImage method is:
%
% MagickBooleanType WriteDDSImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteDDSImage(const ImageInfo *image_info,
Image *image)
{
const char
*option;
size_t
compression,
columns,
maxMipmaps,
mipmaps,
pixelFormat,
rows;
MagickBooleanType
clusterFit,
status,
weightByAlpha;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
pixelFormat=DDPF_FOURCC;
compression=FOURCC_DXT5;
if (!image->matte)
compression=FOURCC_DXT1;
if (LocaleCompare(image_info->magick,"dxt1") == 0)
compression=FOURCC_DXT1;
option=GetImageOption(image_info,"dds:compression");
if (option != (char *) NULL)
{
if (LocaleCompare(option,"dxt1") == 0)
compression=FOURCC_DXT1;
if (LocaleCompare(option,"none") == 0)
pixelFormat=DDPF_RGB;
}
clusterFit=MagickFalse;
weightByAlpha=MagickFalse;
if (pixelFormat == DDPF_FOURCC)
{
option=GetImageOption(image_info,"dds:cluster-fit");
if (option != (char *) NULL && LocaleCompare(option,"true") == 0)
{
clusterFit=MagickTrue;
if (compression != FOURCC_DXT1)
{
option=GetImageOption(image_info,"dds:weight-by-alpha");
if (option != (char *) NULL && LocaleCompare(option,"true") == 0)
weightByAlpha=MagickTrue;
}
}
}
maxMipmaps=SIZE_MAX;
mipmaps=0;
if ((image->columns & (image->columns - 1)) == 0 &&
(image->rows & (image->rows - 1)) == 0)
{
option=GetImageOption(image_info,"dds:mipmaps");
if (option != (char *) NULL)
maxMipmaps=StringToUnsignedLong(option);
if (maxMipmaps != 0)
{
columns=image->columns;
rows=image->rows;
while (columns != 1 && rows != 1 && mipmaps != maxMipmaps)
{
columns=DIV2(columns);
rows=DIV2(rows);
mipmaps++;
}
}
}
WriteDDSInfo(image,pixelFormat,compression,mipmaps);
WriteImageData(image,pixelFormat,compression,clusterFit,weightByAlpha,
&image->exception);
if (mipmaps > 0 && WriteMipmaps(image,pixelFormat,compression,mipmaps,
clusterFit,weightByAlpha,&image->exception) == MagickFalse)
return(MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
static void WriteDDSInfo(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps)
{
char
software[MaxTextExtent];
register ssize_t
i;
unsigned int
format,
caps,
flags;
flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT |
DDSD_PIXELFORMAT | DDSD_LINEARSIZE);
caps=(unsigned int) DDSCAPS_TEXTURE;
format=(unsigned int) pixelFormat;
if (mipmaps > 0)
{
flags=flags | (unsigned int) DDSD_MIPMAPCOUNT;
caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX);
}
if (format != DDPF_FOURCC && image->matte)
format=format | DDPF_ALPHAPIXELS;
(void) WriteBlob(image,4,(unsigned char *) "DDS ");
(void) WriteBlobLSBLong(image,124);
(void) WriteBlobLSBLong(image,flags);
(void) WriteBlobLSBLong(image,image->rows);
(void) WriteBlobLSBLong(image,image->columns);
if (compression == FOURCC_DXT1)
(void) WriteBlobLSBLong(image,
(unsigned int) (Max(1,(image->columns+3)/4) * 8));
else
(void) WriteBlobLSBLong(image,
(unsigned int) (Max(1,(image->columns+3)/4) * 16));
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1);
(void) ResetMagickMemory(software,0,sizeof(software));
(void) strcpy(software,"IMAGEMAGICK");
(void) WriteBlob(image,44,(unsigned char *) software);
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,format);
if (pixelFormat == DDPF_FOURCC)
{
(void) WriteBlobLSBLong(image,(unsigned int) compression);
for(i=0;i < 5;i++) // bitcount / masks
(void) WriteBlobLSBLong(image,0x00);
}
else
{
(void) WriteBlobLSBLong(image,0x00);
if (image->matte)
{
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,0xff0000);
(void) WriteBlobLSBLong(image,0xff00);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0xff000000);
}
else
{
(void) WriteBlobLSBLong(image,24);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,0x00);
}
}
(void) WriteBlobLSBLong(image,caps);
for(i=0;i < 4;i++) // ddscaps2 + reserved region
(void) WriteBlobLSBLong(image,0x00);
}
static void WriteFourCC(Image *image, const size_t compression,
const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,
ExceptionInfo *exception)
{
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
i,
y,
bx,
by;
for (y=0; y < (ssize_t) image->rows; y+=4)
{
for (x=0; x < (ssize_t) image->columns; x+=4)
{
MagickBooleanType
match;
DDSVector4
point,
points[16];
size_t
count = 0,
max5 = 0,
max7 = 0,
min5 = 255,
min7 = 255,
columns = 4,
rows = 4;
ssize_t
alphas[16],
map[16];
unsigned char
alpha;
if (x + columns >= image->columns)
columns = image->columns - x;
if (y + rows >= image->rows)
rows = image->rows - y;
p=GetVirtualPixels(image,x,y,columns,rows,exception);
if (p == (const PixelPacket *) NULL)
break;
for (i=0; i<16; i++)
{
map[i] = -1;
alphas[i] = -1;
}
for (by=0; by < (ssize_t) rows; by++)
{
for (bx=0; bx < (ssize_t) columns; bx++)
{
if (compression == FOURCC_DXT5)
alpha = ScaleQuantumToChar(GetPixelAlpha(p));
else
alpha = 255;
alphas[4*by + bx] = (size_t)alpha;
point.x = (float)ScaleQuantumToChar(GetPixelRed(p)) / 255.0f;
point.y = (float)ScaleQuantumToChar(GetPixelGreen(p)) / 255.0f;
point.z = (float)ScaleQuantumToChar(GetPixelBlue(p)) / 255.0f;
point.w = weightByAlpha ? (float)(alpha + 1) / 256.0f : 1.0f;
p++;
match = MagickFalse;
for (i=0; i < (ssize_t) count; i++)
{
if ((points[i].x == point.x) &&
(points[i].y == point.y) &&
(points[i].z == point.z) &&
(alpha >= 128 || compression == FOURCC_DXT5))
{
points[i].w += point.w;
map[4*by + bx] = i;
match = MagickTrue;
break;
}
}
if (match != MagickFalse)
continue;
points[count].x = point.x;
points[count].y = point.y;
points[count].z = point.z;
points[count].w = point.w;
map[4*by + bx] = count;
count++;
if (compression == FOURCC_DXT5)
{
if (alpha < min7)
min7 = alpha;
if (alpha > max7)
max7 = alpha;
if (alpha != 0 && alpha < min5)
min5 = alpha;
if (alpha != 255 && alpha > max5)
max5 = alpha;
}
}
}
for (i=0; i < (ssize_t) count; i++)
points[i].w = sqrt(points[i].w);
if (compression == FOURCC_DXT5)
WriteAlphas(image,alphas,min5,max5,min7,max7);
if (count == 1)
WriteSingleColorFit(image,points,map);
else
WriteCompressed(image,count,points,map,clusterFit);
}
}
}
static void WriteImageData(Image *image, const size_t pixelFormat,
const size_t compression, const MagickBooleanType clusterFit,
const MagickBooleanType weightByAlpha, ExceptionInfo *exception)
{
if (pixelFormat == DDPF_FOURCC)
WriteFourCC(image,compression,clusterFit,weightByAlpha,exception);
else
WriteUncompressed(image,exception);
}
static inline size_t ClampToLimit(const float value,
const size_t limit)
{
size_t
result = (int) (value + 0.5f);
if (result < 0.0f)
return(0);
if (result > limit)
return(limit);
return result;
}
static inline size_t ColorTo565(const DDSVector3 point)
{
size_t r = ClampToLimit(31.0f*point.x,31);
size_t g = ClampToLimit(63.0f*point.y,63);
size_t b = ClampToLimit(31.0f*point.z,31);
return (r << 11) | (g << 5) | b;
}
static void WriteIndices(Image *image, const DDSVector3 start,
const DDSVector3 end, unsigned char* indices)
{
register ssize_t
i;
size_t
a,
b;
unsigned char
remapped[16];
const unsigned char
*ind;
a = ColorTo565(start);
b = ColorTo565(end);
for (i=0; i<16; i++)
{
if( a < b )
remapped[i] = (indices[i] ^ 0x1) & 0x3;
else if( a == b )
remapped[i] = 0;
else
remapped[i] = indices[i];
}
if( a < b )
Swap(a,b);
(void) WriteBlobByte(image,(unsigned char) (a & 0xff));
(void) WriteBlobByte(image,(unsigned char) (a >> 8));
(void) WriteBlobByte(image,(unsigned char) (b & 0xff));
(void) WriteBlobByte(image,(unsigned char) (b >> 8));
for (i=0; i<4; i++)
{
ind = remapped + 4*i;
(void) WriteBlobByte(image,ind[0] | (ind[1] << 2) | (ind[2] << 4) |
(ind[3] << 6));
}
}
static MagickBooleanType WriteMipmaps(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps,
const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,
ExceptionInfo *exception)
{
Image*
resize_image;
register ssize_t
i;
size_t
columns,
rows;
columns = image->columns;
rows = image->rows;
for (i=0; i< (ssize_t) mipmaps; i++)
{
resize_image = ResizeImage(image,columns/2,rows/2,TriangleFilter,1.0,
exception);
if (resize_image == (Image *) NULL)
return(MagickFalse);
DestroyBlob(resize_image);
resize_image->blob=ReferenceBlob(image->blob);
WriteImageData(resize_image,pixelFormat,compression,weightByAlpha,
clusterFit,exception);
resize_image=DestroyImage(resize_image);
columns = DIV2(columns);
rows = DIV2(rows);
}
return(MagickTrue);
}
static void WriteSingleColorFit(Image *image, const DDSVector4* points,
const ssize_t* map)
{
DDSVector3
start,
end;
register ssize_t
i;
unsigned char
color[3],
index,
indexes[16],
indices[16];
color[0] = (unsigned char) ClampToLimit(255.0f*points->x,255);
color[1] = (unsigned char) ClampToLimit(255.0f*points->y,255);
color[2] = (unsigned char) ClampToLimit(255.0f*points->z,255);
index=0;
ComputeEndPoints(DDS_LOOKUP,color,&start,&end,&index);
for (i=0; i< 16; i++)
indexes[i]=index;
RemapIndices(map,indexes,indices);
WriteIndices(image,start,end,indices);
}
static void WriteUncompressed(Image *image, ExceptionInfo *exception)
{
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
y;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelGreen(p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(p)));
if (image->matte)
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelAlpha(p)));
p++;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_11 |
crossvul-cpp_data_bad_3199_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W W EEEEE BBBB PPPP %
% W W E B B P P %
% W W W EEE BBBB PPPP %
% WW WW E B B P %
% W W EEEEE BBBB P %
% %
% %
% Read/Write WebP Image Format %
% %
% Software Design %
% Cristy %
% March 2011 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/client.h"
#include "magick/colorspace-private.h"
#include "magick/display.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/monitor.h"
#include "magick/monitor-private.h"
#include "magick/memory_.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
#include "magick/utility.h"
#include "magick/xwindow.h"
#include "magick/xwindow-private.h"
#if defined(MAGICKCORE_WEBP_DELEGATE)
#include <webp/decode.h>
#include <webp/encode.h>
#endif
/*
Forward declarations.
*/
#if defined(MAGICKCORE_WEBP_DELEGATE)
static MagickBooleanType
WriteWEBPImage(const ImageInfo *,Image *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s W E B P %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsWEBP() returns MagickTrue if the image format type, identified by the
% magick string, is WebP.
%
% The format of the IsWEBP method is:
%
% MagickBooleanType IsWEBP(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 IsWEBP(const unsigned char *magick,const size_t length)
{
if (length < 12)
return(MagickFalse);
if (LocaleNCompare((const char *) magick+8,"WEBP",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
#if defined(MAGICKCORE_WEBP_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d W E B P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadWEBPImage() reads an image in the WebP image format.
%
% The format of the ReadWEBPImage method is:
%
% Image *ReadWEBPImage(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 inline uint32_t ReadWebPLSBWord(
const unsigned char *magick_restrict data)
{
register const unsigned char
*p;
register uint32_t
value;
p=data;
value=(uint32_t) (*p++);
value|=((uint32_t) (*p++)) << 8;
value|=((uint32_t) (*p++)) << 16;
value|=((uint32_t) (*p++)) << 24;
return(value);
}
static MagickBooleanType IsWEBPImageLossless(const unsigned char *stream,
const size_t length)
{
#define VP8_CHUNK_INDEX 15
#define LOSSLESS_FLAG 'L'
#define EXTENDED_HEADER 'X'
#define VP8_CHUNK_HEADER "VP8"
#define VP8_CHUNK_HEADER_SIZE 3
#define RIFF_HEADER_SIZE 12
#define VP8X_CHUNK_SIZE 10
#define TAG_SIZE 4
#define CHUNK_SIZE_BYTES 4
#define CHUNK_HEADER_SIZE 8
#define MAX_CHUNK_PAYLOAD (~0U-CHUNK_HEADER_SIZE-1)
ssize_t
offset;
/*
Read simple header.
*/
if (stream[VP8_CHUNK_INDEX] != EXTENDED_HEADER)
return(stream[VP8_CHUNK_INDEX] == LOSSLESS_FLAG ? MagickTrue : MagickFalse);
/*
Read extended header.
*/
offset=RIFF_HEADER_SIZE+TAG_SIZE+CHUNK_SIZE_BYTES+VP8X_CHUNK_SIZE;
while (offset <= (ssize_t) length)
{
uint32_t
chunk_size,
chunk_size_pad;
chunk_size=ReadWebPLSBWord(stream+offset+TAG_SIZE);
if (chunk_size > MAX_CHUNK_PAYLOAD)
break;
chunk_size_pad=(CHUNK_HEADER_SIZE+chunk_size+1) & ~1;
if (memcmp(stream+offset,VP8_CHUNK_HEADER,VP8_CHUNK_HEADER_SIZE) == 0)
return(*(stream+offset+VP8_CHUNK_HEADER_SIZE) == LOSSLESS_FLAG ?
MagickTrue : MagickFalse);
offset+=chunk_size_pad;
}
return(MagickFalse);
}
static Image *ReadWEBPImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
int
webp_status;
MagickBooleanType
status;
register unsigned char
*p;
size_t
length;
ssize_t
count,
y;
unsigned char
header[12],
*stream;
WebPDecoderConfig
configure;
WebPDecBuffer
*magick_restrict webp_image = &configure.output;
WebPBitstreamFeatures
*magick_restrict features = &configure.input;
/*
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);
}
if (WebPInitDecoderConfig(&configure) == 0)
ThrowReaderException(ResourceLimitError,"UnableToDecodeImageFile");
webp_image->colorspace=MODE_RGBA;
count=ReadBlob(image,12,header);
if (count != 12)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
status=IsWEBP(header,count);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"CorruptImage");
length=(size_t) (ReadWebPLSBWord(header+4)+8);
if (length < 12)
ThrowReaderException(CorruptImageError,"CorruptImage");
stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream));
if (stream == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) memcpy(stream,header,12);
count=ReadBlob(image,length-12,stream+12);
if (count != (ssize_t) (length-12))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
webp_status=WebPGetFeatures(stream,length,features);
if (webp_status == VP8_STATUS_OK)
{
image->columns=(size_t) features->width;
image->rows=(size_t) features->height;
image->depth=8;
image->matte=features->has_alpha != 0 ? MagickTrue : MagickFalse;
if (IsWEBPImageLossless(stream,length) != MagickFalse)
image->quality=100;
if (image_info->ping != MagickFalse)
{
stream=(unsigned char*) RelinquishMagickMemory(stream);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
webp_status=WebPDecode(stream,length,&configure);
}
if (webp_status != VP8_STATUS_OK)
{
stream=(unsigned char*) RelinquishMagickMemory(stream);
switch (webp_status)
{
case VP8_STATUS_OUT_OF_MEMORY:
{
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
break;
}
case VP8_STATUS_INVALID_PARAM:
{
ThrowReaderException(CorruptImageError,"invalid parameter");
break;
}
case VP8_STATUS_BITSTREAM_ERROR:
{
ThrowReaderException(CorruptImageError,"CorruptImage");
break;
}
case VP8_STATUS_UNSUPPORTED_FEATURE:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
break;
}
case VP8_STATUS_SUSPENDED:
{
ThrowReaderException(CorruptImageError,"decoder suspended");
break;
}
case VP8_STATUS_USER_ABORT:
{
ThrowReaderException(CorruptImageError,"user abort");
break;
}
case VP8_STATUS_NOT_ENOUGH_DATA:
{
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
break;
}
default:
ThrowReaderException(CorruptImageError,"CorruptImage");
}
}
p=(unsigned char *) webp_image->u.RGBA.rgba;
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*q;
register ssize_t
x;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
WebPFreeDecBuffer(webp_image);
stream=(unsigned char*) RelinquishMagickMemory(stream);
return(image);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r W E B P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterWEBPImage() adds attributes for the WebP 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 RegisterWEBPImage method is:
%
% size_t RegisterWEBPImage(void)
%
*/
ModuleExport size_t RegisterWEBPImage(void)
{
char
version[MaxTextExtent];
MagickInfo
*entry;
*version='\0';
entry=SetMagickInfo("WEBP");
#if defined(MAGICKCORE_WEBP_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadWEBPImage;
entry->encoder=(EncodeImageHandler *) WriteWEBPImage;
(void) FormatLocaleString(version,MaxTextExtent,"libwebp %d.%d.%d[%04X]",
(WebPGetDecoderVersion() >> 16) & 0xff,
(WebPGetDecoderVersion() >> 8) & 0xff,
(WebPGetDecoderVersion() >> 0) & 0xff,WEBP_DECODER_ABI_VERSION);
#endif
entry->description=ConstantString("WebP Image Format");
entry->mime_type=ConstantString("image/webp");
entry->adjoin=MagickFalse;
entry->module=ConstantString("WEBP");
entry->magick=(IsImageFormatHandler *) IsWEBP;
if (*version != '\0')
entry->version=ConstantString(version);
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r W E B P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterWEBPImage() removes format registrations made by the WebP module
% from the list of supported formats.
%
% The format of the UnregisterWEBPImage method is:
%
% UnregisterWEBPImage(void)
%
*/
ModuleExport void UnregisterWEBPImage(void)
{
(void) UnregisterMagickInfo("WEBP");
}
#if defined(MAGICKCORE_WEBP_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e W E B P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteWEBPImage() writes an image in the WebP image format.
%
% The format of the WriteWEBPImage method is:
%
% MagickBooleanType WriteWEBPImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
#if WEBP_DECODER_ABI_VERSION >= 0x0100
static int WebPEncodeProgress(int percent,const WebPPicture* picture)
{
#define EncodeImageTag "Encode/Image"
Image
*image;
MagickBooleanType
status;
image=(Image *) picture->custom_ptr;
status=SetImageProgress(image,EncodeImageTag,percent-1,100);
return(status == MagickFalse ? 0 : 1);
}
#endif
static int WebPEncodeWriter(const unsigned char *stream,size_t length,
const WebPPicture *const picture)
{
Image
*image;
image=(Image *) picture->custom_ptr;
return(length != 0 ? (int) WriteBlob(image,length,stream) : 1);
}
static MagickBooleanType WriteWEBPImage(const ImageInfo *image_info,
Image *image)
{
const char
*value;
int
webp_status;
MagickBooleanType
status;
MemoryInfo
*pixel_info;
register uint32_t
*magick_restrict q;
ssize_t
y;
WebPConfig
configure;
WebPPicture
picture;
WebPAuxStats
statistics;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns > 16383UL) || (image->rows > 16383UL))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
if ((WebPPictureInit(&picture) == 0) || (WebPConfigInit(&configure) == 0))
ThrowWriterException(ResourceLimitError,"UnableToEncodeImageFile");
picture.writer=WebPEncodeWriter;
picture.custom_ptr=(void *) image;
#if WEBP_DECODER_ABI_VERSION >= 0x0100
picture.progress_hook=WebPEncodeProgress;
#endif
picture.stats=(&statistics);
picture.width=(int) image->columns;
picture.height=(int) image->rows;
picture.argb_stride=(int) image->columns;
picture.use_argb=1;
if (image->quality != UndefinedCompressionQuality)
configure.quality=(float) image->quality;
if (image->quality >= 100)
configure.lossless=1;
value=GetImageOption(image_info,"webp:lossless");
if (value != (char *) NULL)
configure.lossless=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:method");
if (value != (char *) NULL)
configure.method=StringToInteger(value);
value=GetImageOption(image_info,"webp:image-hint");
if (value != (char *) NULL)
{
if (LocaleCompare(value,"default") == 0)
configure.image_hint=WEBP_HINT_DEFAULT;
if (LocaleCompare(value,"photo") == 0)
configure.image_hint=WEBP_HINT_PHOTO;
if (LocaleCompare(value,"picture") == 0)
configure.image_hint=WEBP_HINT_PICTURE;
#if WEBP_DECODER_ABI_VERSION >= 0x0200
if (LocaleCompare(value,"graph") == 0)
configure.image_hint=WEBP_HINT_GRAPH;
#endif
}
value=GetImageOption(image_info,"webp:target-size");
if (value != (char *) NULL)
configure.target_size=StringToInteger(value);
value=GetImageOption(image_info,"webp:target-psnr");
if (value != (char *) NULL)
configure.target_PSNR=(float) StringToDouble(value,(char **) NULL);
value=GetImageOption(image_info,"webp:segments");
if (value != (char *) NULL)
configure.segments=StringToInteger(value);
value=GetImageOption(image_info,"webp:sns-strength");
if (value != (char *) NULL)
configure.sns_strength=StringToInteger(value);
value=GetImageOption(image_info,"webp:filter-strength");
if (value != (char *) NULL)
configure.filter_strength=StringToInteger(value);
value=GetImageOption(image_info,"webp:filter-sharpness");
if (value != (char *) NULL)
configure.filter_sharpness=StringToInteger(value);
value=GetImageOption(image_info,"webp:filter-type");
if (value != (char *) NULL)
configure.filter_type=StringToInteger(value);
value=GetImageOption(image_info,"webp:auto-filter");
if (value != (char *) NULL)
configure.autofilter=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:alpha-compression");
if (value != (char *) NULL)
configure.alpha_compression=StringToInteger(value);
value=GetImageOption(image_info,"webp:alpha-filtering");
if (value != (char *) NULL)
configure.alpha_filtering=StringToInteger(value);
value=GetImageOption(image_info,"webp:alpha-quality");
if (value != (char *) NULL)
configure.alpha_quality=StringToInteger(value);
value=GetImageOption(image_info,"webp:pass");
if (value != (char *) NULL)
configure.pass=StringToInteger(value);
value=GetImageOption(image_info,"webp:show-compressed");
if (value != (char *) NULL)
configure.show_compressed=StringToInteger(value);
value=GetImageOption(image_info,"webp:preprocessing");
if (value != (char *) NULL)
configure.preprocessing=StringToInteger(value);
value=GetImageOption(image_info,"webp:partitions");
if (value != (char *) NULL)
configure.partitions=StringToInteger(value);
value=GetImageOption(image_info,"webp:partition-limit");
if (value != (char *) NULL)
configure.partition_limit=StringToInteger(value);
#if WEBP_DECODER_ABI_VERSION >= 0x0201
value=GetImageOption(image_info,"webp:emulate-jpeg-size");
if (value != (char *) NULL)
configure.emulate_jpeg_size=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:low-memory");
if (value != (char *) NULL)
configure.low_memory=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:thread-level");
if (value != (char *) NULL)
configure.thread_level=StringToInteger(value);
#endif
if (WebPValidateConfig(&configure) == 0)
ThrowWriterException(ResourceLimitError,"UnableToEncodeImageFile");
/*
Allocate memory for pixels.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
sizeof(*picture.argb));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
picture.argb=(uint32_t *) GetVirtualMemoryBlob(pixel_info);
/*
Convert image to WebP raster pixels.
*/
q=picture.argb;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(uint32_t) (image->matte != MagickFalse ?
ScaleQuantumToChar(GetPixelAlpha(p)) << 24 : 0xff000000u) |
(ScaleQuantumToChar(GetPixelRed(p)) << 16) |
(ScaleQuantumToChar(GetPixelGreen(p)) << 8) |
(ScaleQuantumToChar(GetPixelBlue(p)));
p++;
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
webp_status=WebPEncode(&configure,&picture);
if (webp_status == 0)
{
const char
*message;
switch (picture.error_code)
{
case VP8_ENC_ERROR_OUT_OF_MEMORY:
{
message="out of memory";
break;
}
case VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY:
{
message="bitstream out of memory";
break;
}
case VP8_ENC_ERROR_NULL_PARAMETER:
{
message="NULL parameter";
break;
}
case VP8_ENC_ERROR_INVALID_CONFIGURATION:
{
message="invalid configuration";
break;
}
case VP8_ENC_ERROR_BAD_DIMENSION:
{
message="bad dimension";
break;
}
case VP8_ENC_ERROR_PARTITION0_OVERFLOW:
{
message="partition 0 overflow (> 512K)";
break;
}
case VP8_ENC_ERROR_PARTITION_OVERFLOW:
{
message="partition overflow (> 16M)";
break;
}
case VP8_ENC_ERROR_BAD_WRITE:
{
message="bad write";
break;
}
case VP8_ENC_ERROR_FILE_TOO_BIG:
{
message="file too big (> 4GB)";
break;
}
#if WEBP_DECODER_ABI_VERSION >= 0x0100
case VP8_ENC_ERROR_USER_ABORT:
{
message="user abort";
break;
}
#endif
default:
{
message="unknown exception";
break;
}
}
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CorruptImageError,(char *) message,"`%s'",image->filename);
}
picture.argb=(uint32_t *) NULL;
WebPPictureFree(&picture);
pixel_info=RelinquishVirtualMemory(pixel_info);
(void) CloseBlob(image);
return(webp_status == 0 ? MagickFalse : MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3199_1 |
crossvul-cpp_data_good_4788_4 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M M EEEEE M M OOO RRRR Y Y %
% MM MM E MM MM O O R R Y Y %
% M M M EEE M M M O O RRRR Y %
% M M E M M O O R R Y %
% M M EEEEE M M OOO R R Y %
% %
% %
% MagickCore Memory Allocation Methods %
% %
% Software Design %
% Cristy %
% July 1998 %
% %
% %
% 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Segregate our memory requirements from any program that calls our API. This
% should help reduce the risk of others changing our program state or causing
% memory corruption.
%
% Our custom memory allocation manager implements a best-fit allocation policy
% using segregated free lists. It uses a linear distribution of size classes
% for lower sizes and a power of two distribution of size classes at higher
% sizes. It is based on the paper, "Fast Memory Allocation using Lazy Fits."
% written by Yoo C. Chung.
%
% By default, ANSI memory methods are called (e.g. malloc). Use the
% custom memory allocator by defining MAGICKCORE_ZERO_CONFIGURATION_SUPPORT
% to allocate memory with private anonymous mapping rather than from the
% heap.
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/memory_.h"
#include "magick/memory-private.h"
#include "magick/resource_.h"
#include "magick/semaphore.h"
#include "magick/string_.h"
#include "magick/utility-private.h"
/*
Define declarations.
*/
#define BlockFooter(block,size) \
((size_t *) ((char *) (block)+(size)-2*sizeof(size_t)))
#define BlockHeader(block) ((size_t *) (block)-1)
#define BlockSize 4096
#define BlockThreshold 1024
#define MaxBlockExponent 16
#define MaxBlocks ((BlockThreshold/(4*sizeof(size_t)))+MaxBlockExponent+1)
#define MaxSegments 1024
#define MemoryGuard ((0xdeadbeef << 31)+0xdeafdeed)
#define NextBlock(block) ((char *) (block)+SizeOfBlock(block))
#define NextBlockInList(block) (*(void **) (block))
#define PreviousBlock(block) ((char *) (block)-(*((size_t *) (block)-2)))
#define PreviousBlockBit 0x01
#define PreviousBlockInList(block) (*((void **) (block)+1))
#define SegmentSize (2*1024*1024)
#define SizeMask (~0x01)
#define SizeOfBlock(block) (*BlockHeader(block) & SizeMask)
/*
Typedef declarations.
*/
typedef enum
{
UndefinedVirtualMemory,
AlignedVirtualMemory,
MapVirtualMemory,
UnalignedVirtualMemory
} VirtualMemoryType;
typedef struct _DataSegmentInfo
{
void
*allocation,
*bound;
MagickBooleanType
mapped;
size_t
length;
struct _DataSegmentInfo
*previous,
*next;
} DataSegmentInfo;
typedef struct _MagickMemoryMethods
{
AcquireMemoryHandler
acquire_memory_handler;
ResizeMemoryHandler
resize_memory_handler;
DestroyMemoryHandler
destroy_memory_handler;
} MagickMemoryMethods;
struct _MemoryInfo
{
char
filename[MaxTextExtent];
VirtualMemoryType
type;
size_t
length;
void
*blob;
size_t
signature;
};
typedef struct _MemoryPool
{
size_t
allocation;
void
*blocks[MaxBlocks+1];
size_t
number_segments;
DataSegmentInfo
*segments[MaxSegments],
segment_pool[MaxSegments];
} MemoryPool;
/*
Global declarations.
*/
#if defined _MSC_VER
static void* MSCMalloc(size_t size)
{
return malloc(size);
}
static void* MSCRealloc(void* ptr, size_t size)
{
return realloc(ptr, size);
}
static void MSCFree(void* ptr)
{
free(ptr);
}
#endif
static MagickMemoryMethods
memory_methods =
{
#if defined _MSC_VER
(AcquireMemoryHandler) MSCMalloc,
(ResizeMemoryHandler) MSCRealloc,
(DestroyMemoryHandler) MSCFree
#else
(AcquireMemoryHandler) malloc,
(ResizeMemoryHandler) realloc,
(DestroyMemoryHandler) free
#endif
};
#if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
static MemoryPool
memory_pool;
static SemaphoreInfo
*memory_semaphore = (SemaphoreInfo *) NULL;
static volatile DataSegmentInfo
*free_segments = (DataSegmentInfo *) NULL;
/*
Forward declarations.
*/
static MagickBooleanType
ExpandHeap(size_t);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e A l i g n e d M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireAlignedMemory() returns a pointer to a block of memory at least size
% bytes whose address is a multiple of 16*sizeof(void *).
%
% The format of the AcquireAlignedMemory method is:
%
% void *AcquireAlignedMemory(const size_t count,const size_t quantum)
%
% A description of each parameter follows:
%
% o count: the number of quantum elements to allocate.
%
% o quantum: the number of bytes in each quantum.
%
*/
MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum)
{
#define AlignedExtent(size,alignment) \
(((size)+((alignment)-1)) & ~((alignment)-1))
size_t
alignment,
extent,
size;
void
*memory;
if (HeapOverflowSanityCheck(count,quantum) != MagickFalse)
return((void *) NULL);
memory=NULL;
alignment=CACHE_LINE_SIZE;
size=count*quantum;
extent=AlignedExtent(size,alignment);
if ((size == 0) || (alignment < sizeof(void *)) || (extent < size))
return((void *) NULL);
#if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN)
if (posix_memalign(&memory,alignment,extent) != 0)
memory=NULL;
#elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC)
memory=_aligned_malloc(extent,alignment);
#else
{
void
*p;
extent=(size+alignment-1)+sizeof(void *);
if (extent > size)
{
p=malloc(extent);
if (p != NULL)
{
memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment);
*((void **) memory-1)=p;
}
}
}
#endif
return(memory);
}
#if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e B l o c k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireBlock() returns a pointer to a block of memory at least size bytes
% suitably aligned for any use.
%
% The format of the AcquireBlock method is:
%
% void *AcquireBlock(const size_t size)
%
% A description of each parameter follows:
%
% o size: the size of the memory in bytes to allocate.
%
*/
static inline size_t AllocationPolicy(size_t size)
{
register size_t
blocksize;
/*
The linear distribution.
*/
assert(size != 0);
assert(size % (4*sizeof(size_t)) == 0);
if (size <= BlockThreshold)
return(size/(4*sizeof(size_t)));
/*
Check for the largest block size.
*/
if (size > (size_t) (BlockThreshold*(1L << (MaxBlockExponent-1L))))
return(MaxBlocks-1L);
/*
Otherwise use a power of two distribution.
*/
blocksize=BlockThreshold/(4*sizeof(size_t));
for ( ; size > BlockThreshold; size/=2)
blocksize++;
assert(blocksize > (BlockThreshold/(4*sizeof(size_t))));
assert(blocksize < (MaxBlocks-1L));
return(blocksize);
}
static inline void InsertFreeBlock(void *block,const size_t i)
{
register void
*next,
*previous;
size_t
size;
size=SizeOfBlock(block);
previous=(void *) NULL;
next=memory_pool.blocks[i];
while ((next != (void *) NULL) && (SizeOfBlock(next) < size))
{
previous=next;
next=NextBlockInList(next);
}
PreviousBlockInList(block)=previous;
NextBlockInList(block)=next;
if (previous != (void *) NULL)
NextBlockInList(previous)=block;
else
memory_pool.blocks[i]=block;
if (next != (void *) NULL)
PreviousBlockInList(next)=block;
}
static inline void RemoveFreeBlock(void *block,const size_t i)
{
register void
*next,
*previous;
next=NextBlockInList(block);
previous=PreviousBlockInList(block);
if (previous == (void *) NULL)
memory_pool.blocks[i]=next;
else
NextBlockInList(previous)=next;
if (next != (void *) NULL)
PreviousBlockInList(next)=previous;
}
static void *AcquireBlock(size_t size)
{
register size_t
i;
register void
*block;
/*
Find free block.
*/
size=(size_t) (size+sizeof(size_t)+6*sizeof(size_t)-1) & -(4U*sizeof(size_t));
i=AllocationPolicy(size);
block=memory_pool.blocks[i];
while ((block != (void *) NULL) && (SizeOfBlock(block) < size))
block=NextBlockInList(block);
if (block == (void *) NULL)
{
i++;
while (memory_pool.blocks[i] == (void *) NULL)
i++;
block=memory_pool.blocks[i];
if (i >= MaxBlocks)
return((void *) NULL);
}
assert((*BlockHeader(NextBlock(block)) & PreviousBlockBit) == 0);
assert(SizeOfBlock(block) >= size);
RemoveFreeBlock(block,AllocationPolicy(SizeOfBlock(block)));
if (SizeOfBlock(block) > size)
{
size_t
blocksize;
void
*next;
/*
Split block.
*/
next=(char *) block+size;
blocksize=SizeOfBlock(block)-size;
*BlockHeader(next)=blocksize;
*BlockFooter(next,blocksize)=blocksize;
InsertFreeBlock(next,AllocationPolicy(blocksize));
*BlockHeader(block)=size | (*BlockHeader(block) & ~SizeMask);
}
assert(size == SizeOfBlock(block));
*BlockHeader(NextBlock(block))|=PreviousBlockBit;
memory_pool.allocation+=size;
return(block);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireMagickMemory() returns a pointer to a block of memory at least size
% bytes suitably aligned for any use.
%
% The format of the AcquireMagickMemory method is:
%
% void *AcquireMagickMemory(const size_t size)
%
% A description of each parameter follows:
%
% o size: the size of the memory in bytes to allocate.
%
*/
MagickExport void *AcquireMagickMemory(const size_t size)
{
register void
*memory;
#if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
memory=memory_methods.acquire_memory_handler(size == 0 ? 1UL : size);
#else
if (memory_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&memory_semaphore);
if (free_segments == (DataSegmentInfo *) NULL)
{
LockSemaphoreInfo(memory_semaphore);
if (free_segments == (DataSegmentInfo *) NULL)
{
register ssize_t
i;
assert(2*sizeof(size_t) > (size_t) (~SizeMask));
(void) ResetMagickMemory(&memory_pool,0,sizeof(memory_pool));
memory_pool.allocation=SegmentSize;
memory_pool.blocks[MaxBlocks]=(void *) (-1);
for (i=0; i < MaxSegments; i++)
{
if (i != 0)
memory_pool.segment_pool[i].previous=
(&memory_pool.segment_pool[i-1]);
if (i != (MaxSegments-1))
memory_pool.segment_pool[i].next=(&memory_pool.segment_pool[i+1]);
}
free_segments=(&memory_pool.segment_pool[0]);
}
UnlockSemaphoreInfo(memory_semaphore);
}
LockSemaphoreInfo(memory_semaphore);
memory=AcquireBlock(size == 0 ? 1UL : size);
if (memory == (void *) NULL)
{
if (ExpandHeap(size == 0 ? 1UL : size) != MagickFalse)
memory=AcquireBlock(size == 0 ? 1UL : size);
}
UnlockSemaphoreInfo(memory_semaphore);
#endif
return(memory);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e Q u a n t u m M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireQuantumMemory() returns a pointer to a block of memory at least
% count * quantum bytes suitably aligned for any use.
%
% The format of the AcquireQuantumMemory method is:
%
% void *AcquireQuantumMemory(const size_t count,const size_t quantum)
%
% A description of each parameter follows:
%
% o count: the number of quantum elements to allocate.
%
% o quantum: the number of bytes in each quantum.
%
*/
MagickExport void *AcquireQuantumMemory(const size_t count,const size_t quantum)
{
size_t
extent;
if (HeapOverflowSanityCheck(count,quantum) != MagickFalse)
return((void *) NULL);
extent=count*quantum;
return(AcquireMagickMemory(extent));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e V i r t u a l M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireVirtualMemory() allocates a pointer to a block of memory at least size
% bytes suitably aligned for any use.
%
% The format of the AcquireVirtualMemory method is:
%
% MemoryInfo *AcquireVirtualMemory(const size_t count,const size_t quantum)
%
% A description of each parameter follows:
%
% o count: the number of quantum elements to allocate.
%
% o quantum: the number of bytes in each quantum.
%
*/
MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count,
const size_t quantum)
{
MemoryInfo
*memory_info;
size_t
extent;
if (HeapOverflowSanityCheck(count,quantum) != MagickFalse)
return((MemoryInfo *) NULL);
memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1,
sizeof(*memory_info)));
if (memory_info == (MemoryInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(memory_info,0,sizeof(*memory_info));
extent=count*quantum;
memory_info->length=extent;
memory_info->signature=MagickSignature;
if (AcquireMagickResource(MemoryResource,extent) != MagickFalse)
{
memory_info->blob=AcquireAlignedMemory(1,extent);
if (memory_info->blob != NULL)
{
memory_info->type=AlignedVirtualMemory;
return(memory_info);
}
}
RelinquishMagickResource(MemoryResource,extent);
if (AcquireMagickResource(MapResource,extent) != MagickFalse)
{
/*
Heap memory failed, try anonymous memory mapping.
*/
memory_info->blob=MapBlob(-1,IOMode,0,extent);
if (memory_info->blob != NULL)
{
memory_info->type=MapVirtualMemory;
return(memory_info);
}
if (AcquireMagickResource(DiskResource,extent) != MagickFalse)
{
int
file;
/*
Anonymous memory mapping failed, try file-backed memory mapping.
If the MapResource request failed, there is no point in trying
file-backed memory mapping.
*/
file=AcquireUniqueFileResource(memory_info->filename);
if (file != -1)
{
MagickOffsetType
offset;
offset=(MagickOffsetType) lseek(file,extent-1,SEEK_SET);
if ((offset == (MagickOffsetType) (extent-1)) &&
(write(file,"",1) == 1))
{
memory_info->blob=MapBlob(file,IOMode,0,extent);
if (memory_info->blob != NULL)
{
(void) close(file);
memory_info->type=MapVirtualMemory;
return(memory_info);
}
}
/*
File-backed memory mapping failed, delete the temporary file.
*/
(void) close(file);
(void) RelinquishUniqueFileResource(memory_info->filename);
*memory_info->filename='\0';
}
}
RelinquishMagickResource(DiskResource,extent);
}
RelinquishMagickResource(MapResource,extent);
if (memory_info->blob == NULL)
{
memory_info->blob=AcquireMagickMemory(extent);
if (memory_info->blob != NULL)
memory_info->type=UnalignedVirtualMemory;
}
if (memory_info->blob == NULL)
memory_info=RelinquishVirtualMemory(memory_info);
return(memory_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o p y M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CopyMagickMemory() copies size bytes from memory area source to the
% destination. Copying between objects that overlap will take place
% correctly. It returns destination.
%
% The format of the CopyMagickMemory method is:
%
% void *CopyMagickMemory(void *destination,const void *source,
% const size_t size)
%
% A description of each parameter follows:
%
% o destination: the destination.
%
% o source: the source.
%
% o size: the size of the memory in bytes to allocate.
%
*/
MagickExport void *CopyMagickMemory(void *destination,const void *source,
const size_t size)
{
register const unsigned char
*p;
register unsigned char
*q;
assert(destination != (void *) NULL);
assert(source != (const void *) NULL);
p=(const unsigned char *) source;
q=(unsigned char *) destination;
if (((q+size) < p) || (q > (p+size)))
switch (size)
{
default: return(memcpy(destination,source,size));
case 8: *q++=(*p++);
case 7: *q++=(*p++);
case 6: *q++=(*p++);
case 5: *q++=(*p++);
case 4: *q++=(*p++);
case 3: *q++=(*p++);
case 2: *q++=(*p++);
case 1: *q++=(*p++);
case 0: return(destination);
}
return(memmove(destination,source,size));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyMagickMemory() deallocates memory associated with the memory manager.
%
% The format of the DestroyMagickMemory method is:
%
% DestroyMagickMemory(void)
%
*/
MagickExport void DestroyMagickMemory(void)
{
#if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
register ssize_t
i;
if (memory_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&memory_semaphore);
LockSemaphoreInfo(memory_semaphore);
for (i=0; i < (ssize_t) memory_pool.number_segments; i++)
if (memory_pool.segments[i]->mapped == MagickFalse)
memory_methods.destroy_memory_handler(
memory_pool.segments[i]->allocation);
else
(void) UnmapBlob(memory_pool.segments[i]->allocation,
memory_pool.segments[i]->length);
free_segments=(DataSegmentInfo *) NULL;
(void) ResetMagickMemory(&memory_pool,0,sizeof(memory_pool));
UnlockSemaphoreInfo(memory_semaphore);
DestroySemaphoreInfo(&memory_semaphore);
#endif
}
#if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ E x p a n d H e a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ExpandHeap() get more memory from the system. It returns MagickTrue on
% success otherwise MagickFalse.
%
% The format of the ExpandHeap method is:
%
% MagickBooleanType ExpandHeap(size_t size)
%
% A description of each parameter follows:
%
% o size: the size of the memory in bytes we require.
%
*/
static MagickBooleanType ExpandHeap(size_t size)
{
DataSegmentInfo
*segment_info;
MagickBooleanType
mapped;
register ssize_t
i;
register void
*block;
size_t
blocksize;
void
*segment;
blocksize=((size+12*sizeof(size_t))+SegmentSize-1) & -SegmentSize;
assert(memory_pool.number_segments < MaxSegments);
segment=MapBlob(-1,IOMode,0,blocksize);
mapped=segment != (void *) NULL ? MagickTrue : MagickFalse;
if (segment == (void *) NULL)
segment=(void *) memory_methods.acquire_memory_handler(blocksize);
if (segment == (void *) NULL)
return(MagickFalse);
segment_info=(DataSegmentInfo *) free_segments;
free_segments=segment_info->next;
segment_info->mapped=mapped;
segment_info->length=blocksize;
segment_info->allocation=segment;
segment_info->bound=(char *) segment+blocksize;
i=(ssize_t) memory_pool.number_segments-1;
for ( ; (i >= 0) && (memory_pool.segments[i]->allocation > segment); i--)
memory_pool.segments[i+1]=memory_pool.segments[i];
memory_pool.segments[i+1]=segment_info;
memory_pool.number_segments++;
size=blocksize-12*sizeof(size_t);
block=(char *) segment_info->allocation+4*sizeof(size_t);
*BlockHeader(block)=size | PreviousBlockBit;
*BlockFooter(block,size)=size;
InsertFreeBlock(block,AllocationPolicy(size));
block=NextBlock(block);
assert(block < segment_info->bound);
*BlockHeader(block)=2*sizeof(size_t);
*BlockHeader(NextBlock(block))=PreviousBlockBit;
return(MagickTrue);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t M a g i c k M e m o r y M e t h o d s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetMagickMemoryMethods() gets the methods to acquire, resize, and destroy
% memory.
%
% The format of the GetMagickMemoryMethods() method is:
%
% void GetMagickMemoryMethods(AcquireMemoryHandler *acquire_memory_handler,
% ResizeMemoryHandler *resize_memory_handler,
% DestroyMemoryHandler *destroy_memory_handler)
%
% A description of each parameter follows:
%
% o acquire_memory_handler: method to acquire memory (e.g. malloc).
%
% o resize_memory_handler: method to resize memory (e.g. realloc).
%
% o destroy_memory_handler: method to destroy memory (e.g. free).
%
*/
MagickExport void GetMagickMemoryMethods(
AcquireMemoryHandler *acquire_memory_handler,
ResizeMemoryHandler *resize_memory_handler,
DestroyMemoryHandler *destroy_memory_handler)
{
assert(acquire_memory_handler != (AcquireMemoryHandler *) NULL);
assert(resize_memory_handler != (ResizeMemoryHandler *) NULL);
assert(destroy_memory_handler != (DestroyMemoryHandler *) NULL);
*acquire_memory_handler=memory_methods.acquire_memory_handler;
*resize_memory_handler=memory_methods.resize_memory_handler;
*destroy_memory_handler=memory_methods.destroy_memory_handler;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t V i r t u a l M e m o r y B l o b %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualMemoryBlob() returns the virtual memory blob associated with the
% specified MemoryInfo structure.
%
% The format of the GetVirtualMemoryBlob method is:
%
% void *GetVirtualMemoryBlob(const MemoryInfo *memory_info)
%
% A description of each parameter follows:
%
% o memory_info: The MemoryInfo structure.
*/
MagickExport void *GetVirtualMemoryBlob(const MemoryInfo *memory_info)
{
assert(memory_info != (const MemoryInfo *) NULL);
assert(memory_info->signature == MagickSignature);
return(memory_info->blob);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ H e a p O v e r f l o w S a n i t y C h e c k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% HeapOverflowSanityCheck() returns MagickTrue if the heap allocation request
% does not exceed the maximum limits of a size_t otherwise MagickFalse.
%
% The format of the HeapOverflowSanityCheck method is:
%
% MagickBooleanType HeapOverflowSanityCheck(const size_t count,
% const size_t quantum)
%
% A description of each parameter follows:
%
% o size: the size of the memory in bytes we require.
%
*/
MagickExport MagickBooleanType HeapOverflowSanityCheck(const size_t count,
const size_t quantum)
{
size_t
size;
size=count*quantum;
if ((count == 0) || (quantum != (size/count)))
{
errno=ENOMEM;
return(MagickTrue);
}
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e l i n q u i s h A l i g n e d M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RelinquishAlignedMemory() frees memory acquired with AcquireAlignedMemory()
% or reuse.
%
% The format of the RelinquishAlignedMemory method is:
%
% void *RelinquishAlignedMemory(void *memory)
%
% A description of each parameter follows:
%
% o memory: A pointer to a block of memory to free for reuse.
%
*/
MagickExport void *RelinquishAlignedMemory(void *memory)
{
if (memory == (void *) NULL)
return((void *) NULL);
#if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN)
free(memory);
#elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC)
_aligned_free(memory);
#else
free(*((void **) memory-1));
#endif
return(NULL);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e l i n q u i s h M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RelinquishMagickMemory() frees memory acquired with AcquireMagickMemory()
% or AcquireQuantumMemory() for reuse.
%
% The format of the RelinquishMagickMemory method is:
%
% void *RelinquishMagickMemory(void *memory)
%
% A description of each parameter follows:
%
% o memory: A pointer to a block of memory to free for reuse.
%
*/
MagickExport void *RelinquishMagickMemory(void *memory)
{
if (memory == (void *) NULL)
return((void *) NULL);
#if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
memory_methods.destroy_memory_handler(memory);
#else
LockSemaphoreInfo(memory_semaphore);
assert((SizeOfBlock(memory) % (4*sizeof(size_t))) == 0);
assert((*BlockHeader(NextBlock(memory)) & PreviousBlockBit) != 0);
if ((*BlockHeader(memory) & PreviousBlockBit) == 0)
{
void
*previous;
/*
Coalesce with previous adjacent block.
*/
previous=PreviousBlock(memory);
RemoveFreeBlock(previous,AllocationPolicy(SizeOfBlock(previous)));
*BlockHeader(previous)=(SizeOfBlock(previous)+SizeOfBlock(memory)) |
(*BlockHeader(previous) & ~SizeMask);
memory=previous;
}
if ((*BlockHeader(NextBlock(NextBlock(memory))) & PreviousBlockBit) == 0)
{
void
*next;
/*
Coalesce with next adjacent block.
*/
next=NextBlock(memory);
RemoveFreeBlock(next,AllocationPolicy(SizeOfBlock(next)));
*BlockHeader(memory)=(SizeOfBlock(memory)+SizeOfBlock(next)) |
(*BlockHeader(memory) & ~SizeMask);
}
*BlockFooter(memory,SizeOfBlock(memory))=SizeOfBlock(memory);
*BlockHeader(NextBlock(memory))&=(~PreviousBlockBit);
InsertFreeBlock(memory,AllocationPolicy(SizeOfBlock(memory)));
UnlockSemaphoreInfo(memory_semaphore);
#endif
return((void *) NULL);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e l i n q u i s h V i r t u a l M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RelinquishVirtualMemory() frees memory acquired with AcquireVirtualMemory().
%
% The format of the RelinquishVirtualMemory method is:
%
% MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info)
%
% A description of each parameter follows:
%
% o memory_info: A pointer to a block of memory to free for reuse.
%
*/
MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info)
{
assert(memory_info != (MemoryInfo *) NULL);
assert(memory_info->signature == MagickSignature);
if (memory_info->blob != (void *) NULL)
switch (memory_info->type)
{
case AlignedVirtualMemory:
{
memory_info->blob=RelinquishAlignedMemory(memory_info->blob);
RelinquishMagickResource(MemoryResource,memory_info->length);
break;
}
case MapVirtualMemory:
{
(void) UnmapBlob(memory_info->blob,memory_info->length);
memory_info->blob=NULL;
RelinquishMagickResource(MapResource,memory_info->length);
if (*memory_info->filename != '\0')
{
(void) RelinquishUniqueFileResource(memory_info->filename);
RelinquishMagickResource(DiskResource,memory_info->length);
}
break;
}
case UnalignedVirtualMemory:
default:
{
memory_info->blob=RelinquishMagickMemory(memory_info->blob);
break;
}
}
memory_info->signature=(~MagickSignature);
memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info);
return(memory_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetMagickMemory() fills the first size bytes of the memory area pointed to
% by memory with the constant byte c.
%
% The format of the ResetMagickMemory method is:
%
% void *ResetMagickMemory(void *memory,int byte,const size_t size)
%
% A description of each parameter follows:
%
% o memory: a pointer to a memory allocation.
%
% o byte: set the memory to this value.
%
% o size: size of the memory to reset.
%
*/
MagickExport void *ResetMagickMemory(void *memory,int byte,const size_t size)
{
assert(memory != (void *) NULL);
return(memset(memory,byte,size));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s i z e M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResizeMagickMemory() changes the size of the memory and returns a pointer to
% the (possibly moved) block. The contents will be unchanged up to the
% lesser of the new and old sizes.
%
% The format of the ResizeMagickMemory method is:
%
% void *ResizeMagickMemory(void *memory,const size_t size)
%
% A description of each parameter follows:
%
% o memory: A pointer to a memory allocation.
%
% o size: the new size of the allocated memory.
%
*/
#if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
static inline void *ResizeBlock(void *block,size_t size)
{
register void
*memory;
if (block == (void *) NULL)
return(AcquireBlock(size));
memory=AcquireBlock(size);
if (memory == (void *) NULL)
return((void *) NULL);
if (size <= (SizeOfBlock(block)-sizeof(size_t)))
(void) memcpy(memory,block,size);
else
(void) memcpy(memory,block,SizeOfBlock(block)-sizeof(size_t));
memory_pool.allocation+=size;
return(memory);
}
#endif
MagickExport void *ResizeMagickMemory(void *memory,const size_t size)
{
register void
*block;
if (memory == (void *) NULL)
return(AcquireMagickMemory(size));
#if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
block=memory_methods.resize_memory_handler(memory,size == 0 ? 1UL : size);
if (block == (void *) NULL)
memory=RelinquishMagickMemory(memory);
#else
LockSemaphoreInfo(memory_semaphore);
block=ResizeBlock(memory,size == 0 ? 1UL : size);
if (block == (void *) NULL)
{
if (ExpandHeap(size == 0 ? 1UL : size) == MagickFalse)
{
UnlockSemaphoreInfo(memory_semaphore);
memory=RelinquishMagickMemory(memory);
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
}
block=ResizeBlock(memory,size == 0 ? 1UL : size);
assert(block != (void *) NULL);
}
UnlockSemaphoreInfo(memory_semaphore);
memory=RelinquishMagickMemory(memory);
#endif
return(block);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s i z e Q u a n t u m M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResizeQuantumMemory() changes the size of the memory and returns a pointer
% to the (possibly moved) block. The contents will be unchanged up to the
% lesser of the new and old sizes.
%
% The format of the ResizeQuantumMemory method is:
%
% void *ResizeQuantumMemory(void *memory,const size_t count,
% const size_t quantum)
%
% A description of each parameter follows:
%
% o memory: A pointer to a memory allocation.
%
% o count: the number of quantum elements to allocate.
%
% o quantum: the number of bytes in each quantum.
%
*/
MagickExport void *ResizeQuantumMemory(void *memory,const size_t count,
const size_t quantum)
{
size_t
extent;
if (HeapOverflowSanityCheck(count,quantum) != MagickFalse)
{
memory=RelinquishMagickMemory(memory);
return((void *) NULL);
}
extent=count*quantum;
return(ResizeMagickMemory(memory,extent));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t M a g i c k M e m o r y M e t h o d s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetMagickMemoryMethods() sets the methods to acquire, resize, and destroy
% memory. Your custom memory methods must be set prior to the
% MagickCoreGenesis() method.
%
% The format of the SetMagickMemoryMethods() method is:
%
% SetMagickMemoryMethods(AcquireMemoryHandler acquire_memory_handler,
% ResizeMemoryHandler resize_memory_handler,
% DestroyMemoryHandler destroy_memory_handler)
%
% A description of each parameter follows:
%
% o acquire_memory_handler: method to acquire memory (e.g. malloc).
%
% o resize_memory_handler: method to resize memory (e.g. realloc).
%
% o destroy_memory_handler: method to destroy memory (e.g. free).
%
*/
MagickExport void SetMagickMemoryMethods(
AcquireMemoryHandler acquire_memory_handler,
ResizeMemoryHandler resize_memory_handler,
DestroyMemoryHandler destroy_memory_handler)
{
/*
Set memory methods.
*/
if (acquire_memory_handler != (AcquireMemoryHandler) NULL)
memory_methods.acquire_memory_handler=acquire_memory_handler;
if (resize_memory_handler != (ResizeMemoryHandler) NULL)
memory_methods.resize_memory_handler=resize_memory_handler;
if (destroy_memory_handler != (DestroyMemoryHandler) NULL)
memory_methods.destroy_memory_handler=destroy_memory_handler;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4788_4 |
crossvul-cpp_data_good_810_0 | #include "jsi.h"
#include "jsvalue.h"
#include "jsbuiltin.h"
#if defined(_MSC_VER) && (_MSC_VER < 1700) /* VS2012 has stdint.h */
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif
static void jsB_new_Number(js_State *J)
{
js_newnumber(J, js_gettop(J) > 1 ? js_tonumber(J, 1) : 0);
}
static void jsB_Number(js_State *J)
{
js_pushnumber(J, js_gettop(J) > 1 ? js_tonumber(J, 1) : 0);
}
static void Np_valueOf(js_State *J)
{
js_Object *self = js_toobject(J, 0);
if (self->type != JS_CNUMBER) js_typeerror(J, "not a number");
js_pushnumber(J, self->u.number);
}
static void Np_toString(js_State *J)
{
char buf[100];
js_Object *self = js_toobject(J, 0);
int radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1);
if (self->type != JS_CNUMBER)
js_typeerror(J, "not a number");
if (radix == 10) {
js_pushstring(J, jsV_numbertostring(J, buf, self->u.number));
return;
}
if (radix < 2 || radix > 36)
js_rangeerror(J, "invalid radix");
/* lame number to string conversion for any radix from 2 to 36 */
{
static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
double number = self->u.number;
int sign = self->u.number < 0;
js_Buffer *sb = NULL;
uint64_t u, limit = ((uint64_t)1<<52);
int ndigits, exp, point;
if (number == 0) { js_pushstring(J, "0"); return; }
if (isnan(number)) { js_pushstring(J, "NaN"); return; }
if (isinf(number)) { js_pushstring(J, sign ? "-Infinity" : "Infinity"); return; }
if (sign)
number = -number;
/* fit as many digits as we want in an int */
exp = 0;
while (number * pow(radix, exp) > limit)
--exp;
while (number * pow(radix, exp+1) < limit)
++exp;
u = number * pow(radix, exp) + 0.5;
/* trim trailing zeros */
while (u > 0 && (u % radix) == 0) {
u /= radix;
--exp;
}
/* serialize digits */
ndigits = 0;
while (u > 0) {
buf[ndigits++] = digits[u % radix];
u /= radix;
}
point = ndigits - exp;
if (js_try(J)) {
js_free(J, sb);
js_throw(J);
}
if (sign)
js_putc(J, &sb, '-');
if (point <= 0) {
js_putc(J, &sb, '0');
js_putc(J, &sb, '.');
while (point++ < 0)
js_putc(J, &sb, '0');
while (ndigits-- > 0)
js_putc(J, &sb, buf[ndigits]);
} else {
while (ndigits-- > 0) {
js_putc(J, &sb, buf[ndigits]);
if (--point == 0 && ndigits > 0)
js_putc(J, &sb, '.');
}
while (point-- > 0)
js_putc(J, &sb, '0');
}
js_putc(J, &sb, 0);
js_pushstring(J, sb->s);
js_endtry(J);
js_free(J, sb);
}
}
/* Customized ToString() on a number */
static void numtostr(js_State *J, const char *fmt, int w, double n)
{
/* buf needs to fit printf("%.20f", 1e20) */
char buf[50], *e;
sprintf(buf, fmt, w, n);
e = strchr(buf, 'e');
if (e) {
int exp = atoi(e+1);
sprintf(e, "e%+d", exp);
}
js_pushstring(J, buf);
}
static void Np_toFixed(js_State *J)
{
js_Object *self = js_toobject(J, 0);
int width = js_tointeger(J, 1);
char buf[32];
double x;
if (self->type != JS_CNUMBER) js_typeerror(J, "not a number");
if (width < 0) js_rangeerror(J, "precision %d out of range", width);
if (width > 20) js_rangeerror(J, "precision %d out of range", width);
x = self->u.number;
if (isnan(x) || isinf(x) || x <= -1e21 || x >= 1e21)
js_pushstring(J, jsV_numbertostring(J, buf, x));
else
numtostr(J, "%.*f", width, x);
}
static void Np_toExponential(js_State *J)
{
js_Object *self = js_toobject(J, 0);
int width = js_tointeger(J, 1);
char buf[32];
double x;
if (self->type != JS_CNUMBER) js_typeerror(J, "not a number");
if (width < 0) js_rangeerror(J, "precision %d out of range", width);
if (width > 20) js_rangeerror(J, "precision %d out of range", width);
x = self->u.number;
if (isnan(x) || isinf(x))
js_pushstring(J, jsV_numbertostring(J, buf, x));
else
numtostr(J, "%.*e", width, self->u.number);
}
static void Np_toPrecision(js_State *J)
{
js_Object *self = js_toobject(J, 0);
int width = js_tointeger(J, 1);
char buf[32];
double x;
if (self->type != JS_CNUMBER) js_typeerror(J, "not a number");
if (width < 1) js_rangeerror(J, "precision %d out of range", width);
if (width > 21) js_rangeerror(J, "precision %d out of range", width);
x = self->u.number;
if (isnan(x) || isinf(x))
js_pushstring(J, jsV_numbertostring(J, buf, x));
else
numtostr(J, "%.*g", width, self->u.number);
}
void jsB_initnumber(js_State *J)
{
J->Number_prototype->u.number = 0;
js_pushobject(J, J->Number_prototype);
{
jsB_propf(J, "Number.prototype.valueOf", Np_valueOf, 0);
jsB_propf(J, "Number.prototype.toString", Np_toString, 1);
jsB_propf(J, "Number.prototype.toLocaleString", Np_toString, 0);
jsB_propf(J, "Number.prototype.toFixed", Np_toFixed, 1);
jsB_propf(J, "Number.prototype.toExponential", Np_toExponential, 1);
jsB_propf(J, "Number.prototype.toPrecision", Np_toPrecision, 1);
}
js_newcconstructor(J, jsB_Number, jsB_new_Number, "Number", 0); /* 1 */
{
jsB_propn(J, "MAX_VALUE", 1.7976931348623157e+308);
jsB_propn(J, "MIN_VALUE", 5e-324);
jsB_propn(J, "NaN", NAN);
jsB_propn(J, "NEGATIVE_INFINITY", -INFINITY);
jsB_propn(J, "POSITIVE_INFINITY", INFINITY);
}
js_defglobal(J, "Number", JS_DONTENUM);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_810_0 |
crossvul-cpp_data_good_3199_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W W EEEEE BBBB PPPP %
% W W E B B P P %
% W W W EEE BBBB PPPP %
% WW WW E B B P %
% W W EEEEE BBBB P %
% %
% %
% Read/Write WebP Image Format %
% %
% Software Design %
% Cristy %
% March 2011 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/client.h"
#include "magick/colorspace-private.h"
#include "magick/display.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/monitor.h"
#include "magick/monitor-private.h"
#include "magick/memory_.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
#include "magick/utility.h"
#include "magick/xwindow.h"
#include "magick/xwindow-private.h"
#if defined(MAGICKCORE_WEBP_DELEGATE)
#include <webp/decode.h>
#include <webp/encode.h>
#endif
/*
Forward declarations.
*/
#if defined(MAGICKCORE_WEBP_DELEGATE)
static MagickBooleanType
WriteWEBPImage(const ImageInfo *,Image *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s W E B P %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsWEBP() returns MagickTrue if the image format type, identified by the
% magick string, is WebP.
%
% The format of the IsWEBP method is:
%
% MagickBooleanType IsWEBP(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 IsWEBP(const unsigned char *magick,const size_t length)
{
if (length < 12)
return(MagickFalse);
if (LocaleNCompare((const char *) magick+8,"WEBP",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
#if defined(MAGICKCORE_WEBP_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d W E B P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadWEBPImage() reads an image in the WebP image format.
%
% The format of the ReadWEBPImage method is:
%
% Image *ReadWEBPImage(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 inline uint32_t ReadWebPLSBWord(
const unsigned char *magick_restrict data)
{
register const unsigned char
*p;
register uint32_t
value;
p=data;
value=(uint32_t) (*p++);
value|=((uint32_t) (*p++)) << 8;
value|=((uint32_t) (*p++)) << 16;
value|=((uint32_t) (*p++)) << 24;
return(value);
}
static MagickBooleanType IsWEBPImageLossless(const unsigned char *stream,
const size_t length)
{
#define VP8_CHUNK_INDEX 15
#define LOSSLESS_FLAG 'L'
#define EXTENDED_HEADER 'X'
#define VP8_CHUNK_HEADER "VP8"
#define VP8_CHUNK_HEADER_SIZE 3
#define RIFF_HEADER_SIZE 12
#define VP8X_CHUNK_SIZE 10
#define TAG_SIZE 4
#define CHUNK_SIZE_BYTES 4
#define CHUNK_HEADER_SIZE 8
#define MAX_CHUNK_PAYLOAD (~0U-CHUNK_HEADER_SIZE-1)
ssize_t
offset;
/*
Read simple header.
*/
if (stream[VP8_CHUNK_INDEX] != EXTENDED_HEADER)
return(stream[VP8_CHUNK_INDEX] == LOSSLESS_FLAG ? MagickTrue : MagickFalse);
/*
Read extended header.
*/
offset=RIFF_HEADER_SIZE+TAG_SIZE+CHUNK_SIZE_BYTES+VP8X_CHUNK_SIZE;
while (offset <= (ssize_t) length)
{
uint32_t
chunk_size,
chunk_size_pad;
chunk_size=ReadWebPLSBWord(stream+offset+TAG_SIZE);
if (chunk_size > MAX_CHUNK_PAYLOAD)
break;
chunk_size_pad=(CHUNK_HEADER_SIZE+chunk_size+1) & ~1;
if (memcmp(stream+offset,VP8_CHUNK_HEADER,VP8_CHUNK_HEADER_SIZE) == 0)
return(*(stream+offset+VP8_CHUNK_HEADER_SIZE) == LOSSLESS_FLAG ?
MagickTrue : MagickFalse);
offset+=chunk_size_pad;
}
return(MagickFalse);
}
static Image *ReadWEBPImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
int
webp_status;
MagickBooleanType
status;
register unsigned char
*p;
size_t
length;
ssize_t
count,
y;
unsigned char
header[12],
*stream;
WebPDecoderConfig
configure;
WebPDecBuffer
*magick_restrict webp_image = &configure.output;
WebPBitstreamFeatures
*magick_restrict features = &configure.input;
/*
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);
}
if (WebPInitDecoderConfig(&configure) == 0)
ThrowReaderException(ResourceLimitError,"UnableToDecodeImageFile");
webp_image->colorspace=MODE_RGBA;
count=ReadBlob(image,12,header);
if (count != 12)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
status=IsWEBP(header,count);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"CorruptImage");
length=(size_t) (ReadWebPLSBWord(header+4)+8);
if (length < 12)
ThrowReaderException(CorruptImageError,"CorruptImage");
stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream));
if (stream == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) memcpy(stream,header,12);
count=ReadBlob(image,length-12,stream+12);
if (count != (ssize_t) (length-12))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
webp_status=WebPGetFeatures(stream,length,features);
if (webp_status == VP8_STATUS_OK)
{
image->columns=(size_t) features->width;
image->rows=(size_t) features->height;
image->depth=8;
image->matte=features->has_alpha != 0 ? MagickTrue : MagickFalse;
if (IsWEBPImageLossless(stream,length) != MagickFalse)
image->quality=100;
if (image_info->ping != MagickFalse)
{
stream=(unsigned char*) RelinquishMagickMemory(stream);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
webp_status=WebPDecode(stream,length,&configure);
}
if (webp_status != VP8_STATUS_OK)
{
stream=(unsigned char*) RelinquishMagickMemory(stream);
switch (webp_status)
{
case VP8_STATUS_OUT_OF_MEMORY:
{
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
break;
}
case VP8_STATUS_INVALID_PARAM:
{
ThrowReaderException(CorruptImageError,"invalid parameter");
break;
}
case VP8_STATUS_BITSTREAM_ERROR:
{
ThrowReaderException(CorruptImageError,"CorruptImage");
break;
}
case VP8_STATUS_UNSUPPORTED_FEATURE:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
break;
}
case VP8_STATUS_SUSPENDED:
{
ThrowReaderException(CorruptImageError,"decoder suspended");
break;
}
case VP8_STATUS_USER_ABORT:
{
ThrowReaderException(CorruptImageError,"user abort");
break;
}
case VP8_STATUS_NOT_ENOUGH_DATA:
{
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
break;
}
default:
ThrowReaderException(CorruptImageError,"CorruptImage");
}
}
p=(unsigned char *) webp_image->u.RGBA.rgba;
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*q;
register ssize_t
x;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
WebPFreeDecBuffer(webp_image);
stream=(unsigned char*) RelinquishMagickMemory(stream);
(void) CloseBlob(image);
return(image);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r W E B P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterWEBPImage() adds attributes for the WebP 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 RegisterWEBPImage method is:
%
% size_t RegisterWEBPImage(void)
%
*/
ModuleExport size_t RegisterWEBPImage(void)
{
char
version[MaxTextExtent];
MagickInfo
*entry;
*version='\0';
entry=SetMagickInfo("WEBP");
#if defined(MAGICKCORE_WEBP_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadWEBPImage;
entry->encoder=(EncodeImageHandler *) WriteWEBPImage;
(void) FormatLocaleString(version,MaxTextExtent,"libwebp %d.%d.%d[%04X]",
(WebPGetDecoderVersion() >> 16) & 0xff,
(WebPGetDecoderVersion() >> 8) & 0xff,
(WebPGetDecoderVersion() >> 0) & 0xff,WEBP_DECODER_ABI_VERSION);
#endif
entry->description=ConstantString("WebP Image Format");
entry->mime_type=ConstantString("image/webp");
entry->adjoin=MagickFalse;
entry->module=ConstantString("WEBP");
entry->magick=(IsImageFormatHandler *) IsWEBP;
if (*version != '\0')
entry->version=ConstantString(version);
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r W E B P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterWEBPImage() removes format registrations made by the WebP module
% from the list of supported formats.
%
% The format of the UnregisterWEBPImage method is:
%
% UnregisterWEBPImage(void)
%
*/
ModuleExport void UnregisterWEBPImage(void)
{
(void) UnregisterMagickInfo("WEBP");
}
#if defined(MAGICKCORE_WEBP_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e W E B P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteWEBPImage() writes an image in the WebP image format.
%
% The format of the WriteWEBPImage method is:
%
% MagickBooleanType WriteWEBPImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
#if WEBP_DECODER_ABI_VERSION >= 0x0100
static int WebPEncodeProgress(int percent,const WebPPicture* picture)
{
#define EncodeImageTag "Encode/Image"
Image
*image;
MagickBooleanType
status;
image=(Image *) picture->custom_ptr;
status=SetImageProgress(image,EncodeImageTag,percent-1,100);
return(status == MagickFalse ? 0 : 1);
}
#endif
static int WebPEncodeWriter(const unsigned char *stream,size_t length,
const WebPPicture *const picture)
{
Image
*image;
image=(Image *) picture->custom_ptr;
return(length != 0 ? (int) WriteBlob(image,length,stream) : 1);
}
static MagickBooleanType WriteWEBPImage(const ImageInfo *image_info,
Image *image)
{
const char
*value;
int
webp_status;
MagickBooleanType
status;
MemoryInfo
*pixel_info;
register uint32_t
*magick_restrict q;
ssize_t
y;
WebPConfig
configure;
WebPPicture
picture;
WebPAuxStats
statistics;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns > 16383UL) || (image->rows > 16383UL))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
if ((WebPPictureInit(&picture) == 0) || (WebPConfigInit(&configure) == 0))
ThrowWriterException(ResourceLimitError,"UnableToEncodeImageFile");
picture.writer=WebPEncodeWriter;
picture.custom_ptr=(void *) image;
#if WEBP_DECODER_ABI_VERSION >= 0x0100
picture.progress_hook=WebPEncodeProgress;
#endif
picture.stats=(&statistics);
picture.width=(int) image->columns;
picture.height=(int) image->rows;
picture.argb_stride=(int) image->columns;
picture.use_argb=1;
if (image->quality != UndefinedCompressionQuality)
configure.quality=(float) image->quality;
if (image->quality >= 100)
configure.lossless=1;
value=GetImageOption(image_info,"webp:lossless");
if (value != (char *) NULL)
configure.lossless=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:method");
if (value != (char *) NULL)
configure.method=StringToInteger(value);
value=GetImageOption(image_info,"webp:image-hint");
if (value != (char *) NULL)
{
if (LocaleCompare(value,"default") == 0)
configure.image_hint=WEBP_HINT_DEFAULT;
if (LocaleCompare(value,"photo") == 0)
configure.image_hint=WEBP_HINT_PHOTO;
if (LocaleCompare(value,"picture") == 0)
configure.image_hint=WEBP_HINT_PICTURE;
#if WEBP_DECODER_ABI_VERSION >= 0x0200
if (LocaleCompare(value,"graph") == 0)
configure.image_hint=WEBP_HINT_GRAPH;
#endif
}
value=GetImageOption(image_info,"webp:target-size");
if (value != (char *) NULL)
configure.target_size=StringToInteger(value);
value=GetImageOption(image_info,"webp:target-psnr");
if (value != (char *) NULL)
configure.target_PSNR=(float) StringToDouble(value,(char **) NULL);
value=GetImageOption(image_info,"webp:segments");
if (value != (char *) NULL)
configure.segments=StringToInteger(value);
value=GetImageOption(image_info,"webp:sns-strength");
if (value != (char *) NULL)
configure.sns_strength=StringToInteger(value);
value=GetImageOption(image_info,"webp:filter-strength");
if (value != (char *) NULL)
configure.filter_strength=StringToInteger(value);
value=GetImageOption(image_info,"webp:filter-sharpness");
if (value != (char *) NULL)
configure.filter_sharpness=StringToInteger(value);
value=GetImageOption(image_info,"webp:filter-type");
if (value != (char *) NULL)
configure.filter_type=StringToInteger(value);
value=GetImageOption(image_info,"webp:auto-filter");
if (value != (char *) NULL)
configure.autofilter=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:alpha-compression");
if (value != (char *) NULL)
configure.alpha_compression=StringToInteger(value);
value=GetImageOption(image_info,"webp:alpha-filtering");
if (value != (char *) NULL)
configure.alpha_filtering=StringToInteger(value);
value=GetImageOption(image_info,"webp:alpha-quality");
if (value != (char *) NULL)
configure.alpha_quality=StringToInteger(value);
value=GetImageOption(image_info,"webp:pass");
if (value != (char *) NULL)
configure.pass=StringToInteger(value);
value=GetImageOption(image_info,"webp:show-compressed");
if (value != (char *) NULL)
configure.show_compressed=StringToInteger(value);
value=GetImageOption(image_info,"webp:preprocessing");
if (value != (char *) NULL)
configure.preprocessing=StringToInteger(value);
value=GetImageOption(image_info,"webp:partitions");
if (value != (char *) NULL)
configure.partitions=StringToInteger(value);
value=GetImageOption(image_info,"webp:partition-limit");
if (value != (char *) NULL)
configure.partition_limit=StringToInteger(value);
#if WEBP_DECODER_ABI_VERSION >= 0x0201
value=GetImageOption(image_info,"webp:emulate-jpeg-size");
if (value != (char *) NULL)
configure.emulate_jpeg_size=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:low-memory");
if (value != (char *) NULL)
configure.low_memory=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:thread-level");
if (value != (char *) NULL)
configure.thread_level=StringToInteger(value);
#endif
if (WebPValidateConfig(&configure) == 0)
ThrowWriterException(ResourceLimitError,"UnableToEncodeImageFile");
/*
Allocate memory for pixels.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
sizeof(*picture.argb));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
picture.argb=(uint32_t *) GetVirtualMemoryBlob(pixel_info);
/*
Convert image to WebP raster pixels.
*/
q=picture.argb;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(uint32_t) (image->matte != MagickFalse ?
ScaleQuantumToChar(GetPixelAlpha(p)) << 24 : 0xff000000u) |
(ScaleQuantumToChar(GetPixelRed(p)) << 16) |
(ScaleQuantumToChar(GetPixelGreen(p)) << 8) |
(ScaleQuantumToChar(GetPixelBlue(p)));
p++;
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
webp_status=WebPEncode(&configure,&picture);
if (webp_status == 0)
{
const char
*message;
switch (picture.error_code)
{
case VP8_ENC_ERROR_OUT_OF_MEMORY:
{
message="out of memory";
break;
}
case VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY:
{
message="bitstream out of memory";
break;
}
case VP8_ENC_ERROR_NULL_PARAMETER:
{
message="NULL parameter";
break;
}
case VP8_ENC_ERROR_INVALID_CONFIGURATION:
{
message="invalid configuration";
break;
}
case VP8_ENC_ERROR_BAD_DIMENSION:
{
message="bad dimension";
break;
}
case VP8_ENC_ERROR_PARTITION0_OVERFLOW:
{
message="partition 0 overflow (> 512K)";
break;
}
case VP8_ENC_ERROR_PARTITION_OVERFLOW:
{
message="partition overflow (> 16M)";
break;
}
case VP8_ENC_ERROR_BAD_WRITE:
{
message="bad write";
break;
}
case VP8_ENC_ERROR_FILE_TOO_BIG:
{
message="file too big (> 4GB)";
break;
}
#if WEBP_DECODER_ABI_VERSION >= 0x0100
case VP8_ENC_ERROR_USER_ABORT:
{
message="user abort";
break;
}
#endif
default:
{
message="unknown exception";
break;
}
}
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CorruptImageError,(char *) message,"`%s'",image->filename);
}
picture.argb=(uint32_t *) NULL;
WebPPictureFree(&picture);
pixel_info=RelinquishVirtualMemory(pixel_info);
(void) CloseBlob(image);
return(webp_status == 0 ? MagickFalse : MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3199_1 |
crossvul-cpp_data_good_4775_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% RRRR L EEEEE %
% R R L E %
% RRRR L EEE %
% R R L E %
% R R LLLLL EEEEE %
% %
% %
% Read URT RLE Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-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/colormap.h"
#include "magick/colormap-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/pixel.h"
#include "magick/property.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s R L E %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsRLE() returns MagickTrue if the image format type, identified by the
% magick string, is RLE.
%
% The format of the ReadRLEImage method is:
%
% MagickBooleanType IsRLE(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
%
*/
static MagickBooleanType IsRLE(const unsigned char *magick,const size_t length)
{
if (length < 2)
return(MagickFalse);
if (memcmp(magick,"\122\314",2) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadRLEImage() reads a run-length encoded Utah Raster Toolkit
% image file and returns it. It allocates the memory necessary for the new
% Image structure and returns a pointer to the new image.
%
% The format of the ReadRLEImage method is:
%
% Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
%
*/
static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
IndexPacket
index;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
pixel_info_length;
ssize_t
count,
offset,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->matte=flags & 0x04 ? MagickTrue : MagickFalse;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) ||
((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate RLE pixels.
*/
if (image->matte != MagickFalse)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
MagickMax(number_planes_filled,4)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*
MagickMax(number_planes_filled,4);
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->matte == MagickFalse)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if ((offset < 0) ||
(offset+((size_t) operand*number_planes) > pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
operand++;
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
if ((offset < 0) ||
(offset+((size_t) operand*number_planes) > pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (IsValidColormapIndex(image,*p & mask,&index,exception) ==
MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
if (IsValidColormapIndex(image,(size_t) (x*map_length+
(*p & mask)),&index,exception) == MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p);
image->colormap[i].green=ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->matte == MagickFalse)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*p++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelRed(q,image->colormap[(ssize_t) index].red);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelGreen(q,image->colormap[(ssize_t) index].green);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelBlue(q,image->colormap[(ssize_t) index].blue);
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelPacket *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterRLEImage() adds attributes for the RLE image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterRLEImage method is:
%
% size_t RegisterRLEImage(void)
%
*/
ModuleExport size_t RegisterRLEImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("RLE");
entry->decoder=(DecodeImageHandler *) ReadRLEImage;
entry->magick=(IsImageFormatHandler *) IsRLE;
entry->adjoin=MagickFalse;
entry->description=ConstantString("Utah Run length encoded image");
entry->module=ConstantString("RLE");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterRLEImage() removes format registrations made by the
% RLE module from the list of supported formats.
%
% The format of the UnregisterRLEImage method is:
%
% UnregisterRLEImage(void)
%
*/
ModuleExport void UnregisterRLEImage(void)
{
(void) UnregisterMagickInfo("RLE");
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4775_1 |
crossvul-cpp_data_bad_2197_0 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2001, 2007 by the Massachusetts Institute of Technology.
* Copyright 1993 by OpenVision Technologies, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appears in all copies and
* that both that copyright notice and this permission notice appear in
* supporting documentation, and that the name of OpenVision not be used
* in advertising or publicity pertaining to distribution of the software
* without specific, written prior permission. OpenVision makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
* OPENVISION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL OPENVISION BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
* USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Copyright (C) 1998 by the FundsXpress, INC.
*
* All rights reserved.
*
* Export of this software from the United States of America may require
* a specific license from the United States Government. It is the
* responsibility of any person or organization contemplating export to
* obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of FundsXpress. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. FundsXpress makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "gssapiP_krb5.h"
#ifdef HAVE_MEMORY_H
#include <memory.h>
#endif
#include <assert.h>
/* message_buffer is an input if SIGN, output if SEAL, and ignored if DEL_CTX
conf_state is only valid if SEAL. */
static OM_uint32
kg_unseal_v1(context, minor_status, ctx, ptr, bodysize, message_buffer,
conf_state, qop_state, toktype)
krb5_context context;
OM_uint32 *minor_status;
krb5_gss_ctx_id_rec *ctx;
unsigned char *ptr;
int bodysize;
gss_buffer_t message_buffer;
int *conf_state;
gss_qop_t *qop_state;
int toktype;
{
krb5_error_code code;
int conflen = 0;
int signalg;
int sealalg;
gss_buffer_desc token;
krb5_checksum cksum;
krb5_checksum md5cksum;
krb5_data plaind;
char *data_ptr;
unsigned char *plain;
unsigned int cksum_len = 0;
size_t plainlen;
int direction;
krb5_ui_4 seqnum;
OM_uint32 retval;
size_t sumlen;
krb5_keyusage sign_usage = KG_USAGE_SIGN;
if (toktype == KG_TOK_SEAL_MSG) {
message_buffer->length = 0;
message_buffer->value = NULL;
}
/* get the sign and seal algorithms */
signalg = ptr[0] + (ptr[1]<<8);
sealalg = ptr[2] + (ptr[3]<<8);
/* Sanity checks */
if ((ptr[4] != 0xff) || (ptr[5] != 0xff)) {
*minor_status = 0;
return GSS_S_DEFECTIVE_TOKEN;
}
if ((toktype != KG_TOK_SEAL_MSG) &&
(sealalg != 0xffff)) {
*minor_status = 0;
return GSS_S_DEFECTIVE_TOKEN;
}
/* in the current spec, there is only one valid seal algorithm per
key type, so a simple comparison is ok */
if ((toktype == KG_TOK_SEAL_MSG) &&
!((sealalg == 0xffff) ||
(sealalg == ctx->sealalg))) {
*minor_status = 0;
return GSS_S_DEFECTIVE_TOKEN;
}
/* there are several mappings of seal algorithms to sign algorithms,
but few enough that we can try them all. */
if ((ctx->sealalg == SEAL_ALG_NONE && signalg > 1) ||
(ctx->sealalg == SEAL_ALG_1 && signalg != SGN_ALG_3) ||
(ctx->sealalg == SEAL_ALG_DES3KD &&
signalg != SGN_ALG_HMAC_SHA1_DES3_KD)||
(ctx->sealalg == SEAL_ALG_MICROSOFT_RC4 &&
signalg != SGN_ALG_HMAC_MD5)) {
*minor_status = 0;
return GSS_S_DEFECTIVE_TOKEN;
}
switch (signalg) {
case SGN_ALG_DES_MAC_MD5:
case SGN_ALG_MD2_5:
case SGN_ALG_HMAC_MD5:
cksum_len = 8;
if (toktype != KG_TOK_SEAL_MSG)
sign_usage = 15;
break;
case SGN_ALG_3:
cksum_len = 16;
break;
case SGN_ALG_HMAC_SHA1_DES3_KD:
cksum_len = 20;
break;
default:
*minor_status = 0;
return GSS_S_DEFECTIVE_TOKEN;
}
/* get the token parameters */
if ((code = kg_get_seq_num(context, ctx->seq, ptr+14, ptr+6, &direction,
&seqnum))) {
*minor_status = code;
return(GSS_S_BAD_SIG);
}
/* decode the message, if SEAL */
if (toktype == KG_TOK_SEAL_MSG) {
size_t tmsglen = bodysize-(14+cksum_len);
if (sealalg != 0xffff) {
if ((plain = (unsigned char *) xmalloc(tmsglen)) == NULL) {
*minor_status = ENOMEM;
return(GSS_S_FAILURE);
}
if (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4) {
unsigned char bigend_seqnum[4];
krb5_keyblock *enc_key;
int i;
store_32_be(seqnum, bigend_seqnum);
code = krb5_k_key_keyblock(context, ctx->enc, &enc_key);
if (code)
{
xfree(plain);
*minor_status = code;
return(GSS_S_FAILURE);
}
assert (enc_key->length == 16);
for (i = 0; i <= 15; i++)
((char *) enc_key->contents)[i] ^=0xf0;
code = kg_arcfour_docrypt (enc_key, 0,
&bigend_seqnum[0], 4,
ptr+14+cksum_len, tmsglen,
plain);
krb5_free_keyblock (context, enc_key);
} else {
code = kg_decrypt(context, ctx->enc, KG_USAGE_SEAL, NULL,
ptr+14+cksum_len, plain, tmsglen);
}
if (code) {
xfree(plain);
*minor_status = code;
return(GSS_S_FAILURE);
}
} else {
plain = ptr+14+cksum_len;
}
plainlen = tmsglen;
conflen = kg_confounder_size(context, ctx->enc->keyblock.enctype);
token.length = tmsglen - conflen - plain[tmsglen-1];
if (token.length) {
if ((token.value = (void *) gssalloc_malloc(token.length)) == NULL) {
if (sealalg != 0xffff)
xfree(plain);
*minor_status = ENOMEM;
return(GSS_S_FAILURE);
}
memcpy(token.value, plain+conflen, token.length);
} else {
token.value = NULL;
}
} else if (toktype == KG_TOK_SIGN_MSG) {
token = *message_buffer;
plain = token.value;
plainlen = token.length;
} else {
token.length = 0;
token.value = NULL;
plain = token.value;
plainlen = token.length;
}
/* compute the checksum of the message */
/* initialize the the cksum */
switch (signalg) {
case SGN_ALG_DES_MAC_MD5:
case SGN_ALG_MD2_5:
case SGN_ALG_DES_MAC:
case SGN_ALG_3:
md5cksum.checksum_type = CKSUMTYPE_RSA_MD5;
break;
case SGN_ALG_HMAC_MD5:
md5cksum.checksum_type = CKSUMTYPE_HMAC_MD5_ARCFOUR;
break;
case SGN_ALG_HMAC_SHA1_DES3_KD:
md5cksum.checksum_type = CKSUMTYPE_HMAC_SHA1_DES3;
break;
default:
abort ();
}
code = krb5_c_checksum_length(context, md5cksum.checksum_type, &sumlen);
if (code)
return(code);
md5cksum.length = sumlen;
switch (signalg) {
case SGN_ALG_DES_MAC_MD5:
case SGN_ALG_3:
/* compute the checksum of the message */
/* 8 = bytes of token body to be checksummed according to spec */
if (! (data_ptr = xmalloc(8 + plainlen))) {
if (sealalg != 0xffff)
xfree(plain);
if (toktype == KG_TOK_SEAL_MSG)
gssalloc_free(token.value);
*minor_status = ENOMEM;
return(GSS_S_FAILURE);
}
(void) memcpy(data_ptr, ptr-2, 8);
(void) memcpy(data_ptr+8, plain, plainlen);
plaind.length = 8 + plainlen;
plaind.data = data_ptr;
code = krb5_k_make_checksum(context, md5cksum.checksum_type,
ctx->seq, sign_usage,
&plaind, &md5cksum);
xfree(data_ptr);
if (code) {
if (toktype == KG_TOK_SEAL_MSG)
gssalloc_free(token.value);
*minor_status = code;
return(GSS_S_FAILURE);
}
code = kg_encrypt_inplace(context, ctx->seq, KG_USAGE_SEAL,
(g_OID_equal(ctx->mech_used,
gss_mech_krb5_old) ?
ctx->seq->keyblock.contents : NULL),
md5cksum.contents, 16);
if (code) {
krb5_free_checksum_contents(context, &md5cksum);
if (toktype == KG_TOK_SEAL_MSG)
gssalloc_free(token.value);
*minor_status = code;
return GSS_S_FAILURE;
}
if (signalg == 0)
cksum.length = 8;
else
cksum.length = 16;
cksum.contents = md5cksum.contents + 16 - cksum.length;
code = k5_bcmp(cksum.contents, ptr + 14, cksum.length);
break;
case SGN_ALG_MD2_5:
if (!ctx->seed_init &&
(code = kg_make_seed(context, ctx->subkey, ctx->seed))) {
krb5_free_checksum_contents(context, &md5cksum);
if (sealalg != 0xffff)
xfree(plain);
if (toktype == KG_TOK_SEAL_MSG)
gssalloc_free(token.value);
*minor_status = code;
return GSS_S_FAILURE;
}
if (! (data_ptr = xmalloc(sizeof(ctx->seed) + 8 + plainlen))) {
krb5_free_checksum_contents(context, &md5cksum);
if (sealalg == 0)
xfree(plain);
if (toktype == KG_TOK_SEAL_MSG)
gssalloc_free(token.value);
*minor_status = ENOMEM;
return(GSS_S_FAILURE);
}
(void) memcpy(data_ptr, ptr-2, 8);
(void) memcpy(data_ptr+8, ctx->seed, sizeof(ctx->seed));
(void) memcpy(data_ptr+8+sizeof(ctx->seed), plain, plainlen);
plaind.length = 8 + sizeof(ctx->seed) + plainlen;
plaind.data = data_ptr;
krb5_free_checksum_contents(context, &md5cksum);
code = krb5_k_make_checksum(context, md5cksum.checksum_type,
ctx->seq, sign_usage,
&plaind, &md5cksum);
xfree(data_ptr);
if (code) {
if (sealalg == 0)
xfree(plain);
if (toktype == KG_TOK_SEAL_MSG)
gssalloc_free(token.value);
*minor_status = code;
return(GSS_S_FAILURE);
}
code = k5_bcmp(md5cksum.contents, ptr + 14, 8);
/* Falls through to defective-token?? */
default:
*minor_status = 0;
return(GSS_S_DEFECTIVE_TOKEN);
case SGN_ALG_HMAC_SHA1_DES3_KD:
case SGN_ALG_HMAC_MD5:
/* compute the checksum of the message */
/* 8 = bytes of token body to be checksummed according to spec */
if (! (data_ptr = xmalloc(8 + plainlen))) {
if (sealalg != 0xffff)
xfree(plain);
if (toktype == KG_TOK_SEAL_MSG)
gssalloc_free(token.value);
*minor_status = ENOMEM;
return(GSS_S_FAILURE);
}
(void) memcpy(data_ptr, ptr-2, 8);
(void) memcpy(data_ptr+8, plain, plainlen);
plaind.length = 8 + plainlen;
plaind.data = data_ptr;
code = krb5_k_make_checksum(context, md5cksum.checksum_type,
ctx->seq, sign_usage,
&plaind, &md5cksum);
xfree(data_ptr);
if (code) {
if (toktype == KG_TOK_SEAL_MSG)
gssalloc_free(token.value);
*minor_status = code;
return(GSS_S_FAILURE);
}
code = k5_bcmp(md5cksum.contents, ptr + 14, cksum_len);
break;
}
krb5_free_checksum_contents(context, &md5cksum);
if (sealalg != 0xffff)
xfree(plain);
/* compare the computed checksum against the transmitted checksum */
if (code) {
if (toktype == KG_TOK_SEAL_MSG)
gssalloc_free(token.value);
*minor_status = 0;
return(GSS_S_BAD_SIG);
}
/* it got through unscathed. Make sure the context is unexpired */
if (toktype == KG_TOK_SEAL_MSG)
*message_buffer = token;
if (conf_state)
*conf_state = (sealalg != 0xffff);
if (qop_state)
*qop_state = GSS_C_QOP_DEFAULT;
/* do sequencing checks */
if ((ctx->initiate && direction != 0xff) ||
(!ctx->initiate && direction != 0)) {
if (toktype == KG_TOK_SEAL_MSG) {
gssalloc_free(token.value);
message_buffer->value = NULL;
message_buffer->length = 0;
}
*minor_status = (OM_uint32)G_BAD_DIRECTION;
return(GSS_S_BAD_SIG);
}
retval = g_order_check(&(ctx->seqstate), (gssint_uint64)seqnum);
/* success or ordering violation */
*minor_status = 0;
return(retval);
}
/* message_buffer is an input if SIGN, output if SEAL, and ignored if DEL_CTX
conf_state is only valid if SEAL. */
OM_uint32
kg_unseal(minor_status, context_handle, input_token_buffer,
message_buffer, conf_state, qop_state, toktype)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
gss_buffer_t input_token_buffer;
gss_buffer_t message_buffer;
int *conf_state;
gss_qop_t *qop_state;
int toktype;
{
krb5_gss_ctx_id_rec *ctx;
unsigned char *ptr;
unsigned int bodysize;
int err;
int toktype2;
int vfyflags = 0;
OM_uint32 ret;
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (! ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return(GSS_S_NO_CONTEXT);
}
/* parse the token, leave the data in message_buffer, setting conf_state */
/* verify the header */
ptr = (unsigned char *) input_token_buffer->value;
err = g_verify_token_header(ctx->mech_used,
&bodysize, &ptr, -1,
input_token_buffer->length,
vfyflags);
if (err) {
*minor_status = err;
return GSS_S_DEFECTIVE_TOKEN;
}
if (bodysize < 2) {
*minor_status = (OM_uint32)G_BAD_TOK_HEADER;
return GSS_S_DEFECTIVE_TOKEN;
}
toktype2 = load_16_be(ptr);
ptr += 2;
bodysize -= 2;
switch (toktype2) {
case KG2_TOK_MIC_MSG:
case KG2_TOK_WRAP_MSG:
case KG2_TOK_DEL_CTX:
ret = gss_krb5int_unseal_token_v3(&ctx->k5_context, minor_status, ctx,
ptr, bodysize, message_buffer,
conf_state, qop_state, toktype);
break;
case KG_TOK_MIC_MSG:
case KG_TOK_WRAP_MSG:
case KG_TOK_DEL_CTX:
ret = kg_unseal_v1(ctx->k5_context, minor_status, ctx, ptr, bodysize,
message_buffer, conf_state, qop_state,
toktype);
break;
default:
*minor_status = (OM_uint32)G_BAD_TOK_HEADER;
ret = GSS_S_DEFECTIVE_TOKEN;
break;
}
if (ret != 0)
save_error_info (*minor_status, ctx->k5_context);
return ret;
}
OM_uint32 KRB5_CALLCONV
krb5_gss_unwrap(minor_status, context_handle,
input_message_buffer, output_message_buffer,
conf_state, qop_state)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
gss_buffer_t input_message_buffer;
gss_buffer_t output_message_buffer;
int *conf_state;
gss_qop_t *qop_state;
{
OM_uint32 rstat;
rstat = kg_unseal(minor_status, context_handle,
input_message_buffer, output_message_buffer,
conf_state, qop_state, KG_TOK_WRAP_MSG);
return(rstat);
}
OM_uint32 KRB5_CALLCONV
krb5_gss_verify_mic(minor_status, context_handle,
message_buffer, token_buffer,
qop_state)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
gss_buffer_t message_buffer;
gss_buffer_t token_buffer;
gss_qop_t *qop_state;
{
OM_uint32 rstat;
rstat = kg_unseal(minor_status, context_handle,
token_buffer, message_buffer,
NULL, qop_state, KG_TOK_MIC_MSG);
return(rstat);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2197_0 |
crossvul-cpp_data_bad_4787_24 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% H H DDDD RRRR %
% H H D D R R %
% HHHHH D D RRRR %
% H H D D R R %
% H H DDDD R R %
% %
% %
% Read/Write Radiance RGBE Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.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/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.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/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteHDRImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s H D R %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsHDR() returns MagickTrue if the image format type, identified by the
% magick string, is Radiance RGBE image format.
%
% The format of the IsHDR method is:
%
% MagickBooleanType IsHDR(const unsigned char *magick,
% const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsHDR(const unsigned char *magick,
const size_t length)
{
if (length < 10)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"#?RADIANCE",10) == 0)
return(MagickTrue);
if (LocaleNCompare((const char *) magick,"#?RGBE",6) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadHDRImage() reads the Radiance RGBE image format and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadHDRImage method is:
%
% Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
format[MaxTextExtent],
keyword[MaxTextExtent],
tag[MaxTextExtent],
value[MaxTextExtent];
double
gamma;
Image
*image;
int
c;
MagickBooleanType
status,
value_expected;
register PixelPacket
*q;
register unsigned char
*p;
register ssize_t
i,
x;
ssize_t
count,
y;
unsigned char
*end,
pixel[4],
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Decode image header.
*/
image->columns=0;
image->rows=0;
*format='\0';
c=ReadBlobByte(image);
if (c == EOF)
{
image=DestroyImage(image);
return((Image *) NULL);
}
while (isgraph(c) && (image->columns == 0) && (image->rows == 0))
{
if (c == (int) '#')
{
char
*comment;
register char
*p;
size_t
length;
/*
Read comment-- any text between # and end-of-line.
*/
length=MaxTextExtent;
comment=AcquireString((char *) NULL);
for (p=comment; comment != (char *) NULL; p++)
{
c=ReadBlobByte(image);
if ((c == EOF) || (c == (int) '\n'))
break;
if ((size_t) (p-comment+1) >= length)
{
*p='\0';
length<<=1;
comment=(char *) ResizeQuantumMemory(comment,length+
MaxTextExtent,sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=(char) c;
}
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
*p='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
c=ReadBlobByte(image);
}
else
if (isalnum(c) == MagickFalse)
c=ReadBlobByte(image);
else
{
register char
*p;
/*
Determine a keyword and its value.
*/
p=keyword;
do
{
if ((size_t) (p-keyword) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
} while (isalnum(c) || (c == '_'));
*p='\0';
value_expected=MagickFalse;
while ((isspace((int) ((unsigned char) c)) != 0) || (c == '='))
{
if (c == '=')
value_expected=MagickTrue;
c=ReadBlobByte(image);
}
if (LocaleCompare(keyword,"Y") == 0)
value_expected=MagickTrue;
if (value_expected == MagickFalse)
continue;
p=value;
while ((c != '\n') && (c != '\0'))
{
if ((size_t) (p-value) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"format") == 0)
{
(void) CopyMagickString(format,value,MaxTextExtent);
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
image->gamma=StringToDouble(value,(char **) NULL);
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"primaries") == 0)
{
float
chromaticity[6],
white_point[2];
(void) sscanf(value,"%g %g %g %g %g %g %g %g",
&chromaticity[0],&chromaticity[1],&chromaticity[2],
&chromaticity[3],&chromaticity[4],&chromaticity[5],
&white_point[0],&white_point[1]);
image->chromaticity.red_primary.x=chromaticity[0];
image->chromaticity.red_primary.y=chromaticity[1];
image->chromaticity.green_primary.x=chromaticity[2];
image->chromaticity.green_primary.y=chromaticity[3];
image->chromaticity.blue_primary.x=chromaticity[4];
image->chromaticity.blue_primary.y=chromaticity[5];
image->chromaticity.white_point.x=white_point[0],
image->chromaticity.white_point.y=white_point[1];
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value);
break;
}
case 'Y':
case 'y':
{
if (strcmp(keyword,"Y") == 0)
{
int
height,
width;
(void) sscanf(value,"%d +X %d",&height,&width);
image->columns=(size_t) width;
image->rows=(size_t) height;
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value);
break;
}
default:
{
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value);
break;
}
}
}
if ((image->columns == 0) && (image->rows == 0))
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
if ((LocaleCompare(format,"32-bit_rle_rgbe") != 0) &&
(LocaleCompare(format,"32-bit_rle_xyze") != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
(void) SetImageColorspace(image,RGBColorspace);
if (LocaleCompare(format,"32-bit_rle_xyze") == 0)
(void) SetImageColorspace(image,XYZColorspace);
image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ?
NoCompression : RLECompression;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read RGBE (red+green+blue+exponent) pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
if (image->compression != RLECompression)
{
count=ReadBlob(image,4*image->columns*sizeof(*pixels),pixels);
if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))
break;
}
else
{
count=ReadBlob(image,4*sizeof(*pixel),pixel);
if (count != 4)
break;
if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns)
{
(void) memcpy(pixels,pixel,4*sizeof(*pixel));
count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4);
image->compression=NoCompression;
}
else
{
p=pixels;
for (i=0; i < 4; i++)
{
end=&pixels[(i+1)*image->columns];
while (p < end)
{
count=ReadBlob(image,2*sizeof(*pixel),pixel);
if (count < 1)
break;
if (pixel[0] > 128)
{
count=(ssize_t) pixel[0]-128;
if ((count == 0) || (count > (ssize_t) (end-p)))
break;
while (count-- > 0)
*p++=pixel[1];
}
else
{
count=(ssize_t) pixel[0];
if ((count == 0) || (count > (ssize_t) (end-p)))
break;
*p++=pixel[1];
if (--count > 0)
{
count=ReadBlob(image,(size_t) count*sizeof(*p),p);
if (count < 1)
break;
p+=count;
}
}
}
}
}
}
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->compression == RLECompression)
{
pixel[0]=pixels[x];
pixel[1]=pixels[x+image->columns];
pixel[2]=pixels[x+2*image->columns];
pixel[3]=pixels[x+3*image->columns];
}
else
{
pixel[0]=pixels[i++];
pixel[1]=pixels[i++];
pixel[2]=pixels[i++];
pixel[3]=pixels[i++];
}
SetPixelRed(q,0);
SetPixelGreen(q,0);
SetPixelBlue(q,0);
if (pixel[3] != 0)
{
gamma=pow(2.0,pixel[3]-(128.0+8.0));
SetPixelRed(q,ClampToQuantum(QuantumRange*gamma*pixel[0]));
SetPixelGreen(q,ClampToQuantum(QuantumRange*gamma*pixel[1]));
SetPixelBlue(q,ClampToQuantum(QuantumRange*gamma*pixel[2]));
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterHDRImage() adds attributes for the Radiance RGBE image format to the
% list of supported formats. The attributes include the image format tag, a
% method to read and/or write the format, whether the format supports the
% saving of more than one frame to the same file or blob, whether the format
% supports native in-memory I/O, and a brief description of the format.
%
% The format of the RegisterHDRImage method is:
%
% size_t RegisterHDRImage(void)
%
*/
ModuleExport size_t RegisterHDRImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("HDR");
entry->decoder=(DecodeImageHandler *) ReadHDRImage;
entry->encoder=(EncodeImageHandler *) WriteHDRImage;
entry->description=ConstantString("Radiance RGBE image format");
entry->module=ConstantString("HDR");
entry->magick=(IsImageFormatHandler *) IsHDR;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterHDRImage() removes format registrations made by the
% HDR module from the list of supported formats.
%
% The format of the UnregisterHDRImage method is:
%
% UnregisterHDRImage(void)
%
*/
ModuleExport void UnregisterHDRImage(void)
{
(void) UnregisterMagickInfo("HDR");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteHDRImage() writes an image in the Radience RGBE image format.
%
% The format of the WriteHDRImage method is:
%
% MagickBooleanType WriteHDRImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static size_t HDRWriteRunlengthPixels(Image *image,unsigned char *pixels)
{
#define MinimumRunlength 4
register size_t
p,
q;
size_t
runlength;
ssize_t
count,
previous_count;
unsigned char
pixel[2];
for (p=0; p < image->columns; )
{
q=p;
runlength=0;
previous_count=0;
while ((runlength < MinimumRunlength) && (q < image->columns))
{
q+=runlength;
previous_count=(ssize_t) runlength;
runlength=1;
while ((pixels[q] == pixels[q+runlength]) &&
((q+runlength) < image->columns) && (runlength < 127))
runlength++;
}
if ((previous_count > 1) && (previous_count == (ssize_t) (q-p)))
{
pixel[0]=(unsigned char) (128+previous_count);
pixel[1]=pixels[p];
if (WriteBlob(image,2*sizeof(*pixel),pixel) < 1)
break;
p=q;
}
while (p < q)
{
count=(ssize_t) (q-p);
if (count > 128)
count=128;
pixel[0]=(unsigned char) count;
if (WriteBlob(image,sizeof(*pixel),pixel) < 1)
break;
if (WriteBlob(image,(size_t) count*sizeof(*pixel),&pixels[p]) < 1)
break;
p+=count;
}
if (runlength >= MinimumRunlength)
{
pixel[0]=(unsigned char) (128+runlength);
pixel[1]=pixels[q];
if (WriteBlob(image,2*sizeof(*pixel),pixel) < 1)
break;
p+=runlength;
}
}
return(p);
}
static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image)
{
char
header[MaxTextExtent];
const char
*property;
MagickBooleanType
status;
register const PixelPacket
*p;
register ssize_t
i,
x;
size_t
length;
ssize_t
count,
y;
unsigned char
pixel[4],
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
if (IsRGBColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Write header.
*/
(void) ResetMagickMemory(header,' ',MaxTextExtent);
length=CopyMagickString(header,"#?RGBE\n",MaxTextExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
property=GetImageProperty(image,"comment");
if ((property != (const char *) NULL) &&
(strchr(property,'\n') == (char *) NULL))
{
count=FormatLocaleString(header,MaxTextExtent,"#%s\n",property);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
property=GetImageProperty(image,"hdr:exposure");
if (property != (const char *) NULL)
{
count=FormatLocaleString(header,MaxTextExtent,"EXPOSURE=%g\n",
atof(property));
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
if (image->gamma != 0.0)
{
count=FormatLocaleString(header,MaxTextExtent,"GAMMA=%g\n",image->gamma);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
count=FormatLocaleString(header,MaxTextExtent,
"PRIMARIES=%g %g %g %g %g %g %g %g\n",
image->chromaticity.red_primary.x,image->chromaticity.red_primary.y,
image->chromaticity.green_primary.x,image->chromaticity.green_primary.y,
image->chromaticity.blue_primary.x,image->chromaticity.blue_primary.y,
image->chromaticity.white_point.x,image->chromaticity.white_point.y);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
length=CopyMagickString(header,"FORMAT=32-bit_rle_rgbe\n\n",MaxTextExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
count=FormatLocaleString(header,MaxTextExtent,"-Y %.20g +X %.20g\n",
(double) image->rows,(double) image->columns);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
/*
Write HDR pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
pixel[0]=2;
pixel[1]=2;
pixel[2]=(unsigned char) (image->columns >> 8);
pixel[3]=(unsigned char) (image->columns & 0xff);
count=WriteBlob(image,4*sizeof(*pixel),pixel);
if (count != (ssize_t) (4*sizeof(*pixel)))
break;
}
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
pixel[0]=0;
pixel[1]=0;
pixel[2]=0;
pixel[3]=0;
gamma=QuantumScale*GetPixelRed(p);
if ((QuantumScale*GetPixelGreen(p)) > gamma)
gamma=QuantumScale*GetPixelGreen(p);
if ((QuantumScale*GetPixelBlue(p)) > gamma)
gamma=QuantumScale*GetPixelBlue(p);
if (gamma > MagickEpsilon)
{
int
exponent;
gamma=frexp(gamma,&exponent)*256.0/gamma;
pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(p));
pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(p));
pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(p));
pixel[3]=(unsigned char) (exponent+128);
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
pixels[x]=pixel[0];
pixels[x+image->columns]=pixel[1];
pixels[x+2*image->columns]=pixel[2];
pixels[x+3*image->columns]=pixel[3];
}
else
{
pixels[i++]=pixel[0];
pixels[i++]=pixel[1];
pixels[i++]=pixel[2];
pixels[i++]=pixel[3];
}
p++;
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
for (i=0; i < 4; i++)
length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]);
}
else
{
count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels);
if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))
break;
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4787_24 |
crossvul-cpp_data_good_2915_0 | /*
* message.c - synchronous message handling
*
* Released under the GPLv2 only.
* SPDX-License-Identifier: GPL-2.0
*/
#include <linux/pci.h> /* for scatterlist macros */
#include <linux/usb.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/timer.h>
#include <linux/ctype.h>
#include <linux/nls.h>
#include <linux/device.h>
#include <linux/scatterlist.h>
#include <linux/usb/cdc.h>
#include <linux/usb/quirks.h>
#include <linux/usb/hcd.h> /* for usbcore internals */
#include <asm/byteorder.h>
#include "usb.h"
static void cancel_async_set_config(struct usb_device *udev);
struct api_context {
struct completion done;
int status;
};
static void usb_api_blocking_completion(struct urb *urb)
{
struct api_context *ctx = urb->context;
ctx->status = urb->status;
complete(&ctx->done);
}
/*
* Starts urb and waits for completion or timeout. Note that this call
* is NOT interruptible. Many device driver i/o requests should be
* interruptible and therefore these drivers should implement their
* own interruptible routines.
*/
static int usb_start_wait_urb(struct urb *urb, int timeout, int *actual_length)
{
struct api_context ctx;
unsigned long expire;
int retval;
init_completion(&ctx.done);
urb->context = &ctx;
urb->actual_length = 0;
retval = usb_submit_urb(urb, GFP_NOIO);
if (unlikely(retval))
goto out;
expire = timeout ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT;
if (!wait_for_completion_timeout(&ctx.done, expire)) {
usb_kill_urb(urb);
retval = (ctx.status == -ENOENT ? -ETIMEDOUT : ctx.status);
dev_dbg(&urb->dev->dev,
"%s timed out on ep%d%s len=%u/%u\n",
current->comm,
usb_endpoint_num(&urb->ep->desc),
usb_urb_dir_in(urb) ? "in" : "out",
urb->actual_length,
urb->transfer_buffer_length);
} else
retval = ctx.status;
out:
if (actual_length)
*actual_length = urb->actual_length;
usb_free_urb(urb);
return retval;
}
/*-------------------------------------------------------------------*/
/* returns status (negative) or length (positive) */
static int usb_internal_control_msg(struct usb_device *usb_dev,
unsigned int pipe,
struct usb_ctrlrequest *cmd,
void *data, int len, int timeout)
{
struct urb *urb;
int retv;
int length;
urb = usb_alloc_urb(0, GFP_NOIO);
if (!urb)
return -ENOMEM;
usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
len, usb_api_blocking_completion, NULL);
retv = usb_start_wait_urb(urb, timeout, &length);
if (retv < 0)
return retv;
else
return length;
}
/**
* usb_control_msg - Builds a control urb, sends it off and waits for completion
* @dev: pointer to the usb device to send the message to
* @pipe: endpoint "pipe" to send the message to
* @request: USB message request value
* @requesttype: USB message request type value
* @value: USB message value
* @index: USB message index value
* @data: pointer to the data to send
* @size: length in bytes of the data to send
* @timeout: time in msecs to wait for the message to complete before timing
* out (if 0 the wait is forever)
*
* Context: !in_interrupt ()
*
* This function sends a simple control message to a specified endpoint and
* waits for the message to complete, or timeout.
*
* Don't use this function from within an interrupt context. If you need
* an asynchronous message, or need to send a message from within interrupt
* context, use usb_submit_urb(). If a thread in your driver uses this call,
* make sure your disconnect() method can wait for it to complete. Since you
* don't have a handle on the URB used, you can't cancel the request.
*
* Return: If successful, the number of bytes transferred. Otherwise, a negative
* error number.
*/
int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request,
__u8 requesttype, __u16 value, __u16 index, void *data,
__u16 size, int timeout)
{
struct usb_ctrlrequest *dr;
int ret;
dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
if (!dr)
return -ENOMEM;
dr->bRequestType = requesttype;
dr->bRequest = request;
dr->wValue = cpu_to_le16(value);
dr->wIndex = cpu_to_le16(index);
dr->wLength = cpu_to_le16(size);
ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
kfree(dr);
return ret;
}
EXPORT_SYMBOL_GPL(usb_control_msg);
/**
* usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
* @usb_dev: pointer to the usb device to send the message to
* @pipe: endpoint "pipe" to send the message to
* @data: pointer to the data to send
* @len: length in bytes of the data to send
* @actual_length: pointer to a location to put the actual length transferred
* in bytes
* @timeout: time in msecs to wait for the message to complete before
* timing out (if 0 the wait is forever)
*
* Context: !in_interrupt ()
*
* This function sends a simple interrupt message to a specified endpoint and
* waits for the message to complete, or timeout.
*
* Don't use this function from within an interrupt context. If you need
* an asynchronous message, or need to send a message from within interrupt
* context, use usb_submit_urb() If a thread in your driver uses this call,
* make sure your disconnect() method can wait for it to complete. Since you
* don't have a handle on the URB used, you can't cancel the request.
*
* Return:
* If successful, 0. Otherwise a negative error number. The number of actual
* bytes transferred will be stored in the @actual_length parameter.
*/
int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
void *data, int len, int *actual_length, int timeout)
{
return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout);
}
EXPORT_SYMBOL_GPL(usb_interrupt_msg);
/**
* usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
* @usb_dev: pointer to the usb device to send the message to
* @pipe: endpoint "pipe" to send the message to
* @data: pointer to the data to send
* @len: length in bytes of the data to send
* @actual_length: pointer to a location to put the actual length transferred
* in bytes
* @timeout: time in msecs to wait for the message to complete before
* timing out (if 0 the wait is forever)
*
* Context: !in_interrupt ()
*
* This function sends a simple bulk message to a specified endpoint
* and waits for the message to complete, or timeout.
*
* Don't use this function from within an interrupt context. If you need
* an asynchronous message, or need to send a message from within interrupt
* context, use usb_submit_urb() If a thread in your driver uses this call,
* make sure your disconnect() method can wait for it to complete. Since you
* don't have a handle on the URB used, you can't cancel the request.
*
* Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl,
* users are forced to abuse this routine by using it to submit URBs for
* interrupt endpoints. We will take the liberty of creating an interrupt URB
* (with the default interval) if the target is an interrupt endpoint.
*
* Return:
* If successful, 0. Otherwise a negative error number. The number of actual
* bytes transferred will be stored in the @actual_length parameter.
*
*/
int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
void *data, int len, int *actual_length, int timeout)
{
struct urb *urb;
struct usb_host_endpoint *ep;
ep = usb_pipe_endpoint(usb_dev, pipe);
if (!ep || len < 0)
return -EINVAL;
urb = usb_alloc_urb(0, GFP_KERNEL);
if (!urb)
return -ENOMEM;
if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_INT) {
pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
usb_fill_int_urb(urb, usb_dev, pipe, data, len,
usb_api_blocking_completion, NULL,
ep->desc.bInterval);
} else
usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
usb_api_blocking_completion, NULL);
return usb_start_wait_urb(urb, timeout, actual_length);
}
EXPORT_SYMBOL_GPL(usb_bulk_msg);
/*-------------------------------------------------------------------*/
static void sg_clean(struct usb_sg_request *io)
{
if (io->urbs) {
while (io->entries--)
usb_free_urb(io->urbs[io->entries]);
kfree(io->urbs);
io->urbs = NULL;
}
io->dev = NULL;
}
static void sg_complete(struct urb *urb)
{
struct usb_sg_request *io = urb->context;
int status = urb->status;
spin_lock(&io->lock);
/* In 2.5 we require hcds' endpoint queues not to progress after fault
* reports, until the completion callback (this!) returns. That lets
* device driver code (like this routine) unlink queued urbs first,
* if it needs to, since the HC won't work on them at all. So it's
* not possible for page N+1 to overwrite page N, and so on.
*
* That's only for "hard" faults; "soft" faults (unlinks) sometimes
* complete before the HCD can get requests away from hardware,
* though never during cleanup after a hard fault.
*/
if (io->status
&& (io->status != -ECONNRESET
|| status != -ECONNRESET)
&& urb->actual_length) {
dev_err(io->dev->bus->controller,
"dev %s ep%d%s scatterlist error %d/%d\n",
io->dev->devpath,
usb_endpoint_num(&urb->ep->desc),
usb_urb_dir_in(urb) ? "in" : "out",
status, io->status);
/* BUG (); */
}
if (io->status == 0 && status && status != -ECONNRESET) {
int i, found, retval;
io->status = status;
/* the previous urbs, and this one, completed already.
* unlink pending urbs so they won't rx/tx bad data.
* careful: unlink can sometimes be synchronous...
*/
spin_unlock(&io->lock);
for (i = 0, found = 0; i < io->entries; i++) {
if (!io->urbs[i])
continue;
if (found) {
usb_block_urb(io->urbs[i]);
retval = usb_unlink_urb(io->urbs[i]);
if (retval != -EINPROGRESS &&
retval != -ENODEV &&
retval != -EBUSY &&
retval != -EIDRM)
dev_err(&io->dev->dev,
"%s, unlink --> %d\n",
__func__, retval);
} else if (urb == io->urbs[i])
found = 1;
}
spin_lock(&io->lock);
}
/* on the last completion, signal usb_sg_wait() */
io->bytes += urb->actual_length;
io->count--;
if (!io->count)
complete(&io->complete);
spin_unlock(&io->lock);
}
/**
* usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
* @io: request block being initialized. until usb_sg_wait() returns,
* treat this as a pointer to an opaque block of memory,
* @dev: the usb device that will send or receive the data
* @pipe: endpoint "pipe" used to transfer the data
* @period: polling rate for interrupt endpoints, in frames or
* (for high speed endpoints) microframes; ignored for bulk
* @sg: scatterlist entries
* @nents: how many entries in the scatterlist
* @length: how many bytes to send from the scatterlist, or zero to
* send every byte identified in the list.
* @mem_flags: SLAB_* flags affecting memory allocations in this call
*
* This initializes a scatter/gather request, allocating resources such as
* I/O mappings and urb memory (except maybe memory used by USB controller
* drivers).
*
* The request must be issued using usb_sg_wait(), which waits for the I/O to
* complete (or to be canceled) and then cleans up all resources allocated by
* usb_sg_init().
*
* The request may be canceled with usb_sg_cancel(), either before or after
* usb_sg_wait() is called.
*
* Return: Zero for success, else a negative errno value.
*/
int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev,
unsigned pipe, unsigned period, struct scatterlist *sg,
int nents, size_t length, gfp_t mem_flags)
{
int i;
int urb_flags;
int use_sg;
if (!io || !dev || !sg
|| usb_pipecontrol(pipe)
|| usb_pipeisoc(pipe)
|| nents <= 0)
return -EINVAL;
spin_lock_init(&io->lock);
io->dev = dev;
io->pipe = pipe;
if (dev->bus->sg_tablesize > 0) {
use_sg = true;
io->entries = 1;
} else {
use_sg = false;
io->entries = nents;
}
/* initialize all the urbs we'll use */
io->urbs = kmalloc(io->entries * sizeof(*io->urbs), mem_flags);
if (!io->urbs)
goto nomem;
urb_flags = URB_NO_INTERRUPT;
if (usb_pipein(pipe))
urb_flags |= URB_SHORT_NOT_OK;
for_each_sg(sg, sg, io->entries, i) {
struct urb *urb;
unsigned len;
urb = usb_alloc_urb(0, mem_flags);
if (!urb) {
io->entries = i;
goto nomem;
}
io->urbs[i] = urb;
urb->dev = NULL;
urb->pipe = pipe;
urb->interval = period;
urb->transfer_flags = urb_flags;
urb->complete = sg_complete;
urb->context = io;
urb->sg = sg;
if (use_sg) {
/* There is no single transfer buffer */
urb->transfer_buffer = NULL;
urb->num_sgs = nents;
/* A length of zero means transfer the whole sg list */
len = length;
if (len == 0) {
struct scatterlist *sg2;
int j;
for_each_sg(sg, sg2, nents, j)
len += sg2->length;
}
} else {
/*
* Some systems can't use DMA; they use PIO instead.
* For their sakes, transfer_buffer is set whenever
* possible.
*/
if (!PageHighMem(sg_page(sg)))
urb->transfer_buffer = sg_virt(sg);
else
urb->transfer_buffer = NULL;
len = sg->length;
if (length) {
len = min_t(size_t, len, length);
length -= len;
if (length == 0)
io->entries = i + 1;
}
}
urb->transfer_buffer_length = len;
}
io->urbs[--i]->transfer_flags &= ~URB_NO_INTERRUPT;
/* transaction state */
io->count = io->entries;
io->status = 0;
io->bytes = 0;
init_completion(&io->complete);
return 0;
nomem:
sg_clean(io);
return -ENOMEM;
}
EXPORT_SYMBOL_GPL(usb_sg_init);
/**
* usb_sg_wait - synchronously execute scatter/gather request
* @io: request block handle, as initialized with usb_sg_init().
* some fields become accessible when this call returns.
* Context: !in_interrupt ()
*
* This function blocks until the specified I/O operation completes. It
* leverages the grouping of the related I/O requests to get good transfer
* rates, by queueing the requests. At higher speeds, such queuing can
* significantly improve USB throughput.
*
* There are three kinds of completion for this function.
*
* (1) success, where io->status is zero. The number of io->bytes
* transferred is as requested.
* (2) error, where io->status is a negative errno value. The number
* of io->bytes transferred before the error is usually less
* than requested, and can be nonzero.
* (3) cancellation, a type of error with status -ECONNRESET that
* is initiated by usb_sg_cancel().
*
* When this function returns, all memory allocated through usb_sg_init() or
* this call will have been freed. The request block parameter may still be
* passed to usb_sg_cancel(), or it may be freed. It could also be
* reinitialized and then reused.
*
* Data Transfer Rates:
*
* Bulk transfers are valid for full or high speed endpoints.
* The best full speed data rate is 19 packets of 64 bytes each
* per frame, or 1216 bytes per millisecond.
* The best high speed data rate is 13 packets of 512 bytes each
* per microframe, or 52 KBytes per millisecond.
*
* The reason to use interrupt transfers through this API would most likely
* be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
* could be transferred. That capability is less useful for low or full
* speed interrupt endpoints, which allow at most one packet per millisecond,
* of at most 8 or 64 bytes (respectively).
*
* It is not necessary to call this function to reserve bandwidth for devices
* under an xHCI host controller, as the bandwidth is reserved when the
* configuration or interface alt setting is selected.
*/
void usb_sg_wait(struct usb_sg_request *io)
{
int i;
int entries = io->entries;
/* queue the urbs. */
spin_lock_irq(&io->lock);
i = 0;
while (i < entries && !io->status) {
int retval;
io->urbs[i]->dev = io->dev;
spin_unlock_irq(&io->lock);
retval = usb_submit_urb(io->urbs[i], GFP_NOIO);
switch (retval) {
/* maybe we retrying will recover */
case -ENXIO: /* hc didn't queue this one */
case -EAGAIN:
case -ENOMEM:
retval = 0;
yield();
break;
/* no error? continue immediately.
*
* NOTE: to work better with UHCI (4K I/O buffer may
* need 3K of TDs) it may be good to limit how many
* URBs are queued at once; N milliseconds?
*/
case 0:
++i;
cpu_relax();
break;
/* fail any uncompleted urbs */
default:
io->urbs[i]->status = retval;
dev_dbg(&io->dev->dev, "%s, submit --> %d\n",
__func__, retval);
usb_sg_cancel(io);
}
spin_lock_irq(&io->lock);
if (retval && (io->status == 0 || io->status == -ECONNRESET))
io->status = retval;
}
io->count -= entries - i;
if (io->count == 0)
complete(&io->complete);
spin_unlock_irq(&io->lock);
/* OK, yes, this could be packaged as non-blocking.
* So could the submit loop above ... but it's easier to
* solve neither problem than to solve both!
*/
wait_for_completion(&io->complete);
sg_clean(io);
}
EXPORT_SYMBOL_GPL(usb_sg_wait);
/**
* usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
* @io: request block, initialized with usb_sg_init()
*
* This stops a request after it has been started by usb_sg_wait().
* It can also prevents one initialized by usb_sg_init() from starting,
* so that call just frees resources allocated to the request.
*/
void usb_sg_cancel(struct usb_sg_request *io)
{
unsigned long flags;
int i, retval;
spin_lock_irqsave(&io->lock, flags);
if (io->status) {
spin_unlock_irqrestore(&io->lock, flags);
return;
}
/* shut everything down */
io->status = -ECONNRESET;
spin_unlock_irqrestore(&io->lock, flags);
for (i = io->entries - 1; i >= 0; --i) {
usb_block_urb(io->urbs[i]);
retval = usb_unlink_urb(io->urbs[i]);
if (retval != -EINPROGRESS
&& retval != -ENODEV
&& retval != -EBUSY
&& retval != -EIDRM)
dev_warn(&io->dev->dev, "%s, unlink --> %d\n",
__func__, retval);
}
}
EXPORT_SYMBOL_GPL(usb_sg_cancel);
/*-------------------------------------------------------------------*/
/**
* usb_get_descriptor - issues a generic GET_DESCRIPTOR request
* @dev: the device whose descriptor is being retrieved
* @type: the descriptor type (USB_DT_*)
* @index: the number of the descriptor
* @buf: where to put the descriptor
* @size: how big is "buf"?
* Context: !in_interrupt ()
*
* Gets a USB descriptor. Convenience functions exist to simplify
* getting some types of descriptors. Use
* usb_get_string() or usb_string() for USB_DT_STRING.
* Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
* are part of the device structure.
* In addition to a number of USB-standard descriptors, some
* devices also use class-specific or vendor-specific descriptors.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Return: The number of bytes received on success, or else the status code
* returned by the underlying usb_control_msg() call.
*/
int usb_get_descriptor(struct usb_device *dev, unsigned char type,
unsigned char index, void *buf, int size)
{
int i;
int result;
memset(buf, 0, size); /* Make sure we parse really received data */
for (i = 0; i < 3; ++i) {
/* retry on length 0 or error; some devices are flakey */
result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
(type << 8) + index, 0, buf, size,
USB_CTRL_GET_TIMEOUT);
if (result <= 0 && result != -ETIMEDOUT)
continue;
if (result > 1 && ((u8 *)buf)[1] != type) {
result = -ENODATA;
continue;
}
break;
}
return result;
}
EXPORT_SYMBOL_GPL(usb_get_descriptor);
/**
* usb_get_string - gets a string descriptor
* @dev: the device whose string descriptor is being retrieved
* @langid: code for language chosen (from string descriptor zero)
* @index: the number of the descriptor
* @buf: where to put the string
* @size: how big is "buf"?
* Context: !in_interrupt ()
*
* Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
* in little-endian byte order).
* The usb_string() function will often be a convenient way to turn
* these strings into kernel-printable form.
*
* Strings may be referenced in device, configuration, interface, or other
* descriptors, and could also be used in vendor-specific ways.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Return: The number of bytes received on success, or else the status code
* returned by the underlying usb_control_msg() call.
*/
static int usb_get_string(struct usb_device *dev, unsigned short langid,
unsigned char index, void *buf, int size)
{
int i;
int result;
for (i = 0; i < 3; ++i) {
/* retry on length 0 or stall; some devices are flakey */
result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
(USB_DT_STRING << 8) + index, langid, buf, size,
USB_CTRL_GET_TIMEOUT);
if (result == 0 || result == -EPIPE)
continue;
if (result > 1 && ((u8 *) buf)[1] != USB_DT_STRING) {
result = -ENODATA;
continue;
}
break;
}
return result;
}
static void usb_try_string_workarounds(unsigned char *buf, int *length)
{
int newlength, oldlength = *length;
for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
if (!isprint(buf[newlength]) || buf[newlength + 1])
break;
if (newlength > 2) {
buf[0] = newlength;
*length = newlength;
}
}
static int usb_string_sub(struct usb_device *dev, unsigned int langid,
unsigned int index, unsigned char *buf)
{
int rc;
/* Try to read the string descriptor by asking for the maximum
* possible number of bytes */
if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
rc = -EIO;
else
rc = usb_get_string(dev, langid, index, buf, 255);
/* If that failed try to read the descriptor length, then
* ask for just that many bytes */
if (rc < 2) {
rc = usb_get_string(dev, langid, index, buf, 2);
if (rc == 2)
rc = usb_get_string(dev, langid, index, buf, buf[0]);
}
if (rc >= 2) {
if (!buf[0] && !buf[1])
usb_try_string_workarounds(buf, &rc);
/* There might be extra junk at the end of the descriptor */
if (buf[0] < rc)
rc = buf[0];
rc = rc - (rc & 1); /* force a multiple of two */
}
if (rc < 2)
rc = (rc < 0 ? rc : -EINVAL);
return rc;
}
static int usb_get_langid(struct usb_device *dev, unsigned char *tbuf)
{
int err;
if (dev->have_langid)
return 0;
if (dev->string_langid < 0)
return -EPIPE;
err = usb_string_sub(dev, 0, 0, tbuf);
/* If the string was reported but is malformed, default to english
* (0x0409) */
if (err == -ENODATA || (err > 0 && err < 4)) {
dev->string_langid = 0x0409;
dev->have_langid = 1;
dev_err(&dev->dev,
"language id specifier not provided by device, defaulting to English\n");
return 0;
}
/* In case of all other errors, we assume the device is not able to
* deal with strings at all. Set string_langid to -1 in order to
* prevent any string to be retrieved from the device */
if (err < 0) {
dev_err(&dev->dev, "string descriptor 0 read error: %d\n",
err);
dev->string_langid = -1;
return -EPIPE;
}
/* always use the first langid listed */
dev->string_langid = tbuf[2] | (tbuf[3] << 8);
dev->have_langid = 1;
dev_dbg(&dev->dev, "default language 0x%04x\n",
dev->string_langid);
return 0;
}
/**
* usb_string - returns UTF-8 version of a string descriptor
* @dev: the device whose string descriptor is being retrieved
* @index: the number of the descriptor
* @buf: where to put the string
* @size: how big is "buf"?
* Context: !in_interrupt ()
*
* This converts the UTF-16LE encoded strings returned by devices, from
* usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones
* that are more usable in most kernel contexts. Note that this function
* chooses strings in the first language supported by the device.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Return: length of the string (>= 0) or usb_control_msg status (< 0).
*/
int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
{
unsigned char *tbuf;
int err;
if (dev->state == USB_STATE_SUSPENDED)
return -EHOSTUNREACH;
if (size <= 0 || !buf || !index)
return -EINVAL;
buf[0] = 0;
tbuf = kmalloc(256, GFP_NOIO);
if (!tbuf)
return -ENOMEM;
err = usb_get_langid(dev, tbuf);
if (err < 0)
goto errout;
err = usb_string_sub(dev, dev->string_langid, index, tbuf);
if (err < 0)
goto errout;
size--; /* leave room for trailing NULL char in output buffer */
err = utf16s_to_utf8s((wchar_t *) &tbuf[2], (err - 2) / 2,
UTF16_LITTLE_ENDIAN, buf, size);
buf[err] = 0;
if (tbuf[1] != USB_DT_STRING)
dev_dbg(&dev->dev,
"wrong descriptor type %02x for string %d (\"%s\")\n",
tbuf[1], index, buf);
errout:
kfree(tbuf);
return err;
}
EXPORT_SYMBOL_GPL(usb_string);
/* one UTF-8-encoded 16-bit character has at most three bytes */
#define MAX_USB_STRING_SIZE (127 * 3 + 1)
/**
* usb_cache_string - read a string descriptor and cache it for later use
* @udev: the device whose string descriptor is being read
* @index: the descriptor index
*
* Return: A pointer to a kmalloc'ed buffer containing the descriptor string,
* or %NULL if the index is 0 or the string could not be read.
*/
char *usb_cache_string(struct usb_device *udev, int index)
{
char *buf;
char *smallbuf = NULL;
int len;
if (index <= 0)
return NULL;
buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO);
if (buf) {
len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE);
if (len > 0) {
smallbuf = kmalloc(++len, GFP_NOIO);
if (!smallbuf)
return buf;
memcpy(smallbuf, buf, len);
}
kfree(buf);
}
return smallbuf;
}
/*
* usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
* @dev: the device whose device descriptor is being updated
* @size: how much of the descriptor to read
* Context: !in_interrupt ()
*
* Updates the copy of the device descriptor stored in the device structure,
* which dedicates space for this purpose.
*
* Not exported, only for use by the core. If drivers really want to read
* the device descriptor directly, they can call usb_get_descriptor() with
* type = USB_DT_DEVICE and index = 0.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Return: The number of bytes received on success, or else the status code
* returned by the underlying usb_control_msg() call.
*/
int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
{
struct usb_device_descriptor *desc;
int ret;
if (size > sizeof(*desc))
return -EINVAL;
desc = kmalloc(sizeof(*desc), GFP_NOIO);
if (!desc)
return -ENOMEM;
ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
if (ret >= 0)
memcpy(&dev->descriptor, desc, size);
kfree(desc);
return ret;
}
/**
* usb_get_status - issues a GET_STATUS call
* @dev: the device whose status is being checked
* @type: USB_RECIP_*; for device, interface, or endpoint
* @target: zero (for device), else interface or endpoint number
* @data: pointer to two bytes of bitmap data
* Context: !in_interrupt ()
*
* Returns device, interface, or endpoint status. Normally only of
* interest to see if the device is self powered, or has enabled the
* remote wakeup facility; or whether a bulk or interrupt endpoint
* is halted ("stalled").
*
* Bits in these status bitmaps are set using the SET_FEATURE request,
* and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
* function should be used to clear halt ("stall") status.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Returns 0 and the status value in *@data (in host byte order) on success,
* or else the status code from the underlying usb_control_msg() call.
*/
int usb_get_status(struct usb_device *dev, int type, int target, void *data)
{
int ret;
__le16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
if (!status)
return -ENOMEM;
ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
sizeof(*status), USB_CTRL_GET_TIMEOUT);
if (ret == 2) {
*(u16 *) data = le16_to_cpu(*status);
ret = 0;
} else if (ret >= 0) {
ret = -EIO;
}
kfree(status);
return ret;
}
EXPORT_SYMBOL_GPL(usb_get_status);
/**
* usb_clear_halt - tells device to clear endpoint halt/stall condition
* @dev: device whose endpoint is halted
* @pipe: endpoint "pipe" being cleared
* Context: !in_interrupt ()
*
* This is used to clear halt conditions for bulk and interrupt endpoints,
* as reported by URB completion status. Endpoints that are halted are
* sometimes referred to as being "stalled". Such endpoints are unable
* to transmit or receive data until the halt status is cleared. Any URBs
* queued for such an endpoint should normally be unlinked by the driver
* before clearing the halt condition, as described in sections 5.7.5
* and 5.8.5 of the USB 2.0 spec.
*
* Note that control and isochronous endpoints don't halt, although control
* endpoints report "protocol stall" (for unsupported requests) using the
* same status code used to report a true stall.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Return: Zero on success, or else the status code returned by the
* underlying usb_control_msg() call.
*/
int usb_clear_halt(struct usb_device *dev, int pipe)
{
int result;
int endp = usb_pipeendpoint(pipe);
if (usb_pipein(pipe))
endp |= USB_DIR_IN;
/* we don't care if it wasn't halted first. in fact some devices
* (like some ibmcam model 1 units) seem to expect hosts to make
* this request for iso endpoints, which can't halt!
*/
result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
USB_ENDPOINT_HALT, endp, NULL, 0,
USB_CTRL_SET_TIMEOUT);
/* don't un-halt or force to DATA0 except on success */
if (result < 0)
return result;
/* NOTE: seems like Microsoft and Apple don't bother verifying
* the clear "took", so some devices could lock up if you check...
* such as the Hagiwara FlashGate DUAL. So we won't bother.
*
* NOTE: make sure the logic here doesn't diverge much from
* the copy in usb-storage, for as long as we need two copies.
*/
usb_reset_endpoint(dev, endp);
return 0;
}
EXPORT_SYMBOL_GPL(usb_clear_halt);
static int create_intf_ep_devs(struct usb_interface *intf)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct usb_host_interface *alt = intf->cur_altsetting;
int i;
if (intf->ep_devs_created || intf->unregistering)
return 0;
for (i = 0; i < alt->desc.bNumEndpoints; ++i)
(void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev);
intf->ep_devs_created = 1;
return 0;
}
static void remove_intf_ep_devs(struct usb_interface *intf)
{
struct usb_host_interface *alt = intf->cur_altsetting;
int i;
if (!intf->ep_devs_created)
return;
for (i = 0; i < alt->desc.bNumEndpoints; ++i)
usb_remove_ep_devs(&alt->endpoint[i]);
intf->ep_devs_created = 0;
}
/**
* usb_disable_endpoint -- Disable an endpoint by address
* @dev: the device whose endpoint is being disabled
* @epaddr: the endpoint's address. Endpoint number for output,
* endpoint number + USB_DIR_IN for input
* @reset_hardware: flag to erase any endpoint state stored in the
* controller hardware
*
* Disables the endpoint for URB submission and nukes all pending URBs.
* If @reset_hardware is set then also deallocates hcd/hardware state
* for the endpoint.
*/
void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr,
bool reset_hardware)
{
unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
struct usb_host_endpoint *ep;
if (!dev)
return;
if (usb_endpoint_out(epaddr)) {
ep = dev->ep_out[epnum];
if (reset_hardware)
dev->ep_out[epnum] = NULL;
} else {
ep = dev->ep_in[epnum];
if (reset_hardware)
dev->ep_in[epnum] = NULL;
}
if (ep) {
ep->enabled = 0;
usb_hcd_flush_endpoint(dev, ep);
if (reset_hardware)
usb_hcd_disable_endpoint(dev, ep);
}
}
/**
* usb_reset_endpoint - Reset an endpoint's state.
* @dev: the device whose endpoint is to be reset
* @epaddr: the endpoint's address. Endpoint number for output,
* endpoint number + USB_DIR_IN for input
*
* Resets any host-side endpoint state such as the toggle bit,
* sequence number or current window.
*/
void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr)
{
unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
struct usb_host_endpoint *ep;
if (usb_endpoint_out(epaddr))
ep = dev->ep_out[epnum];
else
ep = dev->ep_in[epnum];
if (ep)
usb_hcd_reset_endpoint(dev, ep);
}
EXPORT_SYMBOL_GPL(usb_reset_endpoint);
/**
* usb_disable_interface -- Disable all endpoints for an interface
* @dev: the device whose interface is being disabled
* @intf: pointer to the interface descriptor
* @reset_hardware: flag to erase any endpoint state stored in the
* controller hardware
*
* Disables all the endpoints for the interface's current altsetting.
*/
void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf,
bool reset_hardware)
{
struct usb_host_interface *alt = intf->cur_altsetting;
int i;
for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
usb_disable_endpoint(dev,
alt->endpoint[i].desc.bEndpointAddress,
reset_hardware);
}
}
/**
* usb_disable_device - Disable all the endpoints for a USB device
* @dev: the device whose endpoints are being disabled
* @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
*
* Disables all the device's endpoints, potentially including endpoint 0.
* Deallocates hcd/hardware state for the endpoints (nuking all or most
* pending urbs) and usbcore state for the interfaces, so that usbcore
* must usb_set_configuration() before any interfaces could be used.
*/
void usb_disable_device(struct usb_device *dev, int skip_ep0)
{
int i;
struct usb_hcd *hcd = bus_to_hcd(dev->bus);
/* getting rid of interfaces will disconnect
* any drivers bound to them (a key side effect)
*/
if (dev->actconfig) {
/*
* FIXME: In order to avoid self-deadlock involving the
* bandwidth_mutex, we have to mark all the interfaces
* before unregistering any of them.
*/
for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++)
dev->actconfig->interface[i]->unregistering = 1;
for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
struct usb_interface *interface;
/* remove this interface if it has been registered */
interface = dev->actconfig->interface[i];
if (!device_is_registered(&interface->dev))
continue;
dev_dbg(&dev->dev, "unregistering interface %s\n",
dev_name(&interface->dev));
remove_intf_ep_devs(interface);
device_del(&interface->dev);
}
/* Now that the interfaces are unbound, nobody should
* try to access them.
*/
for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
put_device(&dev->actconfig->interface[i]->dev);
dev->actconfig->interface[i] = NULL;
}
if (dev->usb2_hw_lpm_enabled == 1)
usb_set_usb2_hardware_lpm(dev, 0);
usb_unlocked_disable_lpm(dev);
usb_disable_ltm(dev);
dev->actconfig = NULL;
if (dev->state == USB_STATE_CONFIGURED)
usb_set_device_state(dev, USB_STATE_ADDRESS);
}
dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
skip_ep0 ? "non-ep0" : "all");
if (hcd->driver->check_bandwidth) {
/* First pass: Cancel URBs, leave endpoint pointers intact. */
for (i = skip_ep0; i < 16; ++i) {
usb_disable_endpoint(dev, i, false);
usb_disable_endpoint(dev, i + USB_DIR_IN, false);
}
/* Remove endpoints from the host controller internal state */
mutex_lock(hcd->bandwidth_mutex);
usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
mutex_unlock(hcd->bandwidth_mutex);
/* Second pass: remove endpoint pointers */
}
for (i = skip_ep0; i < 16; ++i) {
usb_disable_endpoint(dev, i, true);
usb_disable_endpoint(dev, i + USB_DIR_IN, true);
}
}
/**
* usb_enable_endpoint - Enable an endpoint for USB communications
* @dev: the device whose interface is being enabled
* @ep: the endpoint
* @reset_ep: flag to reset the endpoint state
*
* Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers.
* For control endpoints, both the input and output sides are handled.
*/
void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep,
bool reset_ep)
{
int epnum = usb_endpoint_num(&ep->desc);
int is_out = usb_endpoint_dir_out(&ep->desc);
int is_control = usb_endpoint_xfer_control(&ep->desc);
if (reset_ep)
usb_hcd_reset_endpoint(dev, ep);
if (is_out || is_control)
dev->ep_out[epnum] = ep;
if (!is_out || is_control)
dev->ep_in[epnum] = ep;
ep->enabled = 1;
}
/**
* usb_enable_interface - Enable all the endpoints for an interface
* @dev: the device whose interface is being enabled
* @intf: pointer to the interface descriptor
* @reset_eps: flag to reset the endpoints' state
*
* Enables all the endpoints for the interface's current altsetting.
*/
void usb_enable_interface(struct usb_device *dev,
struct usb_interface *intf, bool reset_eps)
{
struct usb_host_interface *alt = intf->cur_altsetting;
int i;
for (i = 0; i < alt->desc.bNumEndpoints; ++i)
usb_enable_endpoint(dev, &alt->endpoint[i], reset_eps);
}
/**
* usb_set_interface - Makes a particular alternate setting be current
* @dev: the device whose interface is being updated
* @interface: the interface being updated
* @alternate: the setting being chosen.
* Context: !in_interrupt ()
*
* This is used to enable data transfers on interfaces that may not
* be enabled by default. Not all devices support such configurability.
* Only the driver bound to an interface may change its setting.
*
* Within any given configuration, each interface may have several
* alternative settings. These are often used to control levels of
* bandwidth consumption. For example, the default setting for a high
* speed interrupt endpoint may not send more than 64 bytes per microframe,
* while interrupt transfers of up to 3KBytes per microframe are legal.
* Also, isochronous endpoints may never be part of an
* interface's default setting. To access such bandwidth, alternate
* interface settings must be made current.
*
* Note that in the Linux USB subsystem, bandwidth associated with
* an endpoint in a given alternate setting is not reserved until an URB
* is submitted that needs that bandwidth. Some other operating systems
* allocate bandwidth early, when a configuration is chosen.
*
* This call is synchronous, and may not be used in an interrupt context.
* Also, drivers must not change altsettings while urbs are scheduled for
* endpoints in that interface; all such urbs must first be completed
* (perhaps forced by unlinking).
*
* Return: Zero on success, or else the status code returned by the
* underlying usb_control_msg() call.
*/
int usb_set_interface(struct usb_device *dev, int interface, int alternate)
{
struct usb_interface *iface;
struct usb_host_interface *alt;
struct usb_hcd *hcd = bus_to_hcd(dev->bus);
int i, ret, manual = 0;
unsigned int epaddr;
unsigned int pipe;
if (dev->state == USB_STATE_SUSPENDED)
return -EHOSTUNREACH;
iface = usb_ifnum_to_if(dev, interface);
if (!iface) {
dev_dbg(&dev->dev, "selecting invalid interface %d\n",
interface);
return -EINVAL;
}
if (iface->unregistering)
return -ENODEV;
alt = usb_altnum_to_altsetting(iface, alternate);
if (!alt) {
dev_warn(&dev->dev, "selecting invalid altsetting %d\n",
alternate);
return -EINVAL;
}
/* Make sure we have enough bandwidth for this alternate interface.
* Remove the current alt setting and add the new alt setting.
*/
mutex_lock(hcd->bandwidth_mutex);
/* Disable LPM, and re-enable it once the new alt setting is installed,
* so that the xHCI driver can recalculate the U1/U2 timeouts.
*/
if (usb_disable_lpm(dev)) {
dev_err(&iface->dev, "%s Failed to disable LPM\n.", __func__);
mutex_unlock(hcd->bandwidth_mutex);
return -ENOMEM;
}
/* Changing alt-setting also frees any allocated streams */
for (i = 0; i < iface->cur_altsetting->desc.bNumEndpoints; i++)
iface->cur_altsetting->endpoint[i].streams = 0;
ret = usb_hcd_alloc_bandwidth(dev, NULL, iface->cur_altsetting, alt);
if (ret < 0) {
dev_info(&dev->dev, "Not enough bandwidth for altsetting %d\n",
alternate);
usb_enable_lpm(dev);
mutex_unlock(hcd->bandwidth_mutex);
return ret;
}
if (dev->quirks & USB_QUIRK_NO_SET_INTF)
ret = -EPIPE;
else
ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
alternate, interface, NULL, 0, 5000);
/* 9.4.10 says devices don't need this and are free to STALL the
* request if the interface only has one alternate setting.
*/
if (ret == -EPIPE && iface->num_altsetting == 1) {
dev_dbg(&dev->dev,
"manual set_interface for iface %d, alt %d\n",
interface, alternate);
manual = 1;
} else if (ret < 0) {
/* Re-instate the old alt setting */
usb_hcd_alloc_bandwidth(dev, NULL, alt, iface->cur_altsetting);
usb_enable_lpm(dev);
mutex_unlock(hcd->bandwidth_mutex);
return ret;
}
mutex_unlock(hcd->bandwidth_mutex);
/* FIXME drivers shouldn't need to replicate/bugfix the logic here
* when they implement async or easily-killable versions of this or
* other "should-be-internal" functions (like clear_halt).
* should hcd+usbcore postprocess control requests?
*/
/* prevent submissions using previous endpoint settings */
if (iface->cur_altsetting != alt) {
remove_intf_ep_devs(iface);
usb_remove_sysfs_intf_files(iface);
}
usb_disable_interface(dev, iface, true);
iface->cur_altsetting = alt;
/* Now that the interface is installed, re-enable LPM. */
usb_unlocked_enable_lpm(dev);
/* If the interface only has one altsetting and the device didn't
* accept the request, we attempt to carry out the equivalent action
* by manually clearing the HALT feature for each endpoint in the
* new altsetting.
*/
if (manual) {
for (i = 0; i < alt->desc.bNumEndpoints; i++) {
epaddr = alt->endpoint[i].desc.bEndpointAddress;
pipe = __create_pipe(dev,
USB_ENDPOINT_NUMBER_MASK & epaddr) |
(usb_endpoint_out(epaddr) ?
USB_DIR_OUT : USB_DIR_IN);
usb_clear_halt(dev, pipe);
}
}
/* 9.1.1.5: reset toggles for all endpoints in the new altsetting
*
* Note:
* Despite EP0 is always present in all interfaces/AS, the list of
* endpoints from the descriptor does not contain EP0. Due to its
* omnipresence one might expect EP0 being considered "affected" by
* any SetInterface request and hence assume toggles need to be reset.
* However, EP0 toggles are re-synced for every individual transfer
* during the SETUP stage - hence EP0 toggles are "don't care" here.
* (Likewise, EP0 never "halts" on well designed devices.)
*/
usb_enable_interface(dev, iface, true);
if (device_is_registered(&iface->dev)) {
usb_create_sysfs_intf_files(iface);
create_intf_ep_devs(iface);
}
return 0;
}
EXPORT_SYMBOL_GPL(usb_set_interface);
/**
* usb_reset_configuration - lightweight device reset
* @dev: the device whose configuration is being reset
*
* This issues a standard SET_CONFIGURATION request to the device using
* the current configuration. The effect is to reset most USB-related
* state in the device, including interface altsettings (reset to zero),
* endpoint halts (cleared), and endpoint state (only for bulk and interrupt
* endpoints). Other usbcore state is unchanged, including bindings of
* usb device drivers to interfaces.
*
* Because this affects multiple interfaces, avoid using this with composite
* (multi-interface) devices. Instead, the driver for each interface may
* use usb_set_interface() on the interfaces it claims. Be careful though;
* some devices don't support the SET_INTERFACE request, and others won't
* reset all the interface state (notably endpoint state). Resetting the whole
* configuration would affect other drivers' interfaces.
*
* The caller must own the device lock.
*
* Return: Zero on success, else a negative error code.
*/
int usb_reset_configuration(struct usb_device *dev)
{
int i, retval;
struct usb_host_config *config;
struct usb_hcd *hcd = bus_to_hcd(dev->bus);
if (dev->state == USB_STATE_SUSPENDED)
return -EHOSTUNREACH;
/* caller must have locked the device and must own
* the usb bus readlock (so driver bindings are stable);
* calls during probe() are fine
*/
for (i = 1; i < 16; ++i) {
usb_disable_endpoint(dev, i, true);
usb_disable_endpoint(dev, i + USB_DIR_IN, true);
}
config = dev->actconfig;
retval = 0;
mutex_lock(hcd->bandwidth_mutex);
/* Disable LPM, and re-enable it once the configuration is reset, so
* that the xHCI driver can recalculate the U1/U2 timeouts.
*/
if (usb_disable_lpm(dev)) {
dev_err(&dev->dev, "%s Failed to disable LPM\n.", __func__);
mutex_unlock(hcd->bandwidth_mutex);
return -ENOMEM;
}
/* Make sure we have enough bandwidth for each alternate setting 0 */
for (i = 0; i < config->desc.bNumInterfaces; i++) {
struct usb_interface *intf = config->interface[i];
struct usb_host_interface *alt;
alt = usb_altnum_to_altsetting(intf, 0);
if (!alt)
alt = &intf->altsetting[0];
if (alt != intf->cur_altsetting)
retval = usb_hcd_alloc_bandwidth(dev, NULL,
intf->cur_altsetting, alt);
if (retval < 0)
break;
}
/* If not, reinstate the old alternate settings */
if (retval < 0) {
reset_old_alts:
for (i--; i >= 0; i--) {
struct usb_interface *intf = config->interface[i];
struct usb_host_interface *alt;
alt = usb_altnum_to_altsetting(intf, 0);
if (!alt)
alt = &intf->altsetting[0];
if (alt != intf->cur_altsetting)
usb_hcd_alloc_bandwidth(dev, NULL,
alt, intf->cur_altsetting);
}
usb_enable_lpm(dev);
mutex_unlock(hcd->bandwidth_mutex);
return retval;
}
retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_CONFIGURATION, 0,
config->desc.bConfigurationValue, 0,
NULL, 0, USB_CTRL_SET_TIMEOUT);
if (retval < 0)
goto reset_old_alts;
mutex_unlock(hcd->bandwidth_mutex);
/* re-init hc/hcd interface/endpoint state */
for (i = 0; i < config->desc.bNumInterfaces; i++) {
struct usb_interface *intf = config->interface[i];
struct usb_host_interface *alt;
alt = usb_altnum_to_altsetting(intf, 0);
/* No altsetting 0? We'll assume the first altsetting.
* We could use a GetInterface call, but if a device is
* so non-compliant that it doesn't have altsetting 0
* then I wouldn't trust its reply anyway.
*/
if (!alt)
alt = &intf->altsetting[0];
if (alt != intf->cur_altsetting) {
remove_intf_ep_devs(intf);
usb_remove_sysfs_intf_files(intf);
}
intf->cur_altsetting = alt;
usb_enable_interface(dev, intf, true);
if (device_is_registered(&intf->dev)) {
usb_create_sysfs_intf_files(intf);
create_intf_ep_devs(intf);
}
}
/* Now that the interfaces are installed, re-enable LPM. */
usb_unlocked_enable_lpm(dev);
return 0;
}
EXPORT_SYMBOL_GPL(usb_reset_configuration);
static void usb_release_interface(struct device *dev)
{
struct usb_interface *intf = to_usb_interface(dev);
struct usb_interface_cache *intfc =
altsetting_to_usb_interface_cache(intf->altsetting);
kref_put(&intfc->ref, usb_release_interface_cache);
usb_put_dev(interface_to_usbdev(intf));
kfree(intf);
}
/*
* usb_deauthorize_interface - deauthorize an USB interface
*
* @intf: USB interface structure
*/
void usb_deauthorize_interface(struct usb_interface *intf)
{
struct device *dev = &intf->dev;
device_lock(dev->parent);
if (intf->authorized) {
device_lock(dev);
intf->authorized = 0;
device_unlock(dev);
usb_forced_unbind_intf(intf);
}
device_unlock(dev->parent);
}
/*
* usb_authorize_interface - authorize an USB interface
*
* @intf: USB interface structure
*/
void usb_authorize_interface(struct usb_interface *intf)
{
struct device *dev = &intf->dev;
if (!intf->authorized) {
device_lock(dev);
intf->authorized = 1; /* authorize interface */
device_unlock(dev);
}
}
static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env)
{
struct usb_device *usb_dev;
struct usb_interface *intf;
struct usb_host_interface *alt;
intf = to_usb_interface(dev);
usb_dev = interface_to_usbdev(intf);
alt = intf->cur_altsetting;
if (add_uevent_var(env, "INTERFACE=%d/%d/%d",
alt->desc.bInterfaceClass,
alt->desc.bInterfaceSubClass,
alt->desc.bInterfaceProtocol))
return -ENOMEM;
if (add_uevent_var(env,
"MODALIAS=usb:"
"v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02Xin%02X",
le16_to_cpu(usb_dev->descriptor.idVendor),
le16_to_cpu(usb_dev->descriptor.idProduct),
le16_to_cpu(usb_dev->descriptor.bcdDevice),
usb_dev->descriptor.bDeviceClass,
usb_dev->descriptor.bDeviceSubClass,
usb_dev->descriptor.bDeviceProtocol,
alt->desc.bInterfaceClass,
alt->desc.bInterfaceSubClass,
alt->desc.bInterfaceProtocol,
alt->desc.bInterfaceNumber))
return -ENOMEM;
return 0;
}
struct device_type usb_if_device_type = {
.name = "usb_interface",
.release = usb_release_interface,
.uevent = usb_if_uevent,
};
static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
struct usb_host_config *config,
u8 inum)
{
struct usb_interface_assoc_descriptor *retval = NULL;
struct usb_interface_assoc_descriptor *intf_assoc;
int first_intf;
int last_intf;
int i;
for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
intf_assoc = config->intf_assoc[i];
if (intf_assoc->bInterfaceCount == 0)
continue;
first_intf = intf_assoc->bFirstInterface;
last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
if (inum >= first_intf && inum <= last_intf) {
if (!retval)
retval = intf_assoc;
else
dev_err(&dev->dev, "Interface #%d referenced"
" by multiple IADs\n", inum);
}
}
return retval;
}
/*
* Internal function to queue a device reset
* See usb_queue_reset_device() for more details
*/
static void __usb_queue_reset_device(struct work_struct *ws)
{
int rc;
struct usb_interface *iface =
container_of(ws, struct usb_interface, reset_ws);
struct usb_device *udev = interface_to_usbdev(iface);
rc = usb_lock_device_for_reset(udev, iface);
if (rc >= 0) {
usb_reset_device(udev);
usb_unlock_device(udev);
}
usb_put_intf(iface); /* Undo _get_ in usb_queue_reset_device() */
}
/*
* usb_set_configuration - Makes a particular device setting be current
* @dev: the device whose configuration is being updated
* @configuration: the configuration being chosen.
* Context: !in_interrupt(), caller owns the device lock
*
* This is used to enable non-default device modes. Not all devices
* use this kind of configurability; many devices only have one
* configuration.
*
* @configuration is the value of the configuration to be installed.
* According to the USB spec (e.g. section 9.1.1.5), configuration values
* must be non-zero; a value of zero indicates that the device in
* unconfigured. However some devices erroneously use 0 as one of their
* configuration values. To help manage such devices, this routine will
* accept @configuration = -1 as indicating the device should be put in
* an unconfigured state.
*
* USB device configurations may affect Linux interoperability,
* power consumption and the functionality available. For example,
* the default configuration is limited to using 100mA of bus power,
* so that when certain device functionality requires more power,
* and the device is bus powered, that functionality should be in some
* non-default device configuration. Other device modes may also be
* reflected as configuration options, such as whether two ISDN
* channels are available independently; and choosing between open
* standard device protocols (like CDC) or proprietary ones.
*
* Note that a non-authorized device (dev->authorized == 0) will only
* be put in unconfigured mode.
*
* Note that USB has an additional level of device configurability,
* associated with interfaces. That configurability is accessed using
* usb_set_interface().
*
* This call is synchronous. The calling context must be able to sleep,
* must own the device lock, and must not hold the driver model's USB
* bus mutex; usb interface driver probe() methods cannot use this routine.
*
* Returns zero on success, or else the status code returned by the
* underlying call that failed. On successful completion, each interface
* in the original device configuration has been destroyed, and each one
* in the new configuration has been probed by all relevant usb device
* drivers currently known to the kernel.
*/
int usb_set_configuration(struct usb_device *dev, int configuration)
{
int i, ret;
struct usb_host_config *cp = NULL;
struct usb_interface **new_interfaces = NULL;
struct usb_hcd *hcd = bus_to_hcd(dev->bus);
int n, nintf;
if (dev->authorized == 0 || configuration == -1)
configuration = 0;
else {
for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
if (dev->config[i].desc.bConfigurationValue ==
configuration) {
cp = &dev->config[i];
break;
}
}
}
if ((!cp && configuration != 0))
return -EINVAL;
/* The USB spec says configuration 0 means unconfigured.
* But if a device includes a configuration numbered 0,
* we will accept it as a correctly configured state.
* Use -1 if you really want to unconfigure the device.
*/
if (cp && configuration == 0)
dev_warn(&dev->dev, "config 0 descriptor??\n");
/* Allocate memory for new interfaces before doing anything else,
* so that if we run out then nothing will have changed. */
n = nintf = 0;
if (cp) {
nintf = cp->desc.bNumInterfaces;
new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
GFP_NOIO);
if (!new_interfaces)
return -ENOMEM;
for (; n < nintf; ++n) {
new_interfaces[n] = kzalloc(
sizeof(struct usb_interface),
GFP_NOIO);
if (!new_interfaces[n]) {
ret = -ENOMEM;
free_interfaces:
while (--n >= 0)
kfree(new_interfaces[n]);
kfree(new_interfaces);
return ret;
}
}
i = dev->bus_mA - usb_get_max_power(dev, cp);
if (i < 0)
dev_warn(&dev->dev, "new config #%d exceeds power "
"limit by %dmA\n",
configuration, -i);
}
/* Wake up the device so we can send it the Set-Config request */
ret = usb_autoresume_device(dev);
if (ret)
goto free_interfaces;
/* if it's already configured, clear out old state first.
* getting rid of old interfaces means unbinding their drivers.
*/
if (dev->state != USB_STATE_ADDRESS)
usb_disable_device(dev, 1); /* Skip ep0 */
/* Get rid of pending async Set-Config requests for this device */
cancel_async_set_config(dev);
/* Make sure we have bandwidth (and available HCD resources) for this
* configuration. Remove endpoints from the schedule if we're dropping
* this configuration to set configuration 0. After this point, the
* host controller will not allow submissions to dropped endpoints. If
* this call fails, the device state is unchanged.
*/
mutex_lock(hcd->bandwidth_mutex);
/* Disable LPM, and re-enable it once the new configuration is
* installed, so that the xHCI driver can recalculate the U1/U2
* timeouts.
*/
if (dev->actconfig && usb_disable_lpm(dev)) {
dev_err(&dev->dev, "%s Failed to disable LPM\n.", __func__);
mutex_unlock(hcd->bandwidth_mutex);
ret = -ENOMEM;
goto free_interfaces;
}
ret = usb_hcd_alloc_bandwidth(dev, cp, NULL, NULL);
if (ret < 0) {
if (dev->actconfig)
usb_enable_lpm(dev);
mutex_unlock(hcd->bandwidth_mutex);
usb_autosuspend_device(dev);
goto free_interfaces;
}
/*
* Initialize the new interface structures and the
* hc/hcd/usbcore interface/endpoint state.
*/
for (i = 0; i < nintf; ++i) {
struct usb_interface_cache *intfc;
struct usb_interface *intf;
struct usb_host_interface *alt;
cp->interface[i] = intf = new_interfaces[i];
intfc = cp->intf_cache[i];
intf->altsetting = intfc->altsetting;
intf->num_altsetting = intfc->num_altsetting;
intf->authorized = !!HCD_INTF_AUTHORIZED(hcd);
kref_get(&intfc->ref);
alt = usb_altnum_to_altsetting(intf, 0);
/* No altsetting 0? We'll assume the first altsetting.
* We could use a GetInterface call, but if a device is
* so non-compliant that it doesn't have altsetting 0
* then I wouldn't trust its reply anyway.
*/
if (!alt)
alt = &intf->altsetting[0];
intf->intf_assoc =
find_iad(dev, cp, alt->desc.bInterfaceNumber);
intf->cur_altsetting = alt;
usb_enable_interface(dev, intf, true);
intf->dev.parent = &dev->dev;
intf->dev.driver = NULL;
intf->dev.bus = &usb_bus_type;
intf->dev.type = &usb_if_device_type;
intf->dev.groups = usb_interface_groups;
/*
* Please refer to usb_alloc_dev() to see why we set
* dma_mask and dma_pfn_offset.
*/
intf->dev.dma_mask = dev->dev.dma_mask;
intf->dev.dma_pfn_offset = dev->dev.dma_pfn_offset;
INIT_WORK(&intf->reset_ws, __usb_queue_reset_device);
intf->minor = -1;
device_initialize(&intf->dev);
pm_runtime_no_callbacks(&intf->dev);
dev_set_name(&intf->dev, "%d-%s:%d.%d",
dev->bus->busnum, dev->devpath,
configuration, alt->desc.bInterfaceNumber);
usb_get_dev(dev);
}
kfree(new_interfaces);
ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
NULL, 0, USB_CTRL_SET_TIMEOUT);
if (ret < 0 && cp) {
/*
* All the old state is gone, so what else can we do?
* The device is probably useless now anyway.
*/
usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
for (i = 0; i < nintf; ++i) {
usb_disable_interface(dev, cp->interface[i], true);
put_device(&cp->interface[i]->dev);
cp->interface[i] = NULL;
}
cp = NULL;
}
dev->actconfig = cp;
mutex_unlock(hcd->bandwidth_mutex);
if (!cp) {
usb_set_device_state(dev, USB_STATE_ADDRESS);
/* Leave LPM disabled while the device is unconfigured. */
usb_autosuspend_device(dev);
return ret;
}
usb_set_device_state(dev, USB_STATE_CONFIGURED);
if (cp->string == NULL &&
!(dev->quirks & USB_QUIRK_CONFIG_INTF_STRINGS))
cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
/* Now that the interfaces are installed, re-enable LPM. */
usb_unlocked_enable_lpm(dev);
/* Enable LTM if it was turned off by usb_disable_device. */
usb_enable_ltm(dev);
/* Now that all the interfaces are set up, register them
* to trigger binding of drivers to interfaces. probe()
* routines may install different altsettings and may
* claim() any interfaces not yet bound. Many class drivers
* need that: CDC, audio, video, etc.
*/
for (i = 0; i < nintf; ++i) {
struct usb_interface *intf = cp->interface[i];
dev_dbg(&dev->dev,
"adding %s (config #%d, interface %d)\n",
dev_name(&intf->dev), configuration,
intf->cur_altsetting->desc.bInterfaceNumber);
device_enable_async_suspend(&intf->dev);
ret = device_add(&intf->dev);
if (ret != 0) {
dev_err(&dev->dev, "device_add(%s) --> %d\n",
dev_name(&intf->dev), ret);
continue;
}
create_intf_ep_devs(intf);
}
usb_autosuspend_device(dev);
return 0;
}
EXPORT_SYMBOL_GPL(usb_set_configuration);
static LIST_HEAD(set_config_list);
static DEFINE_SPINLOCK(set_config_lock);
struct set_config_request {
struct usb_device *udev;
int config;
struct work_struct work;
struct list_head node;
};
/* Worker routine for usb_driver_set_configuration() */
static void driver_set_config_work(struct work_struct *work)
{
struct set_config_request *req =
container_of(work, struct set_config_request, work);
struct usb_device *udev = req->udev;
usb_lock_device(udev);
spin_lock(&set_config_lock);
list_del(&req->node);
spin_unlock(&set_config_lock);
if (req->config >= -1) /* Is req still valid? */
usb_set_configuration(udev, req->config);
usb_unlock_device(udev);
usb_put_dev(udev);
kfree(req);
}
/* Cancel pending Set-Config requests for a device whose configuration
* was just changed
*/
static void cancel_async_set_config(struct usb_device *udev)
{
struct set_config_request *req;
spin_lock(&set_config_lock);
list_for_each_entry(req, &set_config_list, node) {
if (req->udev == udev)
req->config = -999; /* Mark as cancelled */
}
spin_unlock(&set_config_lock);
}
/**
* usb_driver_set_configuration - Provide a way for drivers to change device configurations
* @udev: the device whose configuration is being updated
* @config: the configuration being chosen.
* Context: In process context, must be able to sleep
*
* Device interface drivers are not allowed to change device configurations.
* This is because changing configurations will destroy the interface the
* driver is bound to and create new ones; it would be like a floppy-disk
* driver telling the computer to replace the floppy-disk drive with a
* tape drive!
*
* Still, in certain specialized circumstances the need may arise. This
* routine gets around the normal restrictions by using a work thread to
* submit the change-config request.
*
* Return: 0 if the request was successfully queued, error code otherwise.
* The caller has no way to know whether the queued request will eventually
* succeed.
*/
int usb_driver_set_configuration(struct usb_device *udev, int config)
{
struct set_config_request *req;
req = kmalloc(sizeof(*req), GFP_KERNEL);
if (!req)
return -ENOMEM;
req->udev = udev;
req->config = config;
INIT_WORK(&req->work, driver_set_config_work);
spin_lock(&set_config_lock);
list_add(&req->node, &set_config_list);
spin_unlock(&set_config_lock);
usb_get_dev(udev);
schedule_work(&req->work);
return 0;
}
EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
/**
* cdc_parse_cdc_header - parse the extra headers present in CDC devices
* @hdr: the place to put the results of the parsing
* @intf: the interface for which parsing is requested
* @buffer: pointer to the extra headers to be parsed
* @buflen: length of the extra headers
*
* This evaluates the extra headers present in CDC devices which
* bind the interfaces for data and control and provide details
* about the capabilities of the device.
*
* Return: number of descriptors parsed or -EINVAL
* if the header is contradictory beyond salvage
*/
int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr,
struct usb_interface *intf,
u8 *buffer,
int buflen)
{
/* duplicates are ignored */
struct usb_cdc_union_desc *union_header = NULL;
/* duplicates are not tolerated */
struct usb_cdc_header_desc *header = NULL;
struct usb_cdc_ether_desc *ether = NULL;
struct usb_cdc_mdlm_detail_desc *detail = NULL;
struct usb_cdc_mdlm_desc *desc = NULL;
unsigned int elength;
int cnt = 0;
memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header));
hdr->phonet_magic_present = false;
while (buflen > 0) {
elength = buffer[0];
if (!elength) {
dev_err(&intf->dev, "skipping garbage byte\n");
elength = 1;
goto next_desc;
}
if ((buflen < elength) || (elength < 3)) {
dev_err(&intf->dev, "invalid descriptor buffer length\n");
break;
}
if (buffer[1] != USB_DT_CS_INTERFACE) {
dev_err(&intf->dev, "skipping garbage\n");
goto next_desc;
}
switch (buffer[2]) {
case USB_CDC_UNION_TYPE: /* we've found it */
if (elength < sizeof(struct usb_cdc_union_desc))
goto next_desc;
if (union_header) {
dev_err(&intf->dev, "More than one union descriptor, skipping ...\n");
goto next_desc;
}
union_header = (struct usb_cdc_union_desc *)buffer;
break;
case USB_CDC_COUNTRY_TYPE:
if (elength < sizeof(struct usb_cdc_country_functional_desc))
goto next_desc;
hdr->usb_cdc_country_functional_desc =
(struct usb_cdc_country_functional_desc *)buffer;
break;
case USB_CDC_HEADER_TYPE:
if (elength != sizeof(struct usb_cdc_header_desc))
goto next_desc;
if (header)
return -EINVAL;
header = (struct usb_cdc_header_desc *)buffer;
break;
case USB_CDC_ACM_TYPE:
if (elength < sizeof(struct usb_cdc_acm_descriptor))
goto next_desc;
hdr->usb_cdc_acm_descriptor =
(struct usb_cdc_acm_descriptor *)buffer;
break;
case USB_CDC_ETHERNET_TYPE:
if (elength != sizeof(struct usb_cdc_ether_desc))
goto next_desc;
if (ether)
return -EINVAL;
ether = (struct usb_cdc_ether_desc *)buffer;
break;
case USB_CDC_CALL_MANAGEMENT_TYPE:
if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor))
goto next_desc;
hdr->usb_cdc_call_mgmt_descriptor =
(struct usb_cdc_call_mgmt_descriptor *)buffer;
break;
case USB_CDC_DMM_TYPE:
if (elength < sizeof(struct usb_cdc_dmm_desc))
goto next_desc;
hdr->usb_cdc_dmm_desc =
(struct usb_cdc_dmm_desc *)buffer;
break;
case USB_CDC_MDLM_TYPE:
if (elength < sizeof(struct usb_cdc_mdlm_desc *))
goto next_desc;
if (desc)
return -EINVAL;
desc = (struct usb_cdc_mdlm_desc *)buffer;
break;
case USB_CDC_MDLM_DETAIL_TYPE:
if (elength < sizeof(struct usb_cdc_mdlm_detail_desc *))
goto next_desc;
if (detail)
return -EINVAL;
detail = (struct usb_cdc_mdlm_detail_desc *)buffer;
break;
case USB_CDC_NCM_TYPE:
if (elength < sizeof(struct usb_cdc_ncm_desc))
goto next_desc;
hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer;
break;
case USB_CDC_MBIM_TYPE:
if (elength < sizeof(struct usb_cdc_mbim_desc))
goto next_desc;
hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer;
break;
case USB_CDC_MBIM_EXTENDED_TYPE:
if (elength < sizeof(struct usb_cdc_mbim_extended_desc))
break;
hdr->usb_cdc_mbim_extended_desc =
(struct usb_cdc_mbim_extended_desc *)buffer;
break;
case CDC_PHONET_MAGIC_NUMBER:
hdr->phonet_magic_present = true;
break;
default:
/*
* there are LOTS more CDC descriptors that
* could legitimately be found here.
*/
dev_dbg(&intf->dev, "Ignoring descriptor: type %02x, length %ud\n",
buffer[2], elength);
goto next_desc;
}
cnt++;
next_desc:
buflen -= elength;
buffer += elength;
}
hdr->usb_cdc_union_desc = union_header;
hdr->usb_cdc_header_desc = header;
hdr->usb_cdc_mdlm_detail_desc = detail;
hdr->usb_cdc_mdlm_desc = desc;
hdr->usb_cdc_ether_desc = ether;
return cnt;
}
EXPORT_SYMBOL(cdc_parse_cdc_header);
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2915_0 |
crossvul-cpp_data_bad_901_0 | /****************************************************************************
*
* Copyright (C) 2006,2007 A.Kleine
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
****************************************************************************/
#define _GNU_SOURCE 1
//#define DEBUGSTACK
#define DECOMP_SWITCH
// #define DEBUGSWITCH
//#define STATEMENT_CLASS
// I have uncommented some buggy class recognition stuff in decompileIF()
// to make work simple code lines like: "if(!a) trace(a);" - ak, November 2006
// To do: add some free()-calls for allocated blocks
#include <assert.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "read.h"
#include "action.h"
#include "swftypes.h"
#include "../src/blocks/error.h"
#include "vasprintf.h"
static char **pool;
static unsigned short poolcounter;
struct SWF_ACTIONPUSHPARAM *regs[256];
static char *getName(struct SWF_ACTIONPUSHPARAM *act);
static int offseoloop; // offset wherever a break can jump to (loops and switch)
static void
dumpRegs()
{
int i;
for(i=0;i<6;i++)
if( regs[i] )
printf("reg[%d] %s\n", i, getName(regs[i]));
}
/*
* Start Package
*
* A package to build up a string that can be returned to the caller
* ak/2006: Extended for temporary swichting to a 2nd buffer
*/
#define USE_LIB 1
static int strsize=0;
static int strmaxsize=0;
static char *dcstr=NULL;
static char *dcptr=NULL;
#define DCSTRSIZE 40960
#define PARAM_STRSIZE 512
void
dcinit()
{
strsize = 1; // We start with empty string, i.e. \0
strmaxsize=DCSTRSIZE;
dcstr=calloc(DCSTRSIZE,1);
dcptr=dcstr;
}
void
dcchkstr(int size)
{
while( (strsize+size) > strmaxsize ) {
dcstr=realloc(dcstr,strmaxsize+DCSTRSIZE);
strmaxsize+=DCSTRSIZE;
dcptr=dcstr+strsize;
}
}
void
dcputs(const char *s)
{
int len=strlen(s);
dcchkstr(len);
strcat(dcptr,s);
dcptr+=len;
strsize+=len;
}
void
dcputchar(char c)
{
dcchkstr(1);
*dcptr++=c;
*dcptr='\000';
strsize++;
}
int
dcprintf(char *format, ...)
{
char *s;
size_t size;
int ret;
va_list args;
va_start(args,format);
ret = vasprintf(&s,format,args);
dcputs(s);
size=strlen(s);
free(s);
return size;
}
char *
dcgetstr()
{
char *ret;
ret = dcstr;
dcstr=NULL;
strmaxsize=0;
return ret;
}
struct strbufinfo
{
int size;
int maxsize;
char *str;
char *ptr;
};
static struct strbufinfo setTempString(void)
{
struct strbufinfo current;
current.size=strsize;
current.maxsize=strmaxsize;
current.str=dcstr;
current.ptr=dcptr;
dcinit();
return current;
}
static void setOrigString(struct strbufinfo old)
{
free(dcstr); /* not needed anymore */
strsize=old.size;
strmaxsize=old.maxsize;
dcstr=old.str;
dcptr=old.ptr;
}
// a variant of setOrigString()
// but for further usage of 2nd buffer
//
static char *
switchToOrigString(struct strbufinfo old)
{
char *tmp=dcstr;
strsize=old.size;
strmaxsize=old.maxsize;
dcstr=old.str;
dcptr=old.ptr;
return tmp;
}
#if USE_LIB
#define puts(s) dcputs(s)
#define putchar(c) dcputchar(c)
#define printf dcprintf
#endif
#define INDENT { int ii=gIndent; while(--ii>=0) { putchar(' '); putchar(' '); } }
/* String used for terminating lines (see println) */
static const char* newlinestring = "\\\n";
/* Set the newline character. By default it is an escaped NL. */
void
setNewLineString(const char* ch)
{
newlinestring = ch;
}
/* Print a line with a terminating newline, which can be set by
* setNewLineString()
*/
static void
println(const char* fmt, ...)
{
char *tmp;
int written;
va_list ap;
va_start (ap, fmt);
written = vasprintf (&tmp, fmt, ap);
dcprintf("%s%s", tmp, newlinestring);
free(tmp);
}
/* End Package */
/*
* Start Package
*
* A package to maintain escaped characters strings
* [ BSC == BackSlashCounter ]
*/
#define BSC 2
static int strlenext(char *str)
{
int i=0;
while (*str)
{
i++;
if (*str=='\'') i+=BSC;
str++;
}
return i;
}
static char* strcpyext(char *dest,char *src)
{
char *r=dest;
while (*src)
{
if (*src=='\'')
{
*dest++='\\';
#if BSC == 2
*dest++='\\';
#endif
}
*dest++=*src++;
}
*dest='\0';
return r;
}
static char* strcatext(char *dest,char *src)
{
char *r=dest;
while (*dest)
dest++;
strcpyext(dest,src);
return r;
}
/* End Package */
/*
* Start Package
*
* A package to maintain a representation of the Flash VM stack
*/
struct _stack {
char type;
struct SWF_ACTIONPUSHPARAM *val;
struct _stack *next;
};
struct _stack *Stack;
enum
{
PUSH_STRING = 0,
PUSH_FLOAT = 1,
PUSH_NULL = 2,
PUSH_UNDEF = 3,
PUSH_REGISTER = 4,
PUSH_BOOLEAN = 5,
PUSH_DOUBLE = 6,
PUSH_INT = 7,
PUSH_CONSTANT = 8,
PUSH_CONSTANT16 = 9,
PUSH_VARIABLE = 10,
};
static char *
getString(struct SWF_ACTIONPUSHPARAM *act)
{
char *t;
#ifdef DEBUG
printf("*getString* type=%d\n",act->Type);
#endif
switch( act->Type )
{
case PUSH_STRING:
if (!act->p.String) /* Not a NULL string */
{
SWF_warn("WARNING: Call to getString with NULL string.\n");
break;
}
t=malloc(strlen(act->p.String)+3); /* 2 "'"s and a NULL */
strcpy(t,"'");
strcat(t,act->p.String);
strcat(t,"'");
return t;
case PUSH_NULL: /* NULL */
return "null";
case PUSH_UNDEF: /* Undefined */
return "undefined";
case PUSH_REGISTER: /* REGISTER */
if( regs[act->p.RegisterNumber] &&
regs[act->p.RegisterNumber]->Type != 4 &&
regs[act->p.RegisterNumber]->Type != 7 )
{
return getName(regs[act->p.RegisterNumber]);
}
else
{
t=malloc(5); /* Rddd */
sprintf(t,"R%d", act->p.RegisterNumber );
return t;
}
case PUSH_BOOLEAN: /* BOOLEAN */
if( act->p.Boolean )
return "true";
else
return "false";
case PUSH_DOUBLE: /* DOUBLE */
{
char length_finder[1];
int needed_length = snprintf(length_finder, 1, "%g", act->p.Double) + 1;
if (needed_length <= 0)
{
SWF_warn("WARNING: could not evaluate size of buffer (memory issue ?).\n");
break;
}
t = malloc(needed_length);
sprintf(t, "%g", act->p.Double );
return t;
}
case PUSH_INT: /* INTEGER */
t=malloc(10); /* 32-bit decimal */
sprintf(t,"%ld", act->p.Integer );
return t;
case PUSH_CONSTANT: /* CONSTANT8 */
if (act->p.Constant8 > poolcounter)
{
SWF_warn("WARNING: retrieving constants not present in the pool.\n");
break;
}
t=malloc(strlenext(pool[act->p.Constant8])+3); /* 2 "'"s and a NULL */
strcpy(t,"'");
strcatext(t,pool[act->p.Constant8]);
strcat(t,"'");
return t;
case PUSH_CONSTANT16: /* CONSTANT16 */
if (act->p.Constant16 > poolcounter)
{
SWF_warn("WARNING: retrieving constants not present in the pool.\n");
break;
}
t=malloc(strlenext(pool[act->p.Constant16])+3); /* 2 '\"'s and a NULL */
strcpy(t,"'");
strcatext(t,pool[act->p.Constant16]);
strcat(t,"'");
return t;
case 12:
case 11: /* INCREMENTED or DECREMENTED VARIABLE */
case PUSH_VARIABLE: /* VARIABLE */
return act->p.String;
default:
fprintf (stderr," Can't get string for type: %d\n", act->Type);
break;
}
t = malloc(sizeof(char));
strcpyext(t,"");
return t;
}
static char *
getName(struct SWF_ACTIONPUSHPARAM *act)
{
char *t;
switch( act->Type )
{
case PUSH_STRING: /* STRING */
if (!act->p.String) /* Not a NULL string */
{
SWF_warn("WARNING: Call to getName with NULL string.\n");
break;
}
else if (strlen(act->p.String)) /* Not a zero length string */
{
t=malloc(strlen(act->p.String)+3);
strcpyext(t,act->p.String);
return t;
}
else
{
char *return_string = "this";
t=malloc(strlen(return_string)+1); /* string length + \0 */
strcpyext(t,return_string);
return t;
}
#if 0
case 4: /* REGISTER */
t=malloc(5); /* Rddd */
sprintf(t,"R%d", act->p.RegisterNumber );
return t;
#endif
case PUSH_CONSTANT: /* CONSTANT8 */
if (act->p.Constant8 > poolcounter)
{
SWF_warn("WARNING: retrieving constants not present in the pool.\n");
break;
}
t=malloc(strlenext(pool[act->p.Constant8])+1);
strcpyext(t,pool[act->p.Constant8]);
if(strlen(t)) /* Not a zero length string */
return t;
else
{
t=realloc(t,6);
return strcpy(t,"this");
}
case PUSH_CONSTANT16: /* CONSTANT16 */
if (act->p.Constant16 > poolcounter)
{
SWF_warn("WARNING: retrieving constants not present in the pool.\n");
break;
}
t=malloc(strlenext(pool[act->p.Constant16])+1);
strcpyext(t,pool[act->p.Constant16]);
if(strlen(t)) /* Not a zero length string */
return t;
else
{
t=realloc(t,6);
return strcpy(t,"this");
}
default:
return getString(act);
}
t = malloc(sizeof(char));
strcpyext(t,"");
return t;
}
static int
getInt(struct SWF_ACTIONPUSHPARAM *act)
{
switch( act->Type )
{
case PUSH_FLOAT: /* FLOAT -- also used for PROPERTY storing */
return ((int)act->p.Float);
case PUSH_NULL: /* NULL */
return 0;
case PUSH_REGISTER: /* REGISTER */
return getInt(regs[act->p.RegisterNumber]);
case PUSH_DOUBLE: /* DOUBLE */
return (int)act->p.Double;
case PUSH_INT: /* INTEGER */
return act->p.Integer;
default:
fprintf (stderr," Can't get int for type: %d\n", act->Type);
}
return 0;
}
static char *
getProperty(Property prop)
{
switch(prop)
{
case SWF_SETPROPERTY_X: return("_x"); break;
case SWF_SETPROPERTY_Y:
case PROPERTY_Y: return("_y"); break;
case PROPERTY_XMOUSE: return("_xMouse"); break;
case PROPERTY_YMOUSE: return("_yMouse"); break;
case SWF_SETPROPERTY_XSCALE:
case PROPERTY_XSCALE: return("_xScale"); break;
case SWF_SETPROPERTY_YSCALE:
case PROPERTY_YSCALE: return("_yScale"); break;
case PROPERTY_CURRENTFRAME: return("_currentFrame"); break;
case PROPERTY_TOTALFRAMES: return("_totalFrames"); break;
case SWF_SETPROPERTY_ALPHA:
case PROPERTY_ALPHA: return("_alpha"); break;
case SWF_SETPROPERTY_VISIBILITY:
case PROPERTY_VISIBLE: return("_visible"); break;
case PROPERTY_WIDTH: return("_width"); break;
case PROPERTY_HEIGHT: return("_height"); break;
case SWF_SETPROPERTY_ROTATION:
case PROPERTY_ROTATION: return("_rotation"); break;
case PROPERTY_TARGET: return("_target"); break;
case PROPERTY_FRAMESLOADED: return("_framesLoaded"); break;
case SWF_SETPROPERTY_NAME:
case PROPERTY_NAME: return("_name"); break;
case PROPERTY_DROPTARGET: return("_dropTarget"); break;
case PROPERTY_URL: return("_url"); break;
case SWF_SETPROPERTY_HIGHQUALITY:
case PROPERTY_HIGHQUALITY: return("_quality"); break;
case SWF_SETPROPERTY_SHOWFOCUSRECT:
case PROPERTY_FOCUSRECT: return("_focusRect"); break;
case SWF_SETPROPERTY_SOUNDBUFFERTIME:
case PROPERTY_SOUNDBUFTIME: return("_soundBufTime"); break;
case SWF_SETPROPERTY_WTHIT:
case PROPERTY_WTHIT: return("_WTHIT!?"); break;
default: return("unknown property!"); break;
}
}
struct SWF_ACTIONPUSHPARAM *
newVar(char *var)
{
struct SWF_ACTIONPUSHPARAM *v;
v=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));
v->Type = PUSH_VARIABLE;
v->p.String = var;
return v;
}
struct SWF_ACTIONPUSHPARAM *
newVar2(char *var,char *var2)
{
struct SWF_ACTIONPUSHPARAM *v;
v=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));
v->Type = PUSH_VARIABLE;
v->p.String = malloc(strlen(var)+strlen(var2)+1);
strcpy(v->p.String,var);
strcat(v->p.String,var2);
return v;
}
struct SWF_ACTIONPUSHPARAM *
newVar3(char *var,char *var2, char *var3)
{
struct SWF_ACTIONPUSHPARAM *v;
v=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));
v->Type = PUSH_VARIABLE; /* VARIABLE */
v->p.String = malloc(strlen(var)+strlen(var2)+strlen(var3)+1);
strcpy(v->p.String,var);
strcat(v->p.String,var2);
strcat(v->p.String,var3);
return v;
}
struct SWF_ACTIONPUSHPARAM *
newVar5(char *var,char *var2, char *var3,char *var4,char *var5)
{
struct SWF_ACTIONPUSHPARAM *v;
v=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));
v->Type = PUSH_VARIABLE; /* VARIABLE */
v->p.String = malloc(strlen(var)+strlen(var2)+strlen(var3)+strlen(var4)+strlen(var5)+1);
strcpy(v->p.String,var);
strcat(v->p.String,var2);
strcat(v->p.String,var3);
strcat(v->p.String,var4);
strcat(v->p.String,var5);
return v;
}
void
push(struct SWF_ACTIONPUSHPARAM *val)
{
struct _stack *t;
#ifdef DEBUG
printf("*push* type=%d\n",val->Type);
#endif
t = calloc(1,sizeof(*Stack));
t->type = val->Type;
t->val = val;
t->next = Stack;
Stack = t;
}
void
pushdup()
{
struct _stack *t;
#ifdef DEBUG
printf("*pushdup*\n");
#endif
if(Stack == NULL)
{
SWF_warn("WARNING: pushdup on empty stack. This might be wrong!\n");
return;
}
t = calloc(1,sizeof(*Stack));
t->type = Stack->type;
// If element is a string, perform deep copy of Stack->val->p
if (Stack->val->Type == PUSH_STRING) {
t->val = calloc(1, sizeof(struct SWF_ACTIONPUSHPARAM));
*t->val = *Stack->val;
int len = strlen(Stack->val->p.String) + 1; // NULL terminated
t->val->p.String = calloc(len, sizeof(char));
strcpy(t->val->p.String, Stack->val->p.String);
} else {
t->val = Stack->val;
}
t->next = Stack;
Stack = t;
}
void
pushvar(struct SWF_ACTIONPUSHPARAM *val)
{
struct _stack *t;
#ifdef DEBUG
printf("*pushvar*\n");
#endif
t = calloc(1,sizeof(*Stack));
t->type = 'v'; // ???
t->val = val;
t->next = Stack;
Stack = t;
}
struct SWF_ACTIONPUSHPARAM * pop()
{
struct _stack *t;
struct SWF_ACTIONPUSHPARAM * ret;
#ifdef DEBUG
printf("*pop*\n");
#endif
#ifdef DEBUGSTACK /* continue w stack dummy */
if( Stack == NULL ) push(newVar("// *** pop(): INTERNAL STACK ERROR FOUND ***"));
#else
if( Stack == NULL ) SWF_error("Stack blown!! - pop");
#endif
t=Stack;
Stack=t->next;
ret=t->val;
return ret;
}
struct SWF_ACTIONPUSHPARAM * peek()
{
#ifdef DEBUG
printf("*peek*\n");
#endif
#ifdef DEBUGSTACK /* continue w stack dummy */
if( Stack == NULL ) push(newVar("// *** peek(): INTERNAL STACK ERROR FOUND ***"));
#else
if( Stack == NULL ) SWF_error("Stack blown!! - peek");
#endif
return Stack->val;
}
void
stackswap()
{
#ifdef DEBUG
printf("*stackswap*\n");
#endif
struct SWF_ACTIONPUSHPARAM *p = peek(); /* peek() includes error handling */
char type = Stack->type;
if (Stack->next == NULL) {
#if DEBUG
SWF_warn("stackswap: can't swap (stack contains only one element)\n");
#endif
return;
}
Stack->type = Stack->next->type;
Stack->val = Stack->next->val;
Stack->next->type = type;
Stack->next->val = p;
}
static struct SWF_ACTIONPUSHPARAM *
newVar_N(char *var,char *var2, char *var3,char *var4,int pop_counter,char *final)
{
struct SWF_ACTIONPUSHPARAM *v;
int psize=PARAM_STRSIZE;
int i;
int slen=strlen(var)+strlen(var2)+strlen(var3)+strlen(var4)+strlen(final);
v=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));
v->p.String = malloc(psize + slen);
v->Type = PUSH_VARIABLE;
strcpy(v->p.String,var);
strcat(v->p.String,var2);
strcat(v->p.String,var3);
strcat(v->p.String,var4);
for(i=0;i<pop_counter;i++)
{
char *pops=getString(pop());
while ( strlen(v->p.String)+ 2 + strlen(pops) +slen >= psize)
{
psize += PARAM_STRSIZE;
v->p.String = realloc( v->p.String, psize);
}
strcat(v->p.String,pops);
if( i < pop_counter-1 )
strcat(v->p.String,",");
}
strcat(v->p.String,final);
return v;
}
// similar to newVar_N(),
// but pops 2 items from stack per counter,
// and second of them we are interested in getName() instead of getString()
static struct SWF_ACTIONPUSHPARAM *
newVar_N2(char *var,char *var2, char *var3,char *var4,int pop_counter,char *final)
{
struct SWF_ACTIONPUSHPARAM *v;
int psize=PARAM_STRSIZE;
int i;
int slen=strlen(var)+strlen(var2)+strlen(var3)+strlen(var4)+strlen(final);
v=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));
v->p.String = malloc(psize + slen);
v->Type = PUSH_VARIABLE;
strcpy(v->p.String,var);
strcat(v->p.String,var2);
strcat(v->p.String,var3);
strcat(v->p.String,var4);
for(i=0;i<pop_counter;i++)
{
char *pops1=getString(pop());
char *pops2=getName (pop());
while ( strlen(v->p.String)+ 3 + strlen(pops1)+ strlen(pops2) +slen >= psize)
{
psize += PARAM_STRSIZE;
v->p.String = realloc( v->p.String, psize);
}
strcat(v->p.String,pops2);
strcat(v->p.String,":");
strcat(v->p.String,pops1);
if( i < pop_counter-1 )
strcat(v->p.String,",");
}
strcat(v->p.String,final);
return v;
}
/* End Package */
static int gIndent;
static void decompileActions(int n, SWF_ACTION *actions,int indent);
char * decompile5Action(int n, SWF_ACTION *actions,int indent);
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
#define SanityCheck(curact,test,msg ) \
if(!(test) ) SWF_error( "SanityCheck failed in %s\n %s\n", #curact, msg );
#define OUT_BEGIN(block) \
struct block *sact = (struct block *)act;
#define OUT_BEGIN2(block) \
struct block *sact = (struct block *)&(actions[n]);
static void
decompileCONSTANTPOOL (SWF_ACTION *act)
{
OUT_BEGIN(SWF_ACTIONCONSTANTPOOL);
pool=sact->ConstantPool;
poolcounter = sact->Count;
}
static void
decompileWAITFORFRAME (SWF_ACTION *act)
{
OUT_BEGIN(SWF_ACTIONWAITFORFRAME);
INDENT
println("WaitForFrame(%d,%d);", sact->Frame,sact->SkipCount);
}
static void
decompilePUSHPARAM (struct SWF_ACTIONPUSHPARAM *act, int wantstring)
{
char *t;
switch( act->Type )
{
case PUSH_STRING: /* STRING */
if( wantstring ) printf ("'%s'", act->p.String);
else printf ("%s", act->p.String);
break;
case PUSH_FLOAT: /* FLOAT */
printf ("%f", act->p.Float);
break;
case PUSH_NULL: /* NULL */
printf ("NULL" );
break;
case PUSH_UNDEF: /* Undefined */
printf ("undefined" );
break;
case PUSH_REGISTER: /* Register */
if( regs[act->p.RegisterNumber] ) {
printf ("%s", getName(act));
} else {
printf ("R%d", (int)act->p.RegisterNumber);
}
break;
case PUSH_BOOLEAN: /* BOOLEAN */
printf ("%s", act->p.Boolean?"true":"false");
break;
case PUSH_DOUBLE: /* DOUBLE */
printf ("%g", act->p.Double);
break;
case PUSH_INT: /* INTEGER */
printf ("%ld", act->p.Integer);
break;
case PUSH_CONSTANT: /* CONSTANT8 */
case PUSH_CONSTANT16: /* CONSTANT16 */
if( wantstring ) t=getString(act);
else t=getName(act);
puts(t);
free(t);
break;
#if 0
case 8: /* CONSTANT8 */
if (act->p.Constant8 > poolcounter)
{
SWF_warn("WARNING: retrieving constants not present in the pool.\n");
break;
}
if( wantstring )
printf ("'%s'", pool[act->p.Constant8]);
else
printf ("%s", pool[act->p.Constant8]);
break;
case 9: /* CONSTANT16 */
if (act->p.Constant16 > poolcounter)
{
SWF_warn("WARNING: retrieving constants not present in the pool.\n");
break;
}
if( wantstring )
printf ("'%s'", pool[act->p.Constant16]);
else
printf ("%s", pool[act->p.Constant16]);
break;
#endif
case 12:
case 11: /* INCREMENTED or DECREMENTED VARIABLE */
case PUSH_VARIABLE: /* VARIABLE */
printf ("%s", act->p.String);
break;
default:
printf (" Unknown type: %d\n", act->Type);
}
}
static void
decompileGETURL (SWF_ACTION *act)
{
OUT_BEGIN(SWF_ACTIONGETURL);
INDENT
println("getUrl('%s',%s);", sact->UrlString, sact->TargetString);
}
static int
decompileGETURL2 (SWF_ACTION *act)
{
struct SWF_ACTIONPUSHPARAM *a,*b;
OUT_BEGIN(SWF_ACTIONGETURL2);
INDENT
a = pop();
b = pop();
if (sact->f.FlagBits.SendVarsMethod==3)
puts("loadVariables(");
else
{
if (sact->f.FlagBits.SendVarsMethod==2)
puts("loadVariablesNum(");
else
{
if (sact->f.FlagBits.SendVarsMethod==1)
puts("loadMovie(");
else
{
if (*getName(a)=='_') // found a _level
puts("loadMovieNum(");
else
puts("getURL(");
}
}
}
decompilePUSHPARAM (b, 1);
puts(",");
decompilePUSHPARAM (a, 1);
if (sact->f.FlagBits.LoadVariableFlag)
puts(",'GET'");
if (sact->f.FlagBits.LoadTargetFlag)
puts(",'POST'");
println(");");
return 0;
}
static inline int OpCode(SWF_ACTION *actions, int n, int maxn)
{
if(!n || n >= maxn)
{
#if DEBUG
SWF_warn("OpCode: want %i, max %i\n", n, maxn);
#endif
return -999;
} else if (n < 1) {
#if DEBUG
SWF_warn("OpCode: want %i < 1\n", n);
#endif
return -998;
}
return actions[n].SWF_ACTIONRECORD.ActionCode;
}
static int
isStoreOp(int n, SWF_ACTION *actions,int maxn)
{
switch(OpCode(actions, n, maxn))
{
case SWFACTION_STOREREGISTER:
case SWFACTION_SETVARIABLE:
case SWFACTION_SETMEMBER:
case SWFACTION_CASTOP:
return 1;
default:
return 0;
}
}
static int
decompileGOTOFRAME(int n, SWF_ACTION *actions,int maxn,int islabel)
{
int i=0;
struct SWF_ACTIONGOTOLABEL *sactv2;
OUT_BEGIN2(SWF_ACTIONGOTOFRAME);
sactv2 = (struct SWF_ACTIONGOTOLABEL*)sact;
INDENT
if (OpCode(actions, n+1, maxn) == SWFACTION_PLAY)
{
i=1;
puts("gotoAndPlay(");
}
else
{
if (OpCode(actions, n+1, maxn) == SWFACTION_STOP)
i=1;
puts("gotoAndStop(");
}
if (islabel)
println("'%s');", sactv2->FrameLabel);
else
println("%d);", sact->Frame+1); /* GOTOFRAME arg is 0-based */
return i;
}
static int
decompileGOTOFRAME2(int n, SWF_ACTION *actions, int maxn)
{
int i=0;
OUT_BEGIN2(SWF_ACTIONGOTOFRAME2);
INDENT
if (n+1 < maxn)
{
if (OpCode(actions, n+1, maxn) == SWFACTION_PLAY ||
OpCode(actions, n+1, maxn) == SWFACTION_STOP)
i=1;
if (OpCode(actions, n+1, maxn) == SWFACTION_PLAY)
puts("gotoAndPlay(");
else
{
if (OpCode(actions, n+1, maxn) == SWFACTION_STOP)
puts("gotoAndStop(");
else
{
if (sact->f.FlagBits.PlayFlag)
puts("gotoAndPlay(");
else
puts("gotoAndStop(");
}
}
}
else
{
if (sact->f.FlagBits.PlayFlag)
puts("gotoAndPlay(");
else
puts("gotoAndStop(");
}
decompilePUSHPARAM(pop(),0);
println(");");
return i;
}
static int precedence(int op1,int op2)
{
static unsigned char ops[]= { // array of opcodes w rising precedence
// SWFACTION_SETVARIABLE, // TAKE CARE: array is incomplete
// SWFACTION_TRACE,
// missing ops are considered with low precedence
SWFACTION_LOGICALOR,
SWFACTION_LOGICALAND,
SWFACTION_BITWISEOR,
SWFACTION_BITWISEXOR,
SWFACTION_BITWISEAND,
SWFACTION_STRICTEQUALS,
SWFACTION_EQUALS2,
SWFACTION_EQUAL,
SWFACTION_GREATER,
SWFACTION_LESSTHAN,
SWFACTION_LESS2,
SWFACTION_SHIFTRIGHT,
SWFACTION_SHIFTRIGHT2,
SWFACTION_SHIFTLEFT,
SWFACTION_ADD,
SWFACTION_ADD2,
SWFACTION_SUBTRACT,
SWFACTION_MODULO,
SWFACTION_MULTIPLY,
SWFACTION_DIVIDE,
SWFACTION_LOGICALNOT,
SWFACTION_PUSH // FIXME: need more analysis on code after PUSH
};
unsigned char* f=memchr(ops,op1,sizeof(ops));
unsigned char* s=memchr(ops,op2,sizeof(ops));
#ifdef DEBUG
printf("1op=%d 2op=%d result=%d\n",op1,op2,f>s);
if (!f) printf("opcode=%d NOT in precedence list\n",op1);
if (!s) printf("opcode=%d NOT in precedence list\n",op2);
#endif
return f>s;
}
#ifdef DECOMP_SWITCH
static int
check_switch(int firstcode)
{
return (firstcode == SWFACTION_PUSH || firstcode == SWFACTION_JUMP);
}
#endif
static int
decompileArithmeticOp(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *left, *right;
int op_l = OpCode(actions, n, maxn);
int op_r = OpCode(actions, n+1, maxn);
right=pop();
left=pop();
switch(OpCode(actions, n, maxn))
{
/*
case SWFACTION_GETMEMBER:
decompilePUSHPARAM(peek(),0);
break;
*/
case SWFACTION_INSTANCEOF:
if (precedence(op_l, op_r))
push(newVar3(getString(left)," instanceof ",getString(right)));
else
push(newVar_N("(",getString(left)," instanceof ",getString(right),0,")"));
break;
case SWFACTION_ADD:
case SWFACTION_ADD2:
if (precedence(op_l, op_r))
push(newVar3(getString(left),"+",getString(right)));
else
push(newVar_N("(",getString(left),"+",getString(right),0,")"));
break;
case SWFACTION_SUBTRACT:
if (precedence(op_l, op_r))
push(newVar3(getString(left),"-",getString(right)));
else
push(newVar_N("(",getString(left),"-",getString(right),0,")"));
break;
case SWFACTION_MULTIPLY:
if (precedence(op_l, op_r))
push(newVar3(getString(left),"*",getString(right)));
else
push(newVar_N("(",getString(left),"*",getString(right),0,")"));
break;
case SWFACTION_DIVIDE:
if (precedence(op_l, op_r))
push(newVar3(getString(left),"/",getString(right)));
else
push(newVar_N("(",getString(left),"/",getString(right),0,")"));
break;
case SWFACTION_MODULO:
if (precedence(op_l, op_r))
push(newVar3(getString(left),"%",getString(right)));
else
push(newVar_N("(",getString(left),"%",getString(right),0,")"));
break;
case SWFACTION_SHIFTLEFT:
if (precedence(op_l, op_r))
push(newVar3(getString(left),"<<",getString(right)));
else
push(newVar_N("(",getString(left),"<<",getString(right),0,")"));
break;
case SWFACTION_SHIFTRIGHT:
if (precedence(op_l, op_r))
push(newVar3(getString(left),">>",getString(right)));
else
push(newVar_N("(",getString(left),">>",getString(right),0,")"));
break;
case SWFACTION_SHIFTRIGHT2:
if (precedence(op_l, op_r))
push(newVar3(getString(left),">>>",getString(right)));
else
push(newVar_N("(",getString(left),">>>",getString(right),0,")"));
break;
case SWFACTION_LOGICALAND:
if (precedence(op_l, op_r))
push(newVar3(getString(left),"&&",getString(right)));
else
push(newVar_N("(",getString(left),"&&",getString(right),0,")"));
break;
case SWFACTION_LOGICALOR:
if (precedence(op_l, op_r))
push(newVar3(getString(left),"||",getString(right)));
else
push(newVar_N("(",getString(left),"||",getString(right),0,")"));
break;
case SWFACTION_BITWISEAND:
if (precedence(op_l, op_r))
push(newVar3(getString(left),"&",getString(right)));
else
push(newVar_N("(",getString(left),"&",getString(right),0,")"));
break;
case SWFACTION_BITWISEOR:
if (precedence(op_l, op_r))
push(newVar3(getString(left),"|",getString(right)));
else
push(newVar_N("(",getString(left),"|",getString(right),0,")"));
break;
case SWFACTION_BITWISEXOR:
if (precedence(op_l, op_r))
push(newVar3(getString(left),"^",getString(right)));
else
push(newVar_N("(",getString(left),"^",getString(right),0,")"));
break;
case SWFACTION_EQUALS2: /* including negation */
case SWFACTION_EQUAL:
if( OpCode(actions, n+1, maxn) == SWFACTION_LOGICALNOT &&
OpCode(actions, n+2, maxn) != SWFACTION_IF)
{
op_r = OpCode(actions, n+1, maxn);
if (precedence(op_l, op_r))
push(newVar3(getString(left),"!=",getString(right)));
else
push(newVar_N("(",getString(left),"!=",getString(right),0,")"));
return 1; /* due negation op */
}
if (precedence(op_l, op_r))
push(newVar3(getString(left),"==",getString(right)));
else
push(newVar_N("(",getString(left),"==",getString(right),0,")"));
break;
case SWFACTION_LESS2:
if( OpCode(actions, n+1, maxn) == SWFACTION_LOGICALNOT &&
OpCode(actions, n+2, maxn) != SWFACTION_IF )
{
op_r = OpCode(actions, n+2, maxn);
if (precedence(op_l, op_r))
push(newVar3(getString(left),">=",getString(right)));
else
push(newVar_N("(",getString(left),">=",getString(right),0,")"));
return 1; /* due negation op */
}
if (precedence(op_l, op_r))
push(newVar3(getString(left),"<",getString(right)));
else
push(newVar_N("(",getString(left),"<",getString(right),0,")"));
break;
case SWFACTION_GREATER:
if (precedence(op_l, op_r))
push(newVar3(getString(left),">",getString(right)));
else
push(newVar_N("(",getString(left),">",getString(right),0,")"));
break;
case SWFACTION_LESSTHAN:
if (precedence(op_l, op_r))
push(newVar3(getString(left),"<",getString(right)));
else
push(newVar_N("(",getString(left),"<",getString(right),0,")"));
break;
case SWFACTION_STRINGEQ:
if (precedence(op_l, op_r))
push(newVar3(getString(left),"==",getString(right)));
else
push(newVar_N("(",getString(left),"==",getString(right),0,")"));
break;
case SWFACTION_STRINGCOMPARE:
puts("STRINGCOMPARE");
break;
case SWFACTION_STRICTEQUALS:
#ifdef DECOMP_SWITCH
if (OpCode(actions, n, maxn) == SWFACTION_IF)
{
int code = actions[n+1].SWF_ACTIONIF.Actions[0].SWF_ACTIONRECORD.ActionCode;
if(check_switch(code))
{
push(right); // keep left and right side separated
push(left); // because it seems we have found a switch(){} and
break; // let decompileIF() once more do all the dirty work
}
}
#endif
if( OpCode(actions, n+1, maxn) == SWFACTION_LOGICALNOT &&
OpCode(actions, n+2, maxn) != SWFACTION_IF )
{
op_r = OpCode(actions, n+2, maxn);
if (precedence(op_l, op_r))
push(newVar3(getString(left),"!==",getString(right)));
else
push(newVar_N("(",getString(left),"!==",getString(right),0,")"));
return 1; /* due negation op */
} else {
if (precedence(op_l, op_r))
push(newVar3(getString(left),"===",getString(right)));
else
push(newVar_N("(",getString(left),"===",getString(right),0,")"));
break;
}
default:
printf("Unhandled Arithmetic/Logic OP %x\n",
OpCode(actions, n, maxn));
}
return 0;
}
static int
isLogicalOp(int n, SWF_ACTION *actions, int maxn)
{
switch(OpCode(actions, n, maxn))
{
case SWFACTION_LESSTHAN:
case SWFACTION_LOGICALAND:
case SWFACTION_LOGICALOR:
case SWFACTION_LOGICALNOT:
case SWFACTION_STRINGEQ:
case SWFACTION_STRINGCOMPARE:
case SWFACTION_LESS2:
case SWFACTION_EQUALS2:
case SWFACTION_EQUAL:
case SWFACTION_BITWISEAND:
case SWFACTION_BITWISEOR:
case SWFACTION_BITWISEXOR:
case SWFACTION_STRICTEQUALS:
case SWFACTION_GREATER:
/*
case SWFACTION_GETMEMBER:
*/
return 1;
default:
return 0;
}
}
static int
isLogicalOp2(int n, SWF_ACTION *actions,int maxn)
{
switch(OpCode(actions, n, maxn))
{
case SWFACTION_LOGICALNOT:
case SWFACTION_PUSHDUP:
case SWFACTION_IF:
return 1;
default:
return 0;
}
}
static int
stackVal(int n, SWF_ACTION *actions)
{
if (!n)
return 0;
switch((actions[n-1]).SWF_ACTIONRECORD.ActionCode)
{
case SWFACTION_LOGICALNOT:
case SWFACTION_DECREMENT:
case SWFACTION_INCREMENT:
case SWFACTION_RANDOMNUMBER:
case SWFACTION_TOSTRING:
case SWFACTION_TONUMBER:
case SWFACTION_ORD:
case SWFACTION_CHR:
case SWFACTION_MBORD:
case SWFACTION_MBCHR:
case SWFACTION_INT:
case SWFACTION_GETVARIABLE:
case SWFACTION_SUBSTRING:
case SWFACTION_MBSUBSTRING:
case SWFACTION_GETMEMBER:
case SWFACTION_ADD:
case SWFACTION_ADD2:
case SWFACTION_SUBTRACT:
case SWFACTION_MULTIPLY:
case SWFACTION_DIVIDE:
case SWFACTION_MODULO:
case SWFACTION_BITWISEAND:
case SWFACTION_BITWISEOR:
case SWFACTION_BITWISEXOR:
case SWFACTION_LESSTHAN:
case SWFACTION_LOGICALAND:
case SWFACTION_LOGICALOR:
case SWFACTION_STRINGEQ:
case SWFACTION_STRINGCOMPARE:
case SWFACTION_LESS2:
case SWFACTION_EQUALS2:
case SWFACTION_EQUAL:
case SWFACTION_STRICTEQUALS:
case SWFACTION_GREATER:
case SWFACTION_STRINGGREATER:
case SWFACTION_STRINGCONCAT:
case SWFACTION_SHIFTLEFT:
case SWFACTION_SHIFTRIGHT:
case SWFACTION_SHIFTRIGHT2:
case SWFACTION_INSTANCEOF:
case SWFACTION_CALLMETHOD:
case SWFACTION_CALLFUNCTION:
case SWFACTION_GETTIME:
case SWFACTION_GETPROPERTY:
case SWFACTION_PUSH:
case SWFACTION_DELETE:
case SWFACTION_DELETE2:
case SWFACTION_MBLENGTH:
case SWFACTION_STRINGLENGTH:
case SWFACTION_CASTOP:
case SWFACTION_TYPEOF:
case SWFACTION_PUSHDUP:
return 1;
default:
return 0;
}
}
static int
decompileLogicalNot(int n, SWF_ACTION *actions, int maxn)
{
#ifdef STATEMENT_CLASS
if(OpCode(actions, n-1, maxn) == SWFACTION_GETVARIABLE &&
OpCode(actions, n+1, maxn) == SWFACTION_LOGICALNOT &&
OpCode(actions, n+2, maxn) == SWFACTION_IF )
{
/* It's a class statement -- skip over both NOTs */
return 1;
}
#endif
if(OpCode(actions, n+1, maxn) != SWFACTION_IF )
push(newVar2("!",getString(pop())));
return 0;
}
static void
decompilePUSH (SWF_ACTION *act)
{
int i;
OUT_BEGIN(SWF_ACTIONPUSH);
SanityCheck(SWF_PUSH,
act->SWF_ACTIONRECORD.ActionCode == SWFACTION_PUSH,
"not a PUSH")
for(i=0;i<sact->NumParam;i++)
push(&(sact->Params[i]));
}
static void
decompilePUSHDUP (SWF_ACTION *act)
{
SanityCheck(SWF_PUSHDUP,
act->SWF_ACTIONRECORD.ActionCode == SWFACTION_PUSHDUP,
"not a PUSHDUP")
pushdup();
}
static void
decompileSTACKSWAP (SWF_ACTION *act)
{
SanityCheck(SWF_STACKSWAP,
act->SWF_ACTIONRECORD.ActionCode == SWFACTION_STACKSWAP,
"not a STACKSWAP")
stackswap();
}
static int
decompileSETPROPERTY(int n, SWF_ACTION *actions,int maxn)
{
struct SWF_ACTIONPUSHPARAM *val, *idx, *obj;
INDENT
val = pop();
idx = pop();
obj = pop();
#ifdef DEBUG
printf("*setProp* objName %s (type=%d) Prop (type=%d) =%x\n",
getName(obj), obj->Type, idx->Type,getInt(idx));
#endif
if (obj->Type == PUSH_VARIABLE)
puts("eval(");
decompilePUSHPARAM(obj,0);
if (obj->Type == PUSH_VARIABLE)
puts(")");
puts(".");
puts(getProperty(getInt(idx)));
printf(" = " );
decompilePUSHPARAM(val,0);
println(";");
return 0;
}
static int
decompileGETPROPERTY(int n, SWF_ACTION *actions,int maxn)
{
struct SWF_ACTIONPUSHPARAM *idx, *obj;
INDENT
idx = pop();
obj = pop();
#ifdef DEBUG
printf("*GETProp* objName %s (type=%d) Prop (type=%d) =%x\n",
getName(obj), obj->Type, idx->Type,getInt(idx));
#endif
if (obj->Type == PUSH_VARIABLE)
push( newVar5("eval(",getName(obj),".",getProperty(getInt(idx)),")"));
else
push( newVar3( getName(obj),".",getProperty(getInt(idx))));
return 0;
}
static int
decompileTRACE(int n, SWF_ACTION *actions, int maxn)
{
INDENT
puts("trace(");
decompilePUSHPARAM(pop(),1);
println(");");
return 0;
}
static int
decompileCALLFRAME(int n, SWF_ACTION *actions, int maxn)
{
INDENT
puts("callFrame(");
decompilePUSHPARAM(pop(),1);
println(");");
return 0;
}
static int
decompileGETTIME(int n, SWF_ACTION *actions, int maxn)
{
if (OpCode(actions, n+1, maxn) == SWFACTION_POP)
{
INDENT
println("getTimer();");
return 1;
}
else
{
push(newVar("getTimer()"));
return 0;
}
}
static int
decompileINCR_DECR(int n, SWF_ACTION *actions, int maxn, int is_incr)
{
int is_postop;
struct SWF_ACTIONPUSHPARAM *var=pop();
char *dblop=is_incr ? "++":"--";
if((OpCode(actions, n, maxn) == SWFACTION_PUSHDUP
|| OpCode(actions, n+1, maxn) == SWFACTION_PUSHDUP
|| OpCode(actions, n+1, maxn) == SWFACTION_SETVARIABLE)
|| ( OpCode(actions, n-1, maxn) == SWFACTION_GETVARIABLE
&& OpCode(actions, n+1, maxn) == SWFACTION_STOREREGISTER
&& OpCode(actions, n+1, maxn) == SWFACTION_SETVARIABLE))
{
is_postop=(OpCode(actions, n-1, maxn) == SWFACTION_PUSHDUP)?1:0;
if (is_postop)
var = newVar2(getString(var),dblop);
else
var = newVar2(dblop,getString(var));
if (OpCode(actions, n+1, maxn) == SWFACTION_SETVARIABLE)
{
var->Type=11; /* later trigger printing variable inc/dec */
}
else
{
var->Type=12; /* later be quiet, see decompileSETVARIABLE() */
if (is_postop)
{
pop();
push(var); /* will duplicate stacktop */
}
}
push(var);
}
else
{
if((OpCode(actions, n-1, maxn) == SWFACTION_GETMEMBER &&
OpCode(actions, n+1, maxn) == SWFACTION_STOREREGISTER &&
OpCode(actions, n+2, maxn) == SWFACTION_SETMEMBER ) ||
(OpCode(actions, n-1, maxn) == SWFACTION_STOREREGISTER &&
OpCode(actions, n+1, maxn) == SWFACTION_SETMEMBER &&
OpCode(actions, n+2, maxn) == SWFACTION_PUSH ) ||
(OpCode(actions, n-1, maxn) == SWFACTION_PUSH &&
OpCode(actions, n+1, maxn) == SWFACTION_SETMEMBER) ||
(OpCode(actions, n-3, maxn) == SWFACTION_GETMEMBER &&
OpCode(actions, n-2, maxn) == SWFACTION_PUSH &&
OpCode(actions, n-1, maxn) == SWFACTION_GETMEMBER &&
OpCode(actions, n+1, maxn) == SWFACTION_SETMEMBER &&
((struct SWF_ACTIONPUSH *)&actions[n-2].SWF_ACTIONRECORD)->NumParam >= 4
/* 4: a pair of get/set - FIXME: add more analysis about stack here */))
{ // incr/decr object variables with side effects
is_postop= (OpCode(actions, n+1, maxn) == SWFACTION_SETMEMBER)?1:0;
if (is_postop)
var = newVar2(getString(var),dblop);
else
var = newVar2(dblop,getString(var));
if (is_postop && OpCode(actions, n-1, maxn) == SWFACTION_PUSH)
pop();
if(OpCode(actions, n+1, maxn) == SWFACTION_GETMEMBER)
pop();
pop();
pop();
var->Type=12; // to be quiet later in ...SETMEMBER()
regs[0]=var; // FIXME: r0 perhaps a ming special
push(var);
push(var);
push(var);
if (is_postop && OpCode(actions, n-1, maxn) == SWFACTION_PUSH )
push(var);
if (is_postop && OpCode(actions, n-1, maxn) == SWFACTION_GETMEMBER )
push(var);
}
else
{
if(OpCode(actions, n-1, maxn) == SWFACTION_PUSH &&
OpCode(actions, n+1, maxn) == SWFACTION_STOREREGISTER &&
regs[actions[n+1].SWF_ACTIONSTOREREGISTER.Register]->Type == PUSH_VARIABLE)
{
var = newVar2(dblop,getString(var));
if ((OpCode(actions, n+2, maxn) == SWFACTION_POP
&& actions[n-1].SWF_ACTIONPUSH.NumParam==1)
|| OpCode(actions, n+3, maxn) == SWFACTION_POP)
{
var->Type=11; // later print inc/dec
}
else
{
var->Type=12; // later be quiet in ..STOREREGISTER()
if (actions[n-1].SWF_ACTIONPUSH.NumParam>1)
{
pop();
push(var);
}
}
push(var);
}
else // fallback to old incr/decr code
{ // FIXME: this is bad designed for handling side effect code
INDENT // like post-incrementing a function argument etc.
decompilePUSHPARAM(var,0);
puts(dblop);
println(";");
push(var);
}
}
}
return 0;
}
static int
decompileSTOREREGISTER(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *data;
OUT_BEGIN2(SWF_ACTIONSTOREREGISTER);
data=peek();
if (!regs[sact->Register] || sact->Register==0 ) // ===internal===
{
regs[sact->Register] = data;
}
else // ===user visible level===
{
if ( regs[sact->Register]->Type == PUSH_VARIABLE) // V7: a named function parameter in register
{ // V7: a local var in register
if (data->Type==12)
data->Type = PUSH_VARIABLE; // do nothing, but only once
else
{
char *l=getName(regs[sact->Register]);
char *r=getName(data);
if (strcmp(l,r))
{
INDENT
if (data->Type==11)
{
println("%s;", r);
}
else
{
printf("%s = ",l);
decompilePUSHPARAM(data,1);
println(";");
}
}
}
}
}
return 0;
}
static int
decompileNEWOBJECT(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *obj, *nparam;
obj = pop();
nparam=pop();
push(newVar_N("new ","",getName(obj),"(", nparam->p.Integer,")"));
return 0;
}
static int
decompileNEWMETHOD(int n, SWF_ACTION *actions, int maxn)
{
char *t;
struct SWF_ACTIONPUSHPARAM *meth, *nparam, *obj;
meth = pop();
obj = pop();
nparam=pop();
t=malloc(strlen( getName(obj) ) +2);
strcpy(t,getName(obj));
strcat(t,".");
push(newVar_N("new ",t,getName(meth),"(", nparam->p.Integer,")"));
free (t);
return 0;
}
static int
decompileGETMEMBER(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *obj, *mem, *var;
char *vname, *varname,*memname;
int len;
mem=pop();
var=pop();
varname=getName(var);
memname=getName(mem);
#ifdef DEBUG
printf("*getMember* varName %s (type=%d) memName=%s (type=%d)\n",
varname,var->Type, memname,mem->Type);
#endif
len = strlen(varname)+strlen(memname);
if (mem->Type == PUSH_INT || mem->Type == PUSH_DOUBLE || mem->Type == PUSH_VARIABLE
|| mem->Type == PUSH_REGISTER || mem->Type == 12 )
{
vname = malloc(len+3);
strcpy(vname,varname);
strcat(vname,"[");
strcat(vname,memname);
strcat(vname,"]");
}
else
{
vname = malloc(len+2);
strcpy(vname,varname);
strcat(vname,".");
strcat(vname,memname);
}
obj = newVar(vname);
pushvar(obj);
return 0;
}
static int
decompileSETMEMBER(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *val, *var, *obj;
val = pop();
var = pop();
obj = pop();
#ifdef DEBUG
printf("*SETMember* varName %s (type=%d) objName=%s (type=%d)\n",getName(var),var->Type, getName(obj),obj->Type);
#endif
if (obj->Type == 12) /* do nothing: inline inc/dec using side effect */
{
obj->Type = PUSH_VARIABLE; /* ...but only once */
return 0;
}
INDENT
if (obj->Type == 11) /* simply output variable and inc/dec op */
{
decompilePUSHPARAM(obj,0);
println(";");
return 0;
}
decompilePUSHPARAM(obj,0);
if (var->Type == PUSH_INT || var->Type == PUSH_DOUBLE || var->Type == PUSH_VARIABLE
|| var->Type == PUSH_REGISTER || var->Type == 12 )
{
puts("[");
}
else
{
puts(".");
if (OpCode(actions, n-1, maxn) == SWFACTION_STOREREGISTER)
{
struct SWF_ACTIONSTOREREGISTER *sactv2 = (struct SWF_ACTIONSTOREREGISTER*)&actions[n-1];
if (sactv2->Register==0)
regs[0]=newVar3(getName(obj),".",getName(var)); // easter 07: some sugar for mtc et al.
}
}
decompilePUSHPARAM(var,0);
if (var->Type == PUSH_INT || var->Type == PUSH_DOUBLE || var->Type == PUSH_VARIABLE
|| var->Type == PUSH_REGISTER || var->Type == 12 )
{
puts("]");
}
printf(" = " );
if ( OpCode(actions, n-1, maxn) == SWFACTION_STOREREGISTER ) {
struct SWF_ACTIONSTOREREGISTER *sr =
(struct SWF_ACTIONSTOREREGISTER*)&actions[n-1];
printf("R%d", sr->Register);
}
else if (val->Type != PUSH_VARIABLE) {
/* later it will be a switch{} */
decompilePUSHPARAM(val,1);
}
else {
decompilePUSHPARAM(val,0);
}
println(";");
return 0;
}
static int
decompileGETVARIABLE(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *var;
var = pop();
#ifdef DEBUG
printf("*GETVariable* varName %s (type=%d)\n",getName(var),var->Type);
#endif
if (var->Type == PUSH_VARIABLE)
pushvar(newVar3("eval(",getName(var),")"));
else
pushvar(newVar(getName(var)));
return 0;
}
static int
decompileSETVARIABLE(int n, SWF_ACTION *actions,int maxn,int islocalvar)
{
struct SWF_ACTIONPUSHPARAM *val, *var;
val = pop();
var = pop();
if (val->Type!=12)
{
INDENT
}
#ifdef DEBUG
printf("*SETVariable* varName %s (type=%d) valName=%s (type=%d)\n",
getName(var),var->Type, getName(val),val->Type);
#endif
if (val->Type!=12 && islocalvar)
{
puts("var ");
}
if (gIndent<0) /* the ENUM workaround: */
{ /* in "for (xx in yy) { }" we need xx, but nothing else */
puts(getName(var));
return 0;
}
switch (val->Type)
{
case 10:
puts(getName(var)); // Variable (NEVER as string)
printf(" = " );
decompilePUSHPARAM(val,0);
println(";");
break;
case 11: /* simply output variable and inc/dec op */
puts(getName(val));
println(";");
break;
case 12: /* do nothing: inline increment/decrement (using side effect only) */
val->Type = PUSH_VARIABLE; // but print next time e.g. in y=++x;
break;
default:
puts(getName(var));
printf(" = " );
decompilePUSHPARAM(val,1); // for certain types parameter 1 does not care
println(";");
}
return 0;
}
static int
decompileRETURN(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *var=pop();
INDENT
printf("return ");
if (var->Type== PUSH_REGISTER && var->p.RegisterNumber==0) /* REGISTER 0 used as helper variable */
puts(getName(regs[0]));
else
decompilePUSHPARAM(var,1);
println(";");
return 0;
}
static int
decompileJUMP(int n, SWF_ACTION *actions, int maxn)
{
int i=0,j=0;
int offSave;
struct SWF_ACTIONIF *sactif;
OUT_BEGIN2(SWF_ACTIONJUMP);
sactif=NULL;
if(isLogicalOp(n+1, actions, maxn) ||
(OpCode(actions, n+1, maxn) == SWFACTION_PUSH && isLogicalOp(n+2, actions, maxn)))
{
/* Probably the start of a do {} while(), so skip it */
return 0;
}
/* Probably the end of a switch{}, so skip it */
if (OpCode(actions, n+1, maxn) == SWFACTION_POP)
return 1;
if (OpCode(actions, n+1, maxn) == SWFACTION_JUMP)
{
if (actions[n+1].SWF_ACTIONJUMP.BranchOffset==0)
return 1;
}
for(i=0; n + 1 + i < maxn && (actions[(n+1)+i].SWF_ACTIONRECORD.Offset < (actions[n+1].SWF_ACTIONRECORD.Offset+actions[n ].SWF_ACTIONJUMP.BranchOffset)); i++)
{
#if 0
printf("/* for PART3 OP 0x%x */\n",actions[n+1+i].SWF_ACTIONRECORD.ActionCode);
#endif
; // NOOP
}
if (i)
{
for (j=0; n+j+i<maxn; j++)
{
#if 0
printf("/* FOR part2 OP 0x%x */\n",actions[n+i+j].SWF_ACTIONRECORD.ActionCode)
// at least one should push on stack
#endif
if (OpCode(actions, n+i+j, maxn) == SWFACTION_IF)
{
sactif = (struct SWF_ACTIONIF *)&(actions[n+i+j]);
/* chk whether last jump does lead us back to start of loop */
if (sactif->Actions[sactif->numActions-1].SWF_ACTIONRECORD.ActionCode==SWFACTION_JUMP
&& sactif->Actions[sactif->numActions-1].SWF_ACTIONJUMP.BranchOffset+
sactif->Actions[sactif->numActions-1].SWF_ACTIONJUMP.Offset==
actions[n].SWF_ACTIONRECORD.Offset )
{
break;
}
else
sactif=NULL;
}
}
}
if (sactif)
{
INDENT
puts("while(");
decompileActions(j-1, &actions[n+1+i], gIndent);
puts(getName(pop()));
println("){ /* original FOR loop rewritten to WHILE */");
offSave=offseoloop;
if (n+i+j+1<maxn) // see part2 above
offseoloop=actions[n+i+j+1].SWF_ACTIONRECORD.Offset;
else
offseoloop=actions[n+i+j].SWF_ACTIONRECORD.Offset+5;
decompileActions(sactif->numActions-1, sactif->Actions,gIndent+1);
decompileActions(i, &actions[n+1], gIndent+1);
offseoloop=offSave;
INDENT
println("};");
return i+j;
}
if (sact->BranchOffset>0)
{
if ( stackVal(n,actions) == 1 && n+1==maxn)
{ // leaving block @last op with value on stack: a return x;
return decompileRETURN(n, actions,maxn);
}
if (n+2 < maxn && OpCode(actions, n+1, maxn) == SWFACTION_PUSH &&
actions[n+2].SWF_ACTIONRECORD.Offset == actions[n+1].SWF_ACTIONRECORD.Offset+sact->BranchOffset)
{
return 1; // jump to short to be a 'break': but an internal jump over a push
} // to do: add some control flow analysis
INDENT
if (offseoloop==actions[n].SWF_ACTIONRECORD.Offset+sact->BranchOffset+5)
puts("break;" );
else
puts("return;" );
println("\t\t\t// offs_end_of_loop=%d offs_jmp_dest=%d",
offseoloop, actions[n].SWF_ACTIONRECORD.Offset+sact->BranchOffset+5);
}
else
{
if (sact->BranchOffset<0)
{
INDENT
println("continue; /*------*/");
}
}
/* error("Unhandled JUMP"); */
return 0;
}
static int
decompileDEFINELOCAL2(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *var;
INDENT
var = pop();
puts("var ");
puts(getName(var));
println(";");
return 0;
}
static int
decompileENUMERATE(int n, SWF_ACTION *actions, int maxn, int is_type2)
{
int i=0;
while (i < maxn && i < 5 && OpCode(actions, n+i, maxn))
i++;
INDENT
println("/* a for-var-in loop should follow below: */" );
return i-1; // preserve some code for decompileIF()...
} // ... and let decompileIF() do all the dirty work ;-)
#ifdef DECOMP_SWITCH
// [recursive] estimate size of buffer needed for decompiling 'switch'
// [ only call by decompileIF() ]
//
static int
countAllSwitchActions (union SWF_ACTION *actions, union SWF_ACTION *pre)
{
int i,j=1;
if (actions->SWF_ACTIONRECORD.ActionCode==SWFACTION_IF && pre->SWF_ACTIONRECORD.ActionCode==SWFACTION_STRICTEQUALS )
{
for(i=0; i < ((struct SWF_ACTIONIF*)actions)->numActions; i++)
{
j+=countAllSwitchActions(&((struct SWF_ACTIONIF*)actions)->Actions[i],pre);
pre=&((struct SWF_ACTIONIF*)actions)->Actions[i];
}
}
return j;
}
// [recursive] copy all actions in a 'flat' buffer by
// unpackung all if-actions that are part of the switch operation
// [ only call by decompileIF() ]
//
static union SWF_ACTION *
getAllSwitchActions(union SWF_ACTION *dest, union SWF_ACTION *actions, union SWF_ACTION *pre)
{
#ifdef DEBUGSWITCH
println("SWCODE: %p %d %s %s",
dest, actions->SWF_ACTIONRECORD.Offset,
actionName(actions->SWF_ACTIONRECORD.ActionCode),
actionName(pre->SWF_ACTIONRECORD.ActionCode));
#endif
*dest++=*actions;
if (actions->SWF_ACTIONRECORD.ActionCode==SWFACTION_IF
&& pre->SWF_ACTIONRECORD.ActionCode==SWFACTION_STRICTEQUALS )
{
int i;
struct SWF_ACTIONIF *sactv2 = (struct SWF_ACTIONIF*)actions;
for(i=0; i< sactv2->numActions; i++)
{
dest=getAllSwitchActions(dest,&sactv2->Actions[i],pre);
pre=&((struct SWF_ACTIONIF*)actions)->Actions[i];
}
}
return dest;
}
// looks similar other decompileXXXX() but
// can't called by decompileAction()
// [ do only call by decompileIF() ]
//
static int
decompile_SWITCH(int n, SWF_ACTION *actions, int maxn, int off1end)
{
int i,j;
int start; // base action index for case value and code
int ccsize=0; // size of code for case value
int cvsize=0; // size of case value
int maxoff=0; // action offset AFTER switch
int n_maxoff=0; // array index of maxoff
int pend=0; // control pending output
int xsize=0; // ret val
int jmpsize=0; // debug helper
int lastoff=0; // debug helper
int n_firstactions=maxn;// array index of 1st case actions code
int lastcasestart=0; // offs where last "case x:" begins
char *defa="[last]"; // debug helper for early "default:"
char *tmp=NULL; // helper for pending output
struct strbufinfo origbuf; // pending output buffer
struct _stack *StackSave;
struct SWF_ACTIONPUSHPARAM *swcopy,*sw=pop();
struct SWF_ACTIONPUSHPARAM *compare=pop();
int offSave;
for (i=0; i<n_firstactions; i++) // seek last op in 1st if
{
if (actions[i+1].SWF_ACTIONRECORD.Offset==off1end)
{
// println("found #off end first= %d",i+1);
if (OpCode(actions, i, maxn) == SWFACTION_JUMP)
{
maxoff=actions[i].SWF_ACTIONJUMP.BranchOffset+actions[i].SWF_ACTIONJUMP.Offset+5;
j=1;
}
else
{
// SanityCheck(decompile_SWITCH,0,"no jump found where expected");
}
break;
}
}
if (!maxoff)
{
for (i=maxn-1;i>=0;i--) // seek from end of block last op of switch{}
{
if (OpCode(actions, i, maxn) == SWFACTION_JUMP && !actions[i].SWF_ACTIONJUMP.BranchOffset)
{
maxoff=actions[i].SWF_ACTIONRECORD.Offset+5;
j=2;
break;
}
}
}
for (i=0;i<maxn;i++)
{
if (actions[i].SWF_ACTIONRECORD.Offset>=maxoff)
{
n_maxoff=i; // part of block is switch
break;
}
}
if (!n_maxoff)
n_maxoff=maxn; // whole block is switch
INDENT
println("switch( %s ) { // end switch at %d (index %d) / found via meth %d)",
getString(sw), maxoff,n_maxoff,j);
push(sw);
push(compare);
i=1;
do // here we go into main loop
{
if((OpCode(actions, i, maxn) == SWFACTION_IF
&& OpCode(actions, i-1, maxn) == SWFACTION_STRICTEQUALS )
||(OpCode(actions, i, maxn) == SWFACTION_JUMP
&& OpCode(actions, i-1, maxn) == SWFACTION_IF) )
{
start=i;
while (start<maxn
&& actions[start].SWF_ACTIONRECORD.Offset < actions[i].SWF_ACTIONRECORD.Offset+5+actions[i].SWF_ACTIONJUMP.BranchOffset
) {
start++; // count actions until start of "case x:"
}
if (n_firstactions==maxn) // if not done store earliest "case x: "actions
{
n_firstactions=start; // same as array index
}
for (ccsize=0; ccsize+start<n_maxoff; ccsize++) // count actions belonging to "case x:"
{
#ifdef DEBUGSWITCH
println("in ccsize: ccsize=%d off=%d %s",
ccsize,actions[ccsize+start].SWF_ACTIONRECORD.Offset,
actionName(OpCode(actions, ccsize+start, maxn)));
#endif
if (OpCode(actions, ccsize+start, maxn) == SWFACTION_JUMP)
{
if (maxoff == actions[ccsize+start].SWF_ACTIONJUMP.Offset+5 + actions[ccsize+start].SWF_ACTIONJUMP.BranchOffset)
{
jmpsize= actions[ccsize+start].SWF_ACTIONJUMP.BranchOffset;
lastoff= actions[ccsize+start].SWF_ACTIONJUMP.Offset;
ccsize++; // the jmp itself
break;
}
}
}
#if USE_LIB
if (tmp && (start!=pend)) // output pending buffer if neccessary
{
puts(tmp);
}
if (tmp)
{
free(tmp);
tmp=NULL;
}
pend=start;
#endif
if (OpCode(actions, i, maxn) == SWFACTION_JUMP)
{
if (ccsize<=1)
break; // ready
else
{
INDENT
if (actions[start].SWF_ACTIONRECORD.Offset>lastcasestart)
xsize+=ccsize;
else
defa="[early]";
println("default: // at %d %s start=%d ccsize=%d",
actions[start].SWF_ACTIONRECORD.Offset,defa, start, ccsize);
}
}
else
{
INDENT
xsize=ccsize;
lastcasestart=actions[start].SWF_ACTIONRECORD.Offset;
println("case %s: // at %d start=%d ccsize=%d jmp=%d+%d+5",
getString(pop()), lastcasestart, start, ccsize, lastoff,jmpsize);
swcopy=pop();
// SanityCheck(decompile_SWITCH,!strcmp(getName(swcopy),getName(sw)),"sw0 != sw");
}
#if USE_LIB
origbuf=setTempString(); // switch to temp buffer
#endif
StackSave=Stack;
offSave=offseoloop;
offseoloop=maxoff;
decompileActions( ccsize, &actions[start],gIndent+1);
offseoloop=offSave;
Stack=StackSave;
#if USE_LIB
tmp=switchToOrigString(origbuf);
#endif
if (OpCode(actions, i, maxn) == SWFACTION_JUMP) // after "default:"
{
break; // ready
}
else
{
if (OpCode(actions, i+1, maxn) != SWFACTION_JUMP) // not before "default:" or end
{
i++; // the 'if' itself
cvsize=0;
while (i+cvsize < n_firstactions
&& OpCode(actions, i+cvsize, maxn) != SWFACTION_STRICTEQUALS)
{
#ifdef DEBUGSWITCH
println("in cvsize=%d %d %s",
cvsize, actions[i+cvsize].SWF_ACTIONRECORD.Offset,
actionName(OpCode(actions, i+cvsize, maxn)));
#endif
cvsize++; // count "case X:" code size
}
decompileActions( cvsize, &actions[i],gIndent+1); // at least one push on stack expected
i+=cvsize;
}
}
}
} while (++i < n_firstactions);
#if USE_LIB
if (tmp)
{
puts(tmp); // print last pending output
free(tmp);
}
#endif
INDENT
println("} // switch ret value =%d",xsize);
return xsize;
}
#endif
static int
decompileIF(int n, SWF_ACTION *actions, int maxn)
{
int offSave;
int j,i=0;
struct strbufinfo origbuf;
OUT_BEGIN2(SWF_ACTIONIF);
if (sact->numActions < 1) {
return 0;
}
/*
* IF is used in various way to implement different types
* of loops. We try to detect these different types of loops
* here.
*/
#ifdef STATEMENT_CLASS
if((OpCode(actions, n-1, maxn) == SWFACTION_LOGICALNOT) &&
(OpCode(actions, n-2, maxn) == SWFACTION_LOGICALNOT) &&
(OpCode(actions, n-3, maxn) == SWFACTION_GETVARIABLE) &&
(OpCode(actions, n-4, maxn) == SWFACTION_PUSH) )
{
/* It's really a class definition */
INDENT
puts("class ");
decompilePUSHPARAM(newVar(getName(pop())),0);
println(" {" );
decompileActions(sact->numActions, sact->Actions,gIndent+1);
INDENT
println("}");
return 0;
}
if(
(OpCode(actions, n-1, maxn) == SWFACTION_LOGICALNOT) &&
(OpCode(actions, n-2, maxn) == SWFACTION_LOGICALNOT) &&
(OpCode(actions, n-3, maxn) == SWFACTION_GETMEMBER) &&
(OpCode(actions, n-4, maxn) == SWFACTION_PUSH) )
{
/* It's really a class definition */
INDENT
println(" {");
decompileActions(sact->numActions, sact->Actions,gIndent+1);
INDENT
println("}");
return 0;
}
#endif
/*
* do {} while() loops have a JUMP at the end of the if clause
* that points to a JUMP above the IF statement.
*/
if(n && isLogicalOp(n-1, actions, maxn) &&
(sact->Actions[sact->numActions-1].SWF_ACTIONRECORD.ActionCode == SWFACTION_JUMP) &&
( (sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.Offset +
sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset) < actions[n].SWF_ACTIONRECORD.Offset) &&
isLogicalOp(sact->numActions-2, sact->Actions, maxn) )
{
INDENT
println("do {");
offSave=offseoloop;
offseoloop=actions[n].SWF_ACTIONRECORD.Offset+5;
decompileActions(sact->numActions-1, sact->Actions,gIndent+1);
offseoloop=offSave;
INDENT
puts("while( ");
puts(getName(pop()));
puts(");");
return 0;
}
/* ak,2006
* lots of "do {} while()" have simply a CONDITIONED JUMP back at the end of the loop
*/
if( actions[n].SWF_ACTIONJUMP.BranchOffset < 0 )
{
INDENT
println("do { /* 2nd type */ ");
offSave=offseoloop;
offseoloop=actions[n ].SWF_ACTIONRECORD.Offset+5;
decompileActions(sact->numActions, sact->Actions,gIndent+1);
offseoloop=offSave;
INDENT
puts("} while( ");
puts(getName(pop()));
println(");");
return 0;
}
j=0;
while (OpCode(actions, n-j, maxn) != SWFACTION_ENUMERATE &&
OpCode(actions, n-j, maxn) != SWFACTION_ENUMERATE2 && j<n && j<5)
{
j++; // check for a pending ENUMERATE
}
if ((OpCode(actions, n-j, maxn) == SWFACTION_ENUMERATE ||
OpCode(actions, n-j, maxn) == SWFACTION_ENUMERATE2 ) &&
OpCode(actions, n-j+1, maxn) == SWFACTION_STOREREGISTER )
{
struct SWF_ACTIONPUSHPARAM *var;
int x;
var = pop();
INDENT
puts("for ( ");
// check for an usual special case w register Rx
if (sact->Actions[1].SWF_ACTIONRECORD.ActionCode == SWFACTION_STOREREGISTER)
{
struct SWF_ACTIONSTOREREGISTER *sactv2 = (struct SWF_ACTIONSTOREREGISTER*)&sact->Actions[1];
puts("var ");
puts(getName(regs[sactv2->Register]));
x=3;
}
else
{
decompileActions( 2 , sact->Actions,-1); /* -1 == the ENUM workaround */
x=2;
}
puts(" in ");
puts(getName(var));
println(" ) {");
if(n+1 >= maxn)
{
SWF_warn("Warning: %s:%i: something is wrong here\n", __FILE__, __LINE__);
}
else
{
offSave=offseoloop;
offseoloop=actions[n+1].SWF_ACTIONRECORD.Offset;
decompileActions(sact->numActions-1-x, &sact->Actions[x],gIndent+1);
offseoloop=offSave;
}
INDENT
println("}");
return 0;
}
/*
* while() loops have a JUMP at the end of the if clause that jumps backwards
* But also "continue" statements could jump backwards.
*/
if( isLogicalOp(n-1, actions, maxn) &&
( (sact->Actions[sact->numActions-1].SWF_ACTIONRECORD.ActionCode == SWFACTION_JUMP) &&
sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset < 0) )
{
if(0) dumpRegs();
INDENT
/* if on a level >0 we can check for any outer loop
To do: get the level on a better way than using gIndent */
if (gIndent
&& OpCode(actions, maxn-1, maxn) == SWFACTION_JUMP
&& actions[maxn-1].SWF_ACTIONJUMP.Offset+actions[maxn].SWF_ACTIONJUMP.BranchOffset==
sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.Offset+sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset)
{
/* this jump leads from a block to start of a loop on outer block:
it is an 'if' later followed by last action 'continue' */
SWF_warn("WARNING: this might be wrong (%s:%i)\n", __FILE__, __LINE__);
puts("if ( ");
puts(getName(pop()));
println(" ) {");
decompileActions(sact->numActions, sact->Actions,gIndent+1);
}
else /* while(){} as usual */
{
puts("while( ");
puts(getName(pop()));
println(" ) {");
offSave=offseoloop;
offseoloop=actions[n+1].SWF_ACTIONRECORD.Offset;
decompileActions(sact->numActions-1, sact->Actions,gIndent+1);
offseoloop=offSave;
}
INDENT
println("}");
return 0;
}
{ // WTF ???
#define SOME_IF_DEBUG 0 /* coders only */
int has_else_or_break= ((sact->Actions[sact->numActions-1].SWF_ACTIONRECORD.ActionCode == SWFACTION_JUMP) &&
(sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset > 0 )) ? 1:0;
int has_lognot=(OpCode(actions, n-1, maxn) == SWFACTION_LOGICALNOT) ? 1:0;
int else_action_cnt=0,is_logor=0,is_logand=0,sbi,sbe;
/* before emitting any "if"/"else" characters let's check
for a ternary operation cond?a:b
*/
if (has_else_or_break)
{
int limit=actions[n+1].SWF_ACTIONRECORD.Offset + sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset;
/* Count the number of action records that are part of
* the else clause, and then decompile only that many.
*/
for(else_action_cnt=0;
else_action_cnt+n+1<maxn && actions[n+1+else_action_cnt].SWF_ACTIONRECORD.Offset < limit;
else_action_cnt++)
{
#if SOME_IF_DEBUG
println("/* ELSE OP 0x%x at %d*/", OpCode(actions, n+1+else_action_cnt, maxn),
actions[n+1+else_action_cnt].SWF_ACTIONRECORD.Offset)
#endif
;
}
}
i=else_action_cnt; // =return value
sbi=stackVal (sact->numActions-1,sact->Actions);
sbe=stackVal (else_action_cnt,&actions[n+1]);
// check against opcodes we do not expect in a ternary operation
if (sbi==1 && sbe==1)
{
for (j=0;j<sact->numActions-1;j++)
{
if (sact->Actions[j].SWF_ACTIONRECORD.ActionCode==SWFACTION_JUMP) // perhaps more ops
{
sbi=i=has_else_or_break=0;
break;
}
}
for (j=0;j<else_action_cnt;j++)
{
if (OpCode(actions, n+j, maxn) == SWFACTION_JUMP) // perhaps more ops
{
sbe=i=has_else_or_break=0;
break;
}
}
}
#if SOME_IF_DEBUG
printf("sbi=%d sbe=%d\n", sbi,sbe);
#endif
if (sbi==1 && sbe==1)
{
#if SOME_IF_DEBUG
println("/* ****Found ternary ternary operation \"cond ? a : b\" **** */");
printf("If Actions=%d\n",sact->numActions-1);
printf("Else Actions=%d\n",else_action_cnt);
#endif
struct strbufinfo origbuf;
#if USE_LIB
origbuf=setTempString(); /* switch to a temporary string buffer */
#endif
puts("(");
puts(getName(pop()));
puts(" ? ");
decompileActions(else_action_cnt , &actions[n+1],0);
puts(getName(pop()));
puts(" : ");
decompileActions(sact->numActions-1, sact->Actions,0);
puts(getName(pop()));
puts(")");
#if USE_LIB
push (newVar(dcgetstr())); /* push for later assignment */
setOrigString(origbuf); /* switch back to orig buffer */
#else
push (newVar("/* ternary op: see code above */"));
#endif
}
else
{
/* at this point let's check for conditioned jumps that are NOT 'if':
currently that is code for the locical operations && and ||
*/
if (OpCode(actions, n-1, maxn) == SWFACTION_PUSHDUP)
is_logor=1;
if (OpCode(actions, n-2, maxn)== SWFACTION_PUSHDUP
&& OpCode(actions, n-1, maxn) == SWFACTION_LOGICALNOT)
{
is_logand=1;
}
if (is_logor || is_logand)
{
#if SOME_IF_DEBUG
println("");
println("/* detected LOGICAL %s: %d actions*/", is_logor ? "OR":"AND",sact->numActions);
#endif
#if USE_LIB
origbuf=setTempString(); /* switch to a temporary string buffer */
#endif
puts(getName(pop())); /* get left side of logical or */
puts(is_logor ? " || ":" && ");
decompileActions(sact->numActions, sact->Actions,gIndent+1);
puts(getName(pop())); /* get right side of logical or */
#if USE_LIB
push(newVar(dcgetstr()));
setOrigString(origbuf); /* switch back to orig buffer */
#else
push (newVar("/* see logical term lines above */"));
#endif
return 0;
}
#ifdef DECOMP_SWITCH
if ( OpCode(actions, n-1, maxn) == SWFACTION_STRICTEQUALS
&& check_switch(sact->Actions[0].SWF_ACTIONRECORD.ActionCode) )
{
union SWF_ACTION *xact,*xact0;
for(i=n-1,j=0; i< maxn ;i++) // n-1 due adding 1st SWFACTION_STRICTEQUALS in buffer
{
j+=countAllSwitchActions(&actions[i],&actions[i-1]); // FIRST count size of code
}
xact0=xact = (union SWF_ACTION *) calloc (j,sizeof (SWF_ACTION));
INDENT
println("// checking %d actions for switch(){}",j);
for(i=n-1; i< maxn ;i++)
{
xact=getAllSwitchActions(xact,&actions[i],&actions[i-1]); // SECOND copy into xtra buffer
}
j=decompile_SWITCH(0,xact0,j,actions[n+1].SWF_ACTIONRECORD.Offset); // THIRD decompile xtra buffer
free(xact0);
return j;
}
#endif
/* it seems we have a found the REAL 'if' statement,
so it's right time to print the "if" just NOW!
*/
INDENT
puts("if( ");
puts(getName(pop())); /* the condition itself */
println(" ) {");
if ( has_else_or_break )
{
int limit=actions[n+1].SWF_ACTIONRECORD.Offset + sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset;
// limit == dest of jmp == offset next op after 'if' + jumpdist at end of 'if'
int lastopsize=actions[maxn-1].SWF_ACTIONRECORD.Length;
if (OpCode(actions, maxn-1, maxn) == SWFACTION_IF)
lastopsize+=actions[maxn-1].SWF_ACTIONIF.BranchOffset + 3; /* +3 see parser.c: "Action + Length bytes not included in the length" */
if (offseoloop
&& ! (has_lognot
&& OpCode(actions, n-2, maxn) == SWFACTION_EQUALS2
&& OpCode(actions, n-3, maxn) == SWFACTION_PUSH
&& OpCode(actions, n-4, maxn) == SWFACTION_PUSHDUP)
&& limit > actions[maxn-1].SWF_ACTIONRECORD.Offset+lastopsize)
{
/* the jump leads outside this limit, so it is a simple 'if'
with a 'break' or 'return' at the end, and there is NO else clause.
*/
INDENT
println("// offs_endjump_dest=%d offs_after_blk %d",
limit, actions[maxn-1].SWF_ACTIONRECORD.Offset+lastopsize);
decompileActions(sact->numActions, sact->Actions,gIndent+1);
i=0; /* found break/return but no else and thus return 0 */
}
else
{
/* There is an else clause also!
(action counter is set above)
*/
struct _stack *StackSave=Stack; /* decompile if and else blocks at same stack base */
if (has_lognot)
{
decompileActions(sact->numActions-1, sact->Actions,gIndent+1);
INDENT
println("} else {");
}
Stack=StackSave;
decompileActions(else_action_cnt , &actions[n+1],gIndent+1);
if (!has_lognot) /* the missing if-part just NOW */
{
Stack=StackSave;
INDENT
println ("} else {" );
decompileActions(sact->numActions-1, sact->Actions,gIndent+1);
}
}
}
else
{
/* It's a simple if() {} */
decompileActions(sact->numActions, sact->Actions,gIndent+1);
}
INDENT
println("}");
} // WTF ???
return i;
}
return 0;
}
static int
decompileINITOBJECT(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *nparam;
nparam=pop();
push(newVar_N2("","","","{", nparam->p.Integer,"}"));
return 0;
}
static int
decompileWITH(int n, SWF_ACTION *actions, int maxn)
{
OUT_BEGIN2(SWF_ACTIONWITH);
INDENT
puts("with(");
decompilePUSHPARAM(pop(),0);
puts(")");
println(" {" );
decompileActions(sact->numActions, sact->Actions,gIndent+1);
INDENT
println("}" );
return 1;
}
static int
decompileTRY(int n, SWF_ACTION *actions, int maxn)
{
#ifdef DEBUG
struct _stack *StackSave=Stack;
#endif
OUT_BEGIN2(SWF_ACTIONTRY);
INDENT
println("try {");
decompileActions(sact->numTryActs, sact->TryActs,gIndent+1);
INDENT
println("}");
#ifdef DEBUG
if (Stack!=StackSave)
{
println("/* Stack problem in try{} code above */");
Stack=StackSave;
}
#endif
if (sact->numCatchActs)
{
struct SWF_ACTIONPUSHPARAM *rsave=NULL;
INDENT
if( ! sact->CatchInRegisterFlag)
println("catch (%s) {",sact->CatchName);
else
{
char *t=malloc(5); /* Rddd */
sprintf(t,"R%d", sact->CatchRegister );
rsave=regs[sact->CatchRegister];
regs[sact->CatchRegister] = newVar(t);
println("catch (%s) {",t);
}
decompileActions(sact->numCatchActs, sact->CatchActs,gIndent+1);
INDENT
println("}");
if (rsave)
regs[sact->CatchRegister]=rsave;
#ifdef DEBUG
if (Stack!=StackSave)
{
println("/* Stack problem in catch{} code above */");
Stack=StackSave;
}
#endif
}
if (sact->numFinallyActs)
{
INDENT
println("finally () {");
decompileActions(sact->numFinallyActs, sact->FinallyActs,gIndent+1);
INDENT
println("}");
#ifdef DEBUG
if (Stack!=StackSave)
{
println("/* Stack problem in finally{} code above */");
Stack=StackSave;
}
#endif
}
return 0;
}
static int
decompileDEFINEFUNCTION(int n, SWF_ACTION *actions, int maxn, int is_type2)
{
int i,j,k,m,r;
struct SWF_ACTIONPUSHPARAM *myregs[ 256 ];
struct _stack *StackSave;
struct SWF_ACTIONDEFINEFUNCTION2 *sactv2;
struct strbufinfo origbuf;
OUT_BEGIN2(SWF_ACTIONDEFINEFUNCTION);
sactv2 = (struct SWF_ACTIONDEFINEFUNCTION2*)sact;
#ifdef DEBUG
if(n+1 < maxn)
{
println("/* function followed by OP %x */",
OpCode(actions, n+1, maxn));
}
#endif
#if USE_LIB
if (isStoreOp(n+1, actions,maxn)
|| ( *sact->FunctionName==0 && !is_type2 )
|| (*sactv2->FunctionName==0 && is_type2 ))
{
origbuf=setTempString(); /* switch to a temporary string buffer */
}
#endif
puts("function ");
if (is_type2)
{
for(j=1;j<sactv2->RegisterCount;j++)
{
myregs[j]=regs[j];
regs[j]=NULL;
}
r=1;
if (sactv2->PreloadThisFlag) regs[r++]=newVar("this");
if (sactv2->PreloadArgumentsFlag) regs[r++]=newVar("arguments");
if (sactv2->PreloadSuperFlag) regs[r++]=newVar("super");
if (sactv2->PreloadRootFlag) regs[r++]=newVar("root");
if (sactv2->PreloadParentFlag) regs[r++]=newVar("parent");
if (sactv2->PreloadGlobalFlag) regs[r++]=newVar("global");
puts(sactv2->FunctionName);
puts("(");
for(i=0,m=0;i<sactv2->NumParams;i++)
{
puts(sactv2->Params[i].ParamName);
if ( sactv2->Params[i].Register)
{
printf(" /*=R%d*/ ",sactv2->Params[i].Register);
regs[sactv2->Params[i].Register] = newVar(sactv2->Params[i].ParamName);
m++; // do not count 'void' etc
}
if( sactv2->NumParams > i+1 ) puts(",");
}
println(") {" );
if (r+m < sactv2->RegisterCount)
{
INDENT
puts(" var ");
}
for(k=r;r<sactv2->RegisterCount;r++)
{
if (!regs[r])
{
char *t=malloc(5); /* Rddd */
sprintf(t,"R%d", r );
puts (t);
if (k++ < sactv2->RegisterCount- m -1)
puts(", ");
else
println(";" );
regs[r]=newVar(t);
}
}
StackSave=Stack;
decompileActions(sactv2->numActions, sactv2->Actions,gIndent+1);
#ifdef DEBUG
if (Stack!=StackSave)
{
println("/* Stack problem in function code above */");
}
#endif
Stack=StackSave;
for(j=1;j<sactv2->RegisterCount;j++)
regs[j]=myregs[j];
}
else
{
puts(sact->FunctionName);
puts("(");
for(i=0;i<sact->NumParams;i++) {
puts(sact->Params[i]);
if( sact->NumParams > i+1 ) puts(",");
}
println(") {" );
k=0;
if (sact->Actions[0].SWF_ACTIONRECORD.ActionCode == SWFACTION_PUSH)
{
struct SWF_ACTIONPUSH *sactPush=(struct SWF_ACTIONPUSH *)sact->Actions;
for(i=0;i<sactPush->NumParam;i++)
{
if ((&(sactPush->Params[i]))->Type == PUSH_REGISTER)
k++; /* REGISTER */
}
if (k)
{
INDENT
puts(" var ");
for(i=1;i<=k;i++)
{
char *t=malloc(5); /* Rddd */
sprintf(t,"R%d", i );
puts (t);
if (i < k)
puts(", ");
else
println(";" );
regs[i]=newVar(t);
}
}
}
for(j=1;j<=k;j++)
myregs[j]=regs[j];
StackSave=Stack;
decompileActions(sact->numActions, sact->Actions,gIndent+1);
#ifdef DEBUG
if (Stack!=StackSave)
{
println("/* Stack problem in function code above */");
}
#endif
Stack=StackSave;
for(j=1;j<=k;j++)
regs[j]=myregs[j];
}
INDENT
if (isStoreOp(n+1, actions,maxn)
|| ( *sact->FunctionName==0 && !is_type2 )
|| (*sactv2->FunctionName==0 && is_type2 ))
{
puts("}");
#if USE_LIB
push (newVar(dcgetstr())); /* push func body for later assignment */
setOrigString(origbuf); /* switch back to orig buffer */
#else
push (newVar("/* see function code above */")); /* workaround only if LIB is not in use */
#endif
}
else
println("}" );
return 0;
}
static int
decompileCALLMETHOD(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *meth, *obj, *nparam;
meth=pop();
obj=pop();
nparam=pop();
if (nparam->p.Integer>25)
{
INDENT
println("// Problem getting method arguments (%d ignored) below:",
nparam->p.Integer);
nparam->p.Integer=0;
}
#ifdef DEBUG
printf("*CALLMethod* objName=%s (type=%d) methName=%s (type=%d)\n",
getName(obj), obj->Type, getName(meth), meth->Type);
#endif
if (meth->Type == PUSH_UNDEF) /* just undefined, like in "super();" */
push(newVar_N(getName(obj),"","","(", nparam->p.Integer,")"));
else
{
if (meth->Type == PUSH_INT || meth->Type == PUSH_DOUBLE || meth->Type == PUSH_VARIABLE
|| meth->Type == PUSH_REGISTER || meth->Type == 12 )
{
push(newVar_N(getName(obj),"[",getName(meth),"](", nparam->p.Integer,")"));
}
else
push(newVar_N(getName(obj),".",getName(meth),"(", nparam->p.Integer,")"));
}
if (OpCode(actions, n+1, maxn) == SWFACTION_POP)
{
/* call method and throw away any result */
INDENT
puts(getName(pop()));
println(";" );
return 1;
}
return 0;
}
static int
decompileCALLFUNCTION(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *meth, *nparam;
SanityCheck(SWF_CALLMETHOD, OpCode(actions, n-1, maxn) == SWFACTION_PUSH,
"CALLMETHOD not preceeded by PUSH")
meth=pop();
nparam=pop();
if (nparam->p.Integer>25)
{
INDENT
println("// Problem getting function arguments (%d ignored) below:",
nparam->p.Integer);
nparam->p.Integer=0;
}
push(newVar_N("","",getName(meth),"(", nparam->p.Integer,")"));
if (OpCode(actions, n+1, maxn) == SWFACTION_POP)
{
/* call function and throw away any result */
INDENT
puts(getName(pop()));
println(";" );
return 1;
}
return 0;
}
static int
decompile_Null_ArgBuiltInFunctionCall(int n, SWF_ACTION *actions, int maxn, char *functionname)
{
INDENT
puts(functionname); // only used for cases w/o return value
println("();" );
return 0;
}
static int
decompileSingleArgBuiltInFunctionCall(int n, SWF_ACTION *actions, int maxn, char *functionname)
{
push(newVar_N("","",functionname,"(", 1,")"));
if (OpCode(actions, n+1, maxn) == SWFACTION_POP)
{
/* call function and throw away any result */
INDENT
puts(getName(pop()));
println(";" );
return 1;
}
return 0;
}
static int
decompileSTARTDRAG(int n, SWF_ACTION *actions, int maxn)
{
INDENT
puts("startDrag(");
decompilePUSHPARAM(pop(),1);
puts(",");
decompilePUSHPARAM(pop(),0);
puts(",");
decompilePUSHPARAM(pop(),0); //
println(");" );
return 0;
}
static int
decompileSUBSTRING(int n, SWF_ACTION *actions,int maxn)
{
push(newVar_N("","","substr","(", 3,")"));
if (OpCode(actions, n+1, maxn) == SWFACTION_POP)
{
/* call function and throw away any result */
INDENT
puts(getName(pop()));
println(";" );
return 1;
}
return 0;
}
static int
decompileSTRINGCONCAT(int n, SWF_ACTION *actions, int maxn)
{
push(newVar_N("","","concat","(", 2,")"));
if (OpCode(actions, n+1, maxn) == SWFACTION_POP)
{
/* call function and throw away any result */
INDENT
puts(getName(pop()));
println(";" );
return 1;
}
return 0;
}
static int
decompileTHROW(int n, SWF_ACTION *actions, int maxn)
{
INDENT
puts("throw ");
puts(getName(pop()));
println(";");
return 0;
}
static int
decompileREMOVECLIP(int n, SWF_ACTION *actions, int maxn)
{
INDENT
puts("removeMovieClip(");
puts(getName(pop()));
println(");" );
return 0;
}
static int
decompileDUPLICATECLIP(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *a, *b;
INDENT
a = pop();
b = pop();
puts("duplicateMovieClip(");
puts(getString(pop()));
puts(",");
puts(getString(b));
puts(",");
puts(getString(a));
println(");" );
return 0;
}
static int
decompileINITARRAY(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *nparam;
nparam=pop();
push(newVar_N("","","","[", nparam->p.Integer,"]"));
return 0;
}
static int
decompileEXTENDS(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *baseclass;
baseclass=pop();
#if 0
/* It's useless to open a class body when there's no
* other code supporting it. */
printf("class ");
puts(getName(pop()));
printf(" extends ");
puts(getName(baseclass));
println(" {" );
#else
/* We'll do it with asm{} */
println("asm {");
println(" push '%s'", getName(pop()));
println(" getvariable");
println(" push '%s'", getName(baseclass));
println(" getvariable");
println(" extends");
println("};");
#endif
return 0;
}
static int
decompileDELETE(int n, SWF_ACTION *actions, int maxn, int is_type2)
{
if (is_type2)
push(newVar3("delete(",getName(pop()),")"));
else
push(newVar_N("delete(",getName(pop()),".",getName(pop()), 0,")"));
if (OpCode(actions, n+1, maxn) == SWFACTION_POP)
{
/* call delete() with its args and throw away any result */
INDENT
puts(getName(pop()));
println(";" );
return 1;
}
return 0;
}
static int
decompileSETTARGET(int n, SWF_ACTION *actions, int maxn, int is_type2)
{
int action_cnt=0;
char *name;
OUT_BEGIN2(SWF_ACTIONSETTARGET);
name = is_type2 ? getString(pop()) : sact->TargetName;
if (*name)
{
INDENT
println("tellTarget('%s') {" ,name);
while(action_cnt+n<maxn)
{
if (OpCode(actions, n+1+action_cnt, maxn)==SWFACTION_SETTARGET
|| OpCode(actions, n+1+action_cnt, maxn)==SWFACTION_SETTARGET2
|| OpCode(actions, n+1+action_cnt, maxn)==SWFACTION_DEFINEFUNCTION
|| OpCode(actions, n+1+action_cnt, maxn)==SWFACTION_DEFINEFUNCTION2
|| OpCode(actions, n+1+action_cnt, maxn)==SWFACTION_END)
{
break;
}
action_cnt++;
}
decompileActions(action_cnt,&actions[n+1],gIndent+1);
INDENT
println("}" );
}
return action_cnt;
}
static int
decompileIMPLEMENTS(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *nparam;
int i;
INDENT;
puts(getName(pop()));
printf(" implements ");
nparam=pop();
for(i=0;i<nparam->p.Integer;i++)
{
puts(getName(pop()));
}
println(" ;");
return 0;
}
static int
decompileCAST(int n, SWF_ACTION *actions, int maxn)
{
struct SWF_ACTIONPUSHPARAM *iparam=pop();
struct SWF_ACTIONPUSHPARAM *tparam=pop();
push(newVar_N( getName(tparam),"(",getName(iparam),"", 0,")"));
return 0;
}
int
decompileAction(int n, SWF_ACTION *actions, int maxn)
{
if( n > maxn ) SWF_error("Action overflow!!");
#ifdef DEBUG
fprintf(stderr,"%d:\tACTION[%3.3d]: %s\n",
actions[n].SWF_ACTIONRECORD.Offset, n,
actionName(actions[n].SWF_ACTIONRECORD.ActionCode));
#endif
switch(actions[n].SWF_ACTIONRECORD.ActionCode)
{
case SWFACTION_END:
return 0;
case SWFACTION_CONSTANTPOOL:
decompileCONSTANTPOOL(&actions[n]);
return 0;
case SWFACTION_GOTOLABEL:
return decompileGOTOFRAME(n, actions, maxn,1);
case SWFACTION_GOTOFRAME:
return decompileGOTOFRAME(n, actions, maxn,0);
case SWFACTION_GOTOFRAME2:
return decompileGOTOFRAME2(n, actions, maxn);
case SWFACTION_WAITFORFRAME:
decompileWAITFORFRAME(&actions[n]);
return 0;
case SWFACTION_GETURL2:
decompileGETURL2(&actions[n]);
return 0;
case SWFACTION_GETURL:
decompileGETURL(&actions[n]);
return 0;
case SWFACTION_PUSH:
decompilePUSH(&actions[n]);
return 0;
case SWFACTION_PUSHDUP:
decompilePUSHDUP(&actions[n]);
return 0;
case SWFACTION_STACKSWAP:
decompileSTACKSWAP(&actions[n]);
return 0;
case SWFACTION_SETPROPERTY:
decompileSETPROPERTY(n, actions, maxn);
return 0;
case SWFACTION_GETPROPERTY:
decompileGETPROPERTY(n, actions, maxn);
return 0;
case SWFACTION_GETTIME:
return decompileGETTIME(n, actions, maxn);
case SWFACTION_TRACE:
decompileTRACE(n, actions, maxn);
return 0;
case SWFACTION_CALLFRAME:
decompileCALLFRAME(n, actions, maxn);
return 0;
case SWFACTION_EXTENDS:
decompileEXTENDS(n, actions, maxn);
return 0;
case SWFACTION_INITOBJECT:
decompileINITOBJECT(n, actions, maxn);
return 0;
case SWFACTION_NEWOBJECT:
decompileNEWOBJECT(n, actions, maxn);
return 0;
case SWFACTION_NEWMETHOD:
decompileNEWMETHOD(n, actions, maxn);
return 0;
case SWFACTION_GETMEMBER:
decompileGETMEMBER(n, actions, maxn);
return 0;
case SWFACTION_SETMEMBER:
decompileSETMEMBER(n, actions, maxn);
return 0;
case SWFACTION_GETVARIABLE:
decompileGETVARIABLE(n, actions, maxn);
return 0;
case SWFACTION_SETVARIABLE:
decompileSETVARIABLE(n, actions, maxn, 0);
return 0;
case SWFACTION_DEFINELOCAL:
decompileSETVARIABLE(n, actions, maxn, 1);
return 0;
case SWFACTION_DEFINELOCAL2:
decompileDEFINELOCAL2(n, actions, maxn);
return 0;
case SWFACTION_DECREMENT:
return decompileINCR_DECR(n, actions, maxn, 0);
case SWFACTION_INCREMENT:
return decompileINCR_DECR(n, actions, maxn,1);
case SWFACTION_STOREREGISTER:
decompileSTOREREGISTER(n, actions, maxn);
return 0;
case SWFACTION_JUMP:
return decompileJUMP(n, actions, maxn);
case SWFACTION_RETURN:
decompileRETURN(n, actions, maxn);
return 0;
case SWFACTION_LOGICALNOT:
return decompileLogicalNot(n, actions, maxn);
case SWFACTION_IF:
return decompileIF(n, actions, maxn);
case SWFACTION_WITH:
decompileWITH(n, actions, maxn);
return 0;
case SWFACTION_ENUMERATE:
return decompileENUMERATE(n, actions, maxn, 0);
case SWFACTION_ENUMERATE2 :
return decompileENUMERATE(n, actions, maxn,1);
case SWFACTION_INITARRAY:
return decompileINITARRAY(n, actions, maxn);
case SWFACTION_DEFINEFUNCTION:
return decompileDEFINEFUNCTION(n, actions, maxn,0);
case SWFACTION_DEFINEFUNCTION2:
return decompileDEFINEFUNCTION(n, actions, maxn,1);
case SWFACTION_CALLFUNCTION:
return decompileCALLFUNCTION(n, actions, maxn);
case SWFACTION_CALLMETHOD:
return decompileCALLMETHOD(n, actions, maxn);
case SWFACTION_INSTANCEOF:
case SWFACTION_SHIFTLEFT:
case SWFACTION_SHIFTRIGHT:
case SWFACTION_SHIFTRIGHT2:
case SWFACTION_ADD:
case SWFACTION_ADD2:
case SWFACTION_SUBTRACT:
case SWFACTION_MULTIPLY:
case SWFACTION_DIVIDE:
case SWFACTION_MODULO:
case SWFACTION_BITWISEAND:
case SWFACTION_BITWISEOR:
case SWFACTION_BITWISEXOR:
case SWFACTION_EQUAL:
case SWFACTION_EQUALS2:
case SWFACTION_LESS2:
case SWFACTION_LOGICALAND:
case SWFACTION_LOGICALOR:
case SWFACTION_GREATER:
case SWFACTION_LESSTHAN:
case SWFACTION_STRINGEQ:
case SWFACTION_STRINGCOMPARE:
case SWFACTION_STRICTEQUALS:
return decompileArithmeticOp(n, actions, maxn);
case SWFACTION_POP:
pop();
return 0;
case SWFACTION_STARTDRAG:
return decompileSTARTDRAG(n, actions, maxn);
case SWFACTION_DELETE:
return decompileDELETE(n, actions, maxn,0);
case SWFACTION_DELETE2:
return decompileDELETE(n, actions, maxn,1);
case SWFACTION_TARGETPATH:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"targetPath");
case SWFACTION_TYPEOF:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"typeof");
case SWFACTION_ORD:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"ord");
case SWFACTION_CHR:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"chr");
case SWFACTION_INT:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"int");
case SWFACTION_TOSTRING:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"String");
case SWFACTION_TONUMBER:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"Number");
case SWFACTION_RANDOMNUMBER:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"random");
case SWFACTION_STRINGLENGTH:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"length");
case SWFACTION_PLAY:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"play");
case SWFACTION_STOP:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"stop");
case SWFACTION_NEXTFRAME:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"nextFrame");
case SWFACTION_PREVFRAME:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"prevFrame");
case SWFACTION_ENDDRAG:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"stopDrag");
case SWFACTION_STOPSOUNDS:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"stopAllSounds");
case SWFACTION_TOGGLEQUALITY:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"toggleHighQuality");
case SWFACTION_MBSUBSTRING:
case SWFACTION_SUBSTRING:
return decompileSUBSTRING(n, actions, maxn);
case SWFACTION_STRINGCONCAT:
return decompileSTRINGCONCAT(n, actions, maxn);
case SWFACTION_REMOVECLIP:
return decompileREMOVECLIP(n, actions, maxn);
case SWFACTION_DUPLICATECLIP:
return decompileDUPLICATECLIP(n, actions, maxn);
case SWFACTION_SETTARGET:
return decompileSETTARGET(n, actions, maxn,0);
case SWFACTION_SETTARGET2:
return decompileSETTARGET(n, actions, maxn,1);
case SWFACTION_IMPLEMENTSOP:
return decompileIMPLEMENTS(n, actions, maxn);
case SWFACTION_CASTOP:
return decompileCAST(n, actions, maxn);
case SWFACTION_THROW:
return decompileTHROW(n, actions, maxn);
case SWFACTION_TRY:
return decompileTRY(n, actions, maxn);
default:
outputSWF_ACTION(n,&actions[n]);
return 0;
}
}
static void
decompileActions(int n, SWF_ACTION *actions, int indent)
{
int i, svindent;
svindent = gIndent;
gIndent = indent;
for(i=0;i<n;i++) {
i+=decompileAction(i, actions, n);
}
gIndent = svindent;
}
char *
decompile5Action(int n, SWF_ACTION *actions,int indent)
{
int j;
if( !n )
return NULL;
pool = NULL;
poolcounter = 0;
dcinit();
for(j=0;j<256;j++) regs[j]=0;
regs[1] = newVar("R1");
regs[2] = newVar("R2");
regs[3] = newVar("R3");
regs[4] = newVar("R4");
decompileActions(n, actions, indent);
#ifdef DEBUGSTACK
if( Stack != NULL && *dcstr)
{
int i=0;
println("/* -----------------------------------------------------------------");
println("NOTE: some stuff left on the stack at the end of a block of actions:");
while (Stack)
{
i++;
printf("%d.:\t%s",i, getString(pop()));
println("");
}
println("*/");
}
#else
if( Stack != NULL )
fprintf(stderr,
"Stuff left on the stack at the end of a block of actions!?!?!?\n");
while (Stack)
{
pop();
}
#endif
return dcgetstr();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_901_0 |
crossvul-cpp_data_bad_5475_2 | /* $Id$ */
/*
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
/*
* TIFF Library.
*
* Scanline-oriented Write Support
*/
#include "tiffiop.h"
#include <stdio.h>
#define STRIPINCR 20 /* expansion factor on strip array */
#define WRITECHECKSTRIPS(tif, module) \
(((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),0,module))
#define WRITECHECKTILES(tif, module) \
(((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),1,module))
#define BUFFERCHECK(tif) \
((((tif)->tif_flags & TIFF_BUFFERSETUP) && tif->tif_rawdata) || \
TIFFWriteBufferSetup((tif), NULL, (tmsize_t) -1))
static int TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module);
static int TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc);
int
TIFFWriteScanline(TIFF* tif, void* buf, uint32 row, uint16 sample)
{
static const char module[] = "TIFFWriteScanline";
register TIFFDirectory *td;
int status, imagegrew = 0;
uint32 strip;
if (!WRITECHECKSTRIPS(tif, module))
return (-1);
/*
* Handle delayed allocation of data buffer. This
* permits it to be sized more intelligently (using
* directory information).
*/
if (!BUFFERCHECK(tif))
return (-1);
tif->tif_flags |= TIFF_BUF4WRITE; /* not strictly sure this is right*/
td = &tif->tif_dir;
/*
* Extend image length if needed
* (but only for PlanarConfig=1).
*/
if (row >= td->td_imagelength) { /* extend image */
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
TIFFErrorExt(tif->tif_clientdata, module,
"Can not change \"ImageLength\" when using separate planes");
return (-1);
}
td->td_imagelength = row+1;
imagegrew = 1;
}
/*
* Calculate strip and check for crossings.
*/
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
if (sample >= td->td_samplesperpixel) {
TIFFErrorExt(tif->tif_clientdata, module,
"%lu: Sample out of range, max %lu",
(unsigned long) sample, (unsigned long) td->td_samplesperpixel);
return (-1);
}
strip = sample*td->td_stripsperimage + row/td->td_rowsperstrip;
} else
strip = row / td->td_rowsperstrip;
/*
* Check strip array to make sure there's space. We don't support
* dynamically growing files that have data organized in separate
* bitplanes because it's too painful. In that case we require that
* the imagelength be set properly before the first write (so that the
* strips array will be fully allocated above).
*/
if (strip >= td->td_nstrips && !TIFFGrowStrips(tif, 1, module))
return (-1);
if (strip != tif->tif_curstrip) {
/*
* Changing strips -- flush any data present.
*/
if (!TIFFFlushData(tif))
return (-1);
tif->tif_curstrip = strip;
/*
* Watch out for a growing image. The value of strips/image
* will initially be 1 (since it can't be deduced until the
* imagelength is known).
*/
if (strip >= td->td_stripsperimage && imagegrew)
td->td_stripsperimage =
TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip);
if (td->td_stripsperimage == 0) {
TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image");
return (-1);
}
tif->tif_row =
(strip % td->td_stripsperimage) * td->td_rowsperstrip;
if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
if (!(*tif->tif_setupencode)(tif))
return (-1);
tif->tif_flags |= TIFF_CODERSETUP;
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
if( td->td_stripbytecount[strip] > 0 )
{
/* if we are writing over existing tiles, zero length */
td->td_stripbytecount[strip] = 0;
/* this forces TIFFAppendToStrip() to do a seek */
tif->tif_curoff = 0;
}
if (!(*tif->tif_preencode)(tif, sample))
return (-1);
tif->tif_flags |= TIFF_POSTENCODE;
}
/*
* Ensure the write is either sequential or at the
* beginning of a strip (or that we can randomly
* access the data -- i.e. no encoding).
*/
if (row != tif->tif_row) {
if (row < tif->tif_row) {
/*
* Moving backwards within the same strip:
* backup to the start and then decode
* forward (below).
*/
tif->tif_row = (strip % td->td_stripsperimage) *
td->td_rowsperstrip;
tif->tif_rawcp = tif->tif_rawdata;
}
/*
* Seek forward to the desired row.
*/
if (!(*tif->tif_seek)(tif, row - tif->tif_row))
return (-1);
tif->tif_row = row;
}
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) buf, tif->tif_scanlinesize );
status = (*tif->tif_encoderow)(tif, (uint8*) buf,
tif->tif_scanlinesize, sample);
/* we are now poised at the beginning of the next row */
tif->tif_row = row + 1;
return (status);
}
/*
* Encode the supplied data and write it to the
* specified strip.
*
* NB: Image length must be setup before writing.
*/
tmsize_t
TIFFWriteEncodedStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteEncodedStrip";
TIFFDirectory *td = &tif->tif_dir;
uint16 sample;
if (!WRITECHECKSTRIPS(tif, module))
return ((tmsize_t) -1);
/*
* Check strip array to make sure there's space.
* We don't support dynamically growing files that
* have data organized in separate bitplanes because
* it's too painful. In that case we require that
* the imagelength be set properly before the first
* write (so that the strips array will be fully
* allocated above).
*/
if (strip >= td->td_nstrips) {
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
TIFFErrorExt(tif->tif_clientdata, module,
"Can not grow image by strips when using separate planes");
return ((tmsize_t) -1);
}
if (!TIFFGrowStrips(tif, 1, module))
return ((tmsize_t) -1);
td->td_stripsperimage =
TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip);
}
/*
* Handle delayed allocation of data buffer. This
* permits it to be sized according to the directory
* info.
*/
if (!BUFFERCHECK(tif))
return ((tmsize_t) -1);
tif->tif_flags |= TIFF_BUF4WRITE;
tif->tif_curstrip = strip;
if (td->td_stripsperimage == 0) {
TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image");
return ((tmsize_t) -1);
}
tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
if (!(*tif->tif_setupencode)(tif))
return ((tmsize_t) -1);
tif->tif_flags |= TIFF_CODERSETUP;
}
if( td->td_stripbytecount[strip] > 0 )
{
/* Make sure that at the first attempt of rewriting the tile, we will have */
/* more bytes available in the output buffer than the previous byte count, */
/* so that TIFFAppendToStrip() will detect the overflow when it is called the first */
/* time if the new compressed tile is bigger than the older one. (GDAL #4771) */
if( tif->tif_rawdatasize <= (tmsize_t)td->td_stripbytecount[strip] )
{
if( !(TIFFWriteBufferSetup(tif, NULL,
(tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[strip] + 1), 1024))) )
return ((tmsize_t)(-1));
}
/* Force TIFFAppendToStrip() to consider placing data at end
of file. */
tif->tif_curoff = 0;
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
tif->tif_flags &= ~TIFF_POSTENCODE;
/* shortcut to avoid an extra memcpy() */
if( td->td_compression == COMPRESSION_NONE )
{
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*) data, cc);
if (cc > 0 &&
!TIFFAppendToStrip(tif, strip, (uint8*) data, cc))
return ((tmsize_t) -1);
return (cc);
}
sample = (uint16)(strip / td->td_stripsperimage);
if (!(*tif->tif_preencode)(tif, sample))
return ((tmsize_t) -1);
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!(*tif->tif_encodestrip)(tif, (uint8*) data, cc, sample))
return ((tmsize_t) -1);
if (!(*tif->tif_postencode)(tif))
return ((tmsize_t) -1);
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits(tif->tif_rawdata, tif->tif_rawcc);
if (tif->tif_rawcc > 0 &&
!TIFFAppendToStrip(tif, strip, tif->tif_rawdata, tif->tif_rawcc))
return ((tmsize_t) -1);
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
return (cc);
}
/*
* Write the supplied data to the specified strip.
*
* NB: Image length must be setup before writing.
*/
tmsize_t
TIFFWriteRawStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteRawStrip";
TIFFDirectory *td = &tif->tif_dir;
if (!WRITECHECKSTRIPS(tif, module))
return ((tmsize_t) -1);
/*
* Check strip array to make sure there's space.
* We don't support dynamically growing files that
* have data organized in separate bitplanes because
* it's too painful. In that case we require that
* the imagelength be set properly before the first
* write (so that the strips array will be fully
* allocated above).
*/
if (strip >= td->td_nstrips) {
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
TIFFErrorExt(tif->tif_clientdata, module,
"Can not grow image by strips when using separate planes");
return ((tmsize_t) -1);
}
/*
* Watch out for a growing image. The value of
* strips/image will initially be 1 (since it
* can't be deduced until the imagelength is known).
*/
if (strip >= td->td_stripsperimage)
td->td_stripsperimage =
TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip);
if (!TIFFGrowStrips(tif, 1, module))
return ((tmsize_t) -1);
}
tif->tif_curstrip = strip;
if (td->td_stripsperimage == 0) {
TIFFErrorExt(tif->tif_clientdata, module,"Zero strips per image");
return ((tmsize_t) -1);
}
tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
return (TIFFAppendToStrip(tif, strip, (uint8*) data, cc) ?
cc : (tmsize_t) -1);
}
/*
* Write and compress a tile of data. The
* tile is selected by the (x,y,z,s) coordinates.
*/
tmsize_t
TIFFWriteTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s)
{
if (!TIFFCheckTile(tif, x, y, z, s))
return ((tmsize_t)(-1));
/*
* NB: A tile size of -1 is used instead of tif_tilesize knowing
* that TIFFWriteEncodedTile will clamp this to the tile size.
* This is done because the tile size may not be defined until
* after the output buffer is setup in TIFFWriteBufferSetup.
*/
return (TIFFWriteEncodedTile(tif,
TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1)));
}
/*
* Encode the supplied data and write it to the
* specified tile. There must be space for the
* data. The function clamps individual writes
* to a tile to the tile size, but does not (and
* can not) check that multiple writes to the same
* tile do not write more than tile size data.
*
* NB: Image length must be setup before writing; this
* interface does not support automatically growing
* the image on each write (as TIFFWriteScanline does).
*/
tmsize_t
TIFFWriteEncodedTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteEncodedTile";
TIFFDirectory *td;
uint16 sample;
uint32 howmany32;
if (!WRITECHECKTILES(tif, module))
return ((tmsize_t)(-1));
td = &tif->tif_dir;
if (tile >= td->td_nstrips) {
TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu",
(unsigned long) tile, (unsigned long) td->td_nstrips);
return ((tmsize_t)(-1));
}
/*
* Handle delayed allocation of data buffer. This
* permits it to be sized more intelligently (using
* directory information).
*/
if (!BUFFERCHECK(tif))
return ((tmsize_t)(-1));
tif->tif_flags |= TIFF_BUF4WRITE;
tif->tif_curtile = tile;
if( td->td_stripbytecount[tile] > 0 )
{
/* Make sure that at the first attempt of rewriting the tile, we will have */
/* more bytes available in the output buffer than the previous byte count, */
/* so that TIFFAppendToStrip() will detect the overflow when it is called the first */
/* time if the new compressed tile is bigger than the older one. (GDAL #4771) */
if( tif->tif_rawdatasize <= (tmsize_t) td->td_stripbytecount[tile] )
{
if( !(TIFFWriteBufferSetup(tif, NULL,
(tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[tile] + 1), 1024))) )
return ((tmsize_t)(-1));
}
/* Force TIFFAppendToStrip() to consider placing data at end
of file. */
tif->tif_curoff = 0;
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
/*
* Compute tiles per row & per column to compute
* current row and column
*/
howmany32=TIFFhowmany_32(td->td_imagelength, td->td_tilelength);
if (howmany32 == 0) {
TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
return ((tmsize_t)(-1));
}
tif->tif_row = (tile % howmany32) * td->td_tilelength;
howmany32=TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth);
if (howmany32 == 0) {
TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
return ((tmsize_t)(-1));
}
tif->tif_col = (tile % howmany32) * td->td_tilewidth;
if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
if (!(*tif->tif_setupencode)(tif))
return ((tmsize_t)(-1));
tif->tif_flags |= TIFF_CODERSETUP;
}
tif->tif_flags &= ~TIFF_POSTENCODE;
/*
* Clamp write amount to the tile size. This is mostly
* done so that callers can pass in some large number
* (e.g. -1) and have the tile size used instead.
*/
if ( cc < 1 || cc > tif->tif_tilesize)
cc = tif->tif_tilesize;
/* shortcut to avoid an extra memcpy() */
if( td->td_compression == COMPRESSION_NONE )
{
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*) data, cc);
if (cc > 0 &&
!TIFFAppendToStrip(tif, tile, (uint8*) data, cc))
return ((tmsize_t) -1);
return (cc);
}
sample = (uint16)(tile/td->td_stripsperimage);
if (!(*tif->tif_preencode)(tif, sample))
return ((tmsize_t)(-1));
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!(*tif->tif_encodetile)(tif, (uint8*) data, cc, sample))
return ((tmsize_t) -1);
if (!(*tif->tif_postencode)(tif))
return ((tmsize_t)(-1));
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*)tif->tif_rawdata, tif->tif_rawcc);
if (tif->tif_rawcc > 0 && !TIFFAppendToStrip(tif, tile,
tif->tif_rawdata, tif->tif_rawcc))
return ((tmsize_t)(-1));
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
return (cc);
}
/*
* Write the supplied data to the specified strip.
* There must be space for the data; we don't check
* if strips overlap!
*
* NB: Image length must be setup before writing; this
* interface does not support automatically growing
* the image on each write (as TIFFWriteScanline does).
*/
tmsize_t
TIFFWriteRawTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteRawTile";
if (!WRITECHECKTILES(tif, module))
return ((tmsize_t)(-1));
if (tile >= tif->tif_dir.td_nstrips) {
TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu",
(unsigned long) tile,
(unsigned long) tif->tif_dir.td_nstrips);
return ((tmsize_t)(-1));
}
return (TIFFAppendToStrip(tif, tile, (uint8*) data, cc) ?
cc : (tmsize_t)(-1));
}
#define isUnspecified(tif, f) \
(TIFFFieldSet(tif,f) && (tif)->tif_dir.td_imagelength == 0)
int
TIFFSetupStrips(TIFF* tif)
{
TIFFDirectory* td = &tif->tif_dir;
if (isTiled(tif))
td->td_stripsperimage =
isUnspecified(tif, FIELD_TILEDIMENSIONS) ?
td->td_samplesperpixel : TIFFNumberOfTiles(tif);
else
td->td_stripsperimage =
isUnspecified(tif, FIELD_ROWSPERSTRIP) ?
td->td_samplesperpixel : TIFFNumberOfStrips(tif);
td->td_nstrips = td->td_stripsperimage;
if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
td->td_stripsperimage /= td->td_samplesperpixel;
td->td_stripoffset = (uint64 *)
_TIFFmalloc(td->td_nstrips * sizeof (uint64));
td->td_stripbytecount = (uint64 *)
_TIFFmalloc(td->td_nstrips * sizeof (uint64));
if (td->td_stripoffset == NULL || td->td_stripbytecount == NULL)
return (0);
/*
* Place data at the end-of-file
* (by setting offsets to zero).
*/
_TIFFmemset(td->td_stripoffset, 0, td->td_nstrips*sizeof (uint64));
_TIFFmemset(td->td_stripbytecount, 0, td->td_nstrips*sizeof (uint64));
TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS);
TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
return (1);
}
#undef isUnspecified
/*
* Verify file is writable and that the directory
* information is setup properly. In doing the latter
* we also "freeze" the state of the directory so
* that important information is not changed.
*/
int
TIFFWriteCheck(TIFF* tif, int tiles, const char* module)
{
if (tif->tif_mode == O_RDONLY) {
TIFFErrorExt(tif->tif_clientdata, module, "File not open for writing");
return (0);
}
if (tiles ^ isTiled(tif)) {
TIFFErrorExt(tif->tif_clientdata, module, tiles ?
"Can not write tiles to a stripped image" :
"Can not write scanlines to a tiled image");
return (0);
}
_TIFFFillStriles( tif );
/*
* On the first write verify all the required information
* has been setup and initialize any data structures that
* had to wait until directory information was set.
* Note that a lot of our work is assumed to remain valid
* because we disallow any of the important parameters
* from changing after we start writing (i.e. once
* TIFF_BEENWRITING is set, TIFFSetField will only allow
* the image's length to be changed).
*/
if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) {
TIFFErrorExt(tif->tif_clientdata, module,
"Must set \"ImageWidth\" before writing data");
return (0);
}
if (tif->tif_dir.td_samplesperpixel == 1) {
/*
* Planarconfiguration is irrelevant in case of single band
* images and need not be included. We will set it anyway,
* because this field is used in other parts of library even
* in the single band case.
*/
if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG))
tif->tif_dir.td_planarconfig = PLANARCONFIG_CONTIG;
} else {
if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) {
TIFFErrorExt(tif->tif_clientdata, module,
"Must set \"PlanarConfiguration\" before writing data");
return (0);
}
}
if (tif->tif_dir.td_stripoffset == NULL && !TIFFSetupStrips(tif)) {
tif->tif_dir.td_nstrips = 0;
TIFFErrorExt(tif->tif_clientdata, module, "No space for %s arrays",
isTiled(tif) ? "tile" : "strip");
return (0);
}
if (isTiled(tif))
{
tif->tif_tilesize = TIFFTileSize(tif);
if (tif->tif_tilesize == 0)
return (0);
}
else
tif->tif_tilesize = (tmsize_t)(-1);
tif->tif_scanlinesize = TIFFScanlineSize(tif);
if (tif->tif_scanlinesize == 0)
return (0);
tif->tif_flags |= TIFF_BEENWRITING;
return (1);
}
/*
* Setup the raw data buffer used for encoding.
*/
int
TIFFWriteBufferSetup(TIFF* tif, void* bp, tmsize_t size)
{
static const char module[] = "TIFFWriteBufferSetup";
if (tif->tif_rawdata) {
if (tif->tif_flags & TIFF_MYBUFFER) {
_TIFFfree(tif->tif_rawdata);
tif->tif_flags &= ~TIFF_MYBUFFER;
}
tif->tif_rawdata = NULL;
}
if (size == (tmsize_t)(-1)) {
size = (isTiled(tif) ?
tif->tif_tilesize : TIFFStripSize(tif));
/*
* Make raw data buffer at least 8K
*/
if (size < 8*1024)
size = 8*1024;
bp = NULL; /* NB: force malloc */
}
if (bp == NULL) {
bp = _TIFFmalloc(size);
if (bp == NULL) {
TIFFErrorExt(tif->tif_clientdata, module, "No space for output buffer");
return (0);
}
tif->tif_flags |= TIFF_MYBUFFER;
} else
tif->tif_flags &= ~TIFF_MYBUFFER;
tif->tif_rawdata = (uint8*) bp;
tif->tif_rawdatasize = size;
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
tif->tif_flags |= TIFF_BUFFERSETUP;
return (1);
}
/*
* Grow the strip data structures by delta strips.
*/
static int
TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module)
{
TIFFDirectory *td = &tif->tif_dir;
uint64* new_stripoffset;
uint64* new_stripbytecount;
assert(td->td_planarconfig == PLANARCONFIG_CONTIG);
new_stripoffset = (uint64*)_TIFFrealloc(td->td_stripoffset,
(td->td_nstrips + delta) * sizeof (uint64));
new_stripbytecount = (uint64*)_TIFFrealloc(td->td_stripbytecount,
(td->td_nstrips + delta) * sizeof (uint64));
if (new_stripoffset == NULL || new_stripbytecount == NULL) {
if (new_stripoffset)
_TIFFfree(new_stripoffset);
if (new_stripbytecount)
_TIFFfree(new_stripbytecount);
td->td_nstrips = 0;
TIFFErrorExt(tif->tif_clientdata, module, "No space to expand strip arrays");
return (0);
}
td->td_stripoffset = new_stripoffset;
td->td_stripbytecount = new_stripbytecount;
_TIFFmemset(td->td_stripoffset + td->td_nstrips,
0, delta*sizeof (uint64));
_TIFFmemset(td->td_stripbytecount + td->td_nstrips,
0, delta*sizeof (uint64));
td->td_nstrips += delta;
tif->tif_flags |= TIFF_DIRTYDIRECT;
return (1);
}
/*
* Append the data to the specified strip.
*/
static int
TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc)
{
static const char module[] = "TIFFAppendToStrip";
TIFFDirectory *td = &tif->tif_dir;
uint64 m;
int64 old_byte_count = -1;
if (td->td_stripoffset[strip] == 0 || tif->tif_curoff == 0) {
assert(td->td_nstrips > 0);
if( td->td_stripbytecount[strip] != 0
&& td->td_stripoffset[strip] != 0
&& td->td_stripbytecount[strip] >= (uint64) cc )
{
/*
* There is already tile data on disk, and the new tile
* data we have will fit in the same space. The only
* aspect of this that is risky is that there could be
* more data to append to this strip before we are done
* depending on how we are getting called.
*/
if (!SeekOK(tif, td->td_stripoffset[strip])) {
TIFFErrorExt(tif->tif_clientdata, module,
"Seek error at scanline %lu",
(unsigned long)tif->tif_row);
return (0);
}
}
else
{
/*
* Seek to end of file, and set that as our location to
* write this strip.
*/
td->td_stripoffset[strip] = TIFFSeekFile(tif, 0, SEEK_END);
tif->tif_flags |= TIFF_DIRTYSTRIP;
}
tif->tif_curoff = td->td_stripoffset[strip];
/*
* We are starting a fresh strip/tile, so set the size to zero.
*/
old_byte_count = td->td_stripbytecount[strip];
td->td_stripbytecount[strip] = 0;
}
m = tif->tif_curoff+cc;
if (!(tif->tif_flags&TIFF_BIGTIFF))
m = (uint32)m;
if ((m<tif->tif_curoff)||(m<(uint64)cc))
{
TIFFErrorExt(tif->tif_clientdata, module, "Maximum TIFF file size exceeded");
return (0);
}
if (!WriteOK(tif, data, cc)) {
TIFFErrorExt(tif->tif_clientdata, module, "Write error at scanline %lu",
(unsigned long) tif->tif_row);
return (0);
}
tif->tif_curoff = m;
td->td_stripbytecount[strip] += cc;
if( (int64) td->td_stripbytecount[strip] != old_byte_count )
tif->tif_flags |= TIFF_DIRTYSTRIP;
return (1);
}
/*
* Internal version of TIFFFlushData that can be
* called by ``encodestrip routines'' w/o concern
* for infinite recursion.
*/
int
TIFFFlushData1(TIFF* tif)
{
if (tif->tif_rawcc > 0 && tif->tif_flags & TIFF_BUF4WRITE ) {
if (!isFillOrder(tif, tif->tif_dir.td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*)tif->tif_rawdata,
tif->tif_rawcc);
if (!TIFFAppendToStrip(tif,
isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip,
tif->tif_rawdata, tif->tif_rawcc))
return (0);
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
}
return (1);
}
/*
* Set the current write offset. This should only be
* used to set the offset to a known previous location
* (very carefully), or to 0 so that the next write gets
* appended to the end of the file.
*/
void
TIFFSetWriteOffset(TIFF* tif, toff_t off)
{
tif->tif_curoff = off;
}
/* vim: set ts=8 sts=8 sw=8 noet: */
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5475_2 |
crossvul-cpp_data_bad_346_10 | /*
* util.c: utility functions used by OpenSC command line tools.
*
* Copyright (C) 2011 OpenSC Project developers
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#ifndef _WIN32
#include <termios.h>
#else
#include <conio.h>
#endif
#include <ctype.h>
#include "util.h"
#include "ui/notify.h"
int
is_string_valid_atr(const char *atr_str)
{
unsigned char atr[SC_MAX_ATR_SIZE];
size_t atr_len = sizeof(atr);
if (sc_hex_to_bin(atr_str, atr, &atr_len))
return 0;
if (atr_len < 2)
return 0;
if (atr[0] != 0x3B && atr[0] != 0x3F)
return 0;
return 1;
}
int
util_connect_card_ex(sc_context_t *ctx, sc_card_t **cardp,
const char *reader_id, int do_wait, int do_lock, int verbose)
{
struct sc_reader *reader = NULL, *found = NULL;
struct sc_card *card = NULL;
int r;
sc_notify_init();
if (do_wait) {
unsigned int event;
if (sc_ctx_get_reader_count(ctx) == 0) {
fprintf(stderr, "Waiting for a reader to be attached...\n");
r = sc_wait_for_event(ctx, SC_EVENT_READER_ATTACHED, &found, &event, -1, NULL);
if (r < 0) {
fprintf(stderr, "Error while waiting for a reader: %s\n", sc_strerror(r));
return 3;
}
r = sc_ctx_detect_readers(ctx);
if (r < 0) {
fprintf(stderr, "Error while refreshing readers: %s\n", sc_strerror(r));
return 3;
}
}
fprintf(stderr, "Waiting for a card to be inserted...\n");
r = sc_wait_for_event(ctx, SC_EVENT_CARD_INSERTED, &found, &event, -1, NULL);
if (r < 0) {
fprintf(stderr, "Error while waiting for a card: %s\n", sc_strerror(r));
return 3;
}
reader = found;
}
else if (sc_ctx_get_reader_count(ctx) == 0) {
fprintf(stderr, "No smart card readers found.\n");
return 1;
}
else {
if (!reader_id) {
unsigned int i;
/* Automatically try to skip to a reader with a card if reader not specified */
for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) {
reader = sc_ctx_get_reader(ctx, i);
if (sc_detect_card_presence(reader) & SC_READER_CARD_PRESENT) {
fprintf(stderr, "Using reader with a card: %s\n", reader->name);
goto autofound;
}
}
/* If no reader had a card, default to the first reader */
reader = sc_ctx_get_reader(ctx, 0);
}
else {
/* If the reader identifier looks like an ATR, try to find the reader with that card */
if (is_string_valid_atr(reader_id)) {
unsigned char atr_buf[SC_MAX_ATR_SIZE];
size_t atr_buf_len = sizeof(atr_buf);
unsigned int i;
sc_hex_to_bin(reader_id, atr_buf, &atr_buf_len);
/* Loop readers, looking for a card with ATR */
for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) {
struct sc_reader *rdr = sc_ctx_get_reader(ctx, i);
if (!(sc_detect_card_presence(rdr) & SC_READER_CARD_PRESENT))
continue;
else if (rdr->atr.len != atr_buf_len)
continue;
else if (memcmp(rdr->atr.value, atr_buf, rdr->atr.len))
continue;
fprintf(stderr, "Matched ATR in reader: %s\n", rdr->name);
reader = rdr;
goto autofound;
}
}
else {
char *endptr = NULL;
unsigned int num;
errno = 0;
num = strtol(reader_id, &endptr, 0);
if (!errno && endptr && *endptr == '\0')
reader = sc_ctx_get_reader(ctx, num);
else
reader = sc_ctx_get_reader_by_name(ctx, reader_id);
}
}
autofound:
if (!reader) {
fprintf(stderr, "Reader \"%s\" not found (%d reader(s) detected)\n",
reader_id, sc_ctx_get_reader_count(ctx));
return 1;
}
if (sc_detect_card_presence(reader) <= 0) {
fprintf(stderr, "Card not present.\n");
return 3;
}
}
if (verbose)
printf("Connecting to card in reader %s...\n", reader->name);
r = sc_connect_card(reader, &card);
if (r < 0) {
fprintf(stderr, "Failed to connect to card: %s\n", sc_strerror(r));
return 1;
}
if (verbose)
printf("Using card driver %s.\n", card->driver->name);
if (do_lock) {
r = sc_lock(card);
if (r < 0) {
fprintf(stderr, "Failed to lock card: %s\n", sc_strerror(r));
sc_disconnect_card(card);
return 1;
}
}
*cardp = card;
return 0;
}
int
util_connect_card(sc_context_t *ctx, sc_card_t **cardp,
const char *reader_id, int do_wait, int verbose)
{
return util_connect_card_ex(ctx, cardp, reader_id, do_wait, 1, verbose);
}
void util_print_binary(FILE *f, const u8 *buf, int count)
{
int i;
for (i = 0; i < count; i++) {
unsigned char c = buf[i];
const char *format;
if (!isprint(c))
format = "\\x%02X";
else
format = "%c";
fprintf(f, format, c);
}
(void) fflush(f);
}
void util_hex_dump(FILE *f, const u8 *in, int len, const char *sep)
{
int i;
for (i = 0; i < len; i++) {
if (sep != NULL && i)
fprintf(f, "%s", sep);
fprintf(f, "%02X", in[i]);
}
}
void util_hex_dump_asc(FILE *f, const u8 *in, size_t count, int addr)
{
int lines = 0;
while (count) {
char ascbuf[17];
size_t i;
if (addr >= 0) {
fprintf(f, "%08X: ", addr);
addr += 16;
}
for (i = 0; i < count && i < 16; i++) {
fprintf(f, "%02X ", *in);
if (isprint(*in))
ascbuf[i] = *in;
else
ascbuf[i] = '.';
in++;
}
count -= i;
ascbuf[i] = 0;
for (; i < 16 && lines; i++)
fprintf(f, " ");
fprintf(f, "%s\n", ascbuf);
lines++;
}
}
NORETURN void
util_print_usage_and_die(const char *app_name, const struct option options[],
const char *option_help[], const char *args)
{
int i;
int header_shown = 0;
if (args)
printf("Usage: %s [OPTIONS] %s\n", app_name, args);
else
printf("Usage: %s [OPTIONS]\n", app_name);
for (i = 0; options[i].name; i++) {
char buf[40];
const char *arg_str;
/* Skip "hidden" options */
if (option_help[i] == NULL)
continue;
if (!header_shown++)
printf("Options:\n");
switch (options[i].has_arg) {
case 1:
arg_str = " <arg>";
break;
case 2:
arg_str = " [arg]";
break;
default:
arg_str = "";
break;
}
if (isascii(options[i].val) &&
isprint(options[i].val) && !isspace(options[i].val))
sprintf(buf, "-%c, --%s%s", options[i].val, options[i].name, arg_str);
else
sprintf(buf, " --%s%s", options[i].name, arg_str);
/* print the line - wrap if necessary */
if (strlen(buf) > 28) {
printf(" %s\n", buf);
buf[0] = '\0';
}
printf(" %-28s %s\n", buf, option_help[i]);
}
exit(2);
}
const char * util_acl_to_str(const sc_acl_entry_t *e)
{
static char line[80], buf[20];
unsigned int acl;
if (e == NULL)
return "N/A";
line[0] = 0;
while (e != NULL) {
acl = e->method;
switch (acl) {
case SC_AC_UNKNOWN:
return "N/A";
case SC_AC_NEVER:
return "NEVR";
case SC_AC_NONE:
return "NONE";
case SC_AC_CHV:
strcpy(buf, "CHV");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "%d", e->key_ref);
break;
case SC_AC_TERM:
strcpy(buf, "TERM");
break;
case SC_AC_PRO:
strcpy(buf, "PROT");
break;
case SC_AC_AUT:
strcpy(buf, "AUTH");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 4, "%d", e->key_ref);
break;
case SC_AC_SEN:
strcpy(buf, "Sec.Env. ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
case SC_AC_SCB:
strcpy(buf, "Sec.ControlByte ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "Ox%X", e->key_ref);
break;
case SC_AC_IDA:
strcpy(buf, "PKCS#15 AuthID ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
default:
strcpy(buf, "????");
break;
}
strcat(line, buf);
strcat(line, " ");
e = e->next;
}
line[strlen(line)-1] = 0; /* get rid of trailing space */
return line;
}
NORETURN void
util_fatal(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\nAborting.\n");
va_end(ap);
sc_notify_close();
exit(1);
}
void
util_error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
void
util_warn(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "warning: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
int
util_getpass (char **lineptr, size_t *len, FILE *stream)
{
#define MAX_PASS_SIZE 128
char *buf;
size_t i;
int ch = 0;
#ifndef _WIN32
struct termios old, new;
fflush(stdout);
if (tcgetattr (fileno (stdout), &old) != 0)
return -1;
new = old;
new.c_lflag &= ~ECHO;
if (tcsetattr (fileno (stdout), TCSAFLUSH, &new) != 0)
return -1;
#endif
buf = calloc(1, MAX_PASS_SIZE);
if (!buf)
return -1;
for (i = 0; i < MAX_PASS_SIZE - 1; i++) {
#ifndef _WIN32
ch = getchar();
#else
ch = _getch();
#endif
if (ch == 0 || ch == 3)
break;
if (ch == '\n' || ch == '\r')
break;
buf[i] = (char) ch;
}
#ifndef _WIN32
tcsetattr (fileno (stdout), TCSAFLUSH, &old);
fputs("\n", stdout);
#endif
if (ch == 0 || ch == 3) {
free(buf);
return -1;
}
if (*lineptr && (!len || *len < i+1)) {
free(*lineptr);
*lineptr = NULL;
}
if (*lineptr) {
memcpy(*lineptr,buf,i+1);
memset(buf, 0, MAX_PASS_SIZE);
free(buf);
} else {
*lineptr = buf;
if (len)
*len = MAX_PASS_SIZE;
}
return i;
}
size_t
util_get_pin(const char *input, const char **pin)
{
size_t inputlen = strlen(input);
size_t pinlen = 0;
if(inputlen > 4 && strncasecmp(input, "env:", 4) == 0) {
// Get a PIN from a environment variable
*pin = getenv(input + 4);
pinlen = *pin ? strlen(*pin) : 0;
} else {
//Just use the input
*pin = input;
pinlen = inputlen;
}
return pinlen;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_346_10 |
crossvul-cpp_data_bad_4788_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% V V IIIII FFFFF FFFFF %
% V V I F F %
% V V I FFF FFF %
% V V I F F %
% V IIIII F F %
% %
% %
% Read/Write Khoros Visualization Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% 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/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteVIFFImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s V I F F %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsVIFF() returns MagickTrue if the image format type, identified by the
% magick string, is VIFF.
%
% The format of the IsVIFF method is:
%
% MagickBooleanType IsVIFF(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 IsVIFF(const unsigned char *magick,const size_t length)
{
if (length < 2)
return(MagickFalse);
if (memcmp(magick,"\253\001",2) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d V I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadVIFFImage() reads a Khoros Visualization 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 ReadVIFFImage method is:
%
% Image *ReadVIFFImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: Method ReadVIFFImage returns a pointer to the image after
% reading. A null image is returned if there is a memory shortage or if
% the image cannot be read.
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType CheckMemoryOverflow(const size_t count,
const size_t quantum)
{
size_t
size;
size=count*quantum;
if ((count == 0) || (quantum != (size/count)))
{
errno=ENOMEM;
return(MagickTrue);
}
return(MagickFalse);
}
static Image *ReadVIFFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define VFF_CM_genericRGB 15
#define VFF_CM_ntscRGB 1
#define VFF_CM_NONE 0
#define VFF_DEP_DECORDER 0x4
#define VFF_DEP_NSORDER 0x8
#define VFF_DES_RAW 0
#define VFF_LOC_IMPLICIT 1
#define VFF_MAPTYP_NONE 0
#define VFF_MAPTYP_1_BYTE 1
#define VFF_MAPTYP_2_BYTE 2
#define VFF_MAPTYP_4_BYTE 4
#define VFF_MAPTYP_FLOAT 5
#define VFF_MAPTYP_DOUBLE 7
#define VFF_MS_NONE 0
#define VFF_MS_ONEPERBAND 1
#define VFF_MS_SHARED 3
#define VFF_TYP_BIT 0
#define VFF_TYP_1_BYTE 1
#define VFF_TYP_2_BYTE 2
#define VFF_TYP_4_BYTE 4
#define VFF_TYP_FLOAT 5
#define VFF_TYP_DOUBLE 9
typedef struct _ViffInfo
{
unsigned char
identifier,
file_type,
release,
version,
machine_dependency,
reserve[3];
char
comment[512];
unsigned int
rows,
columns,
subrows;
int
x_offset,
y_offset;
float
x_bits_per_pixel,
y_bits_per_pixel;
unsigned int
location_type,
location_dimension,
number_of_images,
number_data_bands,
data_storage_type,
data_encode_scheme,
map_scheme,
map_storage_type,
map_rows,
map_columns,
map_subrows,
map_enable,
maps_per_cycle,
color_space_model;
} ViffInfo;
double
min_value,
scale_factor,
value;
Image
*image;
int
bit;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bytes_per_pixel,
max_packets,
quantum;
ssize_t
count,
y;
unsigned char
*pixels;
unsigned long
lsb_first;
ViffInfo
viff_info;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read VIFF header (1024 bytes).
*/
count=ReadBlob(image,1,&viff_info.identifier);
do
{
/*
Verify VIFF identifier.
*/
if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab))
ThrowReaderException(CorruptImageError,"NotAVIFFImage");
/*
Initialize VIFF image.
*/
(void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type);
(void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release);
(void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version);
(void) ReadBlob(image,sizeof(viff_info.machine_dependency),
&viff_info.machine_dependency);
(void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve);
(void) ReadBlob(image,512,(unsigned char *) viff_info.comment);
viff_info.comment[511]='\0';
if (strlen(viff_info.comment) > 4)
(void) SetImageProperty(image,"comment",viff_info.comment);
if ((viff_info.machine_dependency == VFF_DEP_DECORDER) ||
(viff_info.machine_dependency == VFF_DEP_NSORDER))
image->endian=LSBEndian;
else
image->endian=MSBEndian;
viff_info.rows=ReadBlobLong(image);
viff_info.columns=ReadBlobLong(image);
viff_info.subrows=ReadBlobLong(image);
viff_info.x_offset=ReadBlobSignedLong(image);
viff_info.y_offset=ReadBlobSignedLong(image);
viff_info.x_bits_per_pixel=(float) ReadBlobLong(image);
viff_info.y_bits_per_pixel=(float) ReadBlobLong(image);
viff_info.location_type=ReadBlobLong(image);
viff_info.location_dimension=ReadBlobLong(image);
viff_info.number_of_images=ReadBlobLong(image);
viff_info.number_data_bands=ReadBlobLong(image);
viff_info.data_storage_type=ReadBlobLong(image);
viff_info.data_encode_scheme=ReadBlobLong(image);
viff_info.map_scheme=ReadBlobLong(image);
viff_info.map_storage_type=ReadBlobLong(image);
viff_info.map_rows=ReadBlobLong(image);
viff_info.map_columns=ReadBlobLong(image);
viff_info.map_subrows=ReadBlobLong(image);
viff_info.map_enable=ReadBlobLong(image);
viff_info.maps_per_cycle=ReadBlobLong(image);
viff_info.color_space_model=ReadBlobLong(image);
for (i=0; i < 420; i++)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
image->columns=viff_info.rows;
image->rows=viff_info.columns;
image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL :
MAGICKCORE_QUANTUM_DEPTH;
/*
Verify that we can read this VIFF image.
*/
number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows;
if (number_pixels != (size_t) number_pixels)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (number_pixels == 0)
ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported");
if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((viff_info.data_storage_type != VFF_TYP_BIT) &&
(viff_info.data_storage_type != VFF_TYP_1_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_2_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_4_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_FLOAT) &&
(viff_info.data_storage_type != VFF_TYP_DOUBLE))
ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported");
if (viff_info.data_encode_scheme != VFF_DES_RAW)
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) &&
(viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_FLOAT) &&
(viff_info.map_storage_type != VFF_MAPTYP_DOUBLE))
ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported");
if ((viff_info.color_space_model != VFF_CM_NONE) &&
(viff_info.color_space_model != VFF_CM_ntscRGB) &&
(viff_info.color_space_model != VFF_CM_genericRGB))
ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported");
if (viff_info.location_type != VFF_LOC_IMPLICIT)
ThrowReaderException(CoderError,"LocationTypeIsNotSupported");
if (viff_info.number_of_images != 1)
ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported");
if (viff_info.map_rows == 0)
viff_info.map_scheme=VFF_MS_NONE;
switch ((int) viff_info.map_scheme)
{
case VFF_MS_NONE:
{
if (viff_info.number_data_bands < 3)
{
/*
Create linear color ramp.
*/
if (viff_info.data_storage_type == VFF_TYP_BIT)
image->colors=2;
else
if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE)
image->colors=256UL;
else
image->colors=image->depth <= 8 ? 256UL : 65536UL;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
break;
}
case VFF_MS_ONEPERBAND:
case VFF_MS_SHARED:
{
unsigned char
*viff_colormap;
/*
Allocate VIFF colormap.
*/
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break;
case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break;
case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break;
case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break;
case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break;
default: bytes_per_pixel=1; break;
}
image->colors=viff_info.map_columns;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (viff_info.map_rows >
(viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap));
if (viff_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Read VIFF raster colormap.
*/
(void) ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows,
viff_colormap);
lsb_first=1;
if (*(char *) &lsb_first &&
((viff_info.machine_dependency != VFF_DEP_DECORDER) &&
(viff_info.machine_dependency != VFF_DEP_NSORDER)))
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_2_BYTE:
{
MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors*
viff_info.map_rows));
break;
}
case VFF_MAPTYP_4_BYTE:
case VFF_MAPTYP_FLOAT:
{
MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors*
viff_info.map_rows));
break;
}
default: break;
}
for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++)
{
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break;
case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break;
case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break;
case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break;
default: value=1.0*viff_colormap[i]; break;
}
if (i < (ssize_t) image->colors)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char) value);
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
value);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value);
}
else
if (i < (ssize_t) (2*image->colors))
image->colormap[i % image->colors].green=ScaleCharToQuantum(
(unsigned char) value);
else
if (i < (ssize_t) (3*image->colors))
image->colormap[i % image->colors].blue=ScaleCharToQuantum(
(unsigned char) value);
}
viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap);
break;
}
default:
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
}
/*
Initialize image structure.
*/
image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse;
image->storage_class=
(viff_info.number_data_bands < 3 ? PseudoClass : DirectClass);
image->columns=viff_info.rows;
image->rows=viff_info.columns;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate VIFF pixels.
*/
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: bytes_per_pixel=2; break;
case VFF_TYP_4_BYTE: bytes_per_pixel=4; break;
case VFF_TYP_FLOAT: bytes_per_pixel=4; break;
case VFF_TYP_DOUBLE: bytes_per_pixel=8; break;
default: bytes_per_pixel=1; break;
}
if (viff_info.data_storage_type == VFF_TYP_BIT)
{
if (CheckMemoryOverflow((image->columns+7UL) >> 3UL,image->rows) != MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
max_packets=((image->columns+7UL) >> 3UL)*image->rows;
}
else
{
if (CheckMemoryOverflow(number_pixels,viff_info.number_data_bands) != MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
max_packets=(size_t) (number_pixels*viff_info.number_data_bands);
}
pixels=(unsigned char *) AcquireQuantumMemory(MagickMax(number_pixels,
max_packets),bytes_per_pixel*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,bytes_per_pixel*max_packets,pixels);
lsb_first=1;
if (*(char *) &lsb_first &&
((viff_info.machine_dependency != VFF_DEP_DECORDER) &&
(viff_info.machine_dependency != VFF_DEP_NSORDER)))
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE:
{
MSBOrderShort(pixels,bytes_per_pixel*max_packets);
break;
}
case VFF_TYP_4_BYTE:
case VFF_TYP_FLOAT:
{
MSBOrderLong(pixels,bytes_per_pixel*max_packets);
break;
}
default: break;
}
min_value=0.0;
scale_factor=1.0;
if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) &&
(viff_info.map_scheme == VFF_MS_NONE))
{
double
max_value;
/*
Determine scale factor.
*/
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break;
default: value=1.0*pixels[0]; break;
}
max_value=value;
min_value=value;
for (i=0; i < (ssize_t) max_packets; i++)
{
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;
default: value=1.0*pixels[i]; break;
}
if (value > max_value)
max_value=value;
else
if (value < min_value)
min_value=value;
}
if ((min_value == 0) && (max_value == 0))
scale_factor=0;
else
if (min_value == max_value)
{
scale_factor=(MagickRealType) QuantumRange/min_value;
min_value=0;
}
else
scale_factor=(MagickRealType) QuantumRange/(max_value-min_value);
}
/*
Convert pixels to Quantum size.
*/
p=(unsigned char *) pixels;
for (i=0; i < (ssize_t) max_packets; i++)
{
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;
default: value=1.0*pixels[i]; break;
}
if (viff_info.map_scheme == VFF_MS_NONE)
{
value=(value-min_value)*scale_factor;
if (value > QuantumRange)
value=QuantumRange;
else
if (value < 0)
value=0;
}
*p=(unsigned char) ((Quantum) value);
p++;
}
/*
Convert VIFF raster image to pixel packets.
*/
p=(unsigned char *) pixels;
if (viff_info.data_storage_type == VFF_TYP_BIT)
{
/*
Convert bitmap scanline.
*/
if (image->storage_class != PseudoClass)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) (image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);
SetPixelRed(q,quantum == 0 ? 0 : QuantumRange);
SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange);
SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange);
if (image->storage_class == PseudoClass)
SetPixelIndex(indexes+x+bit,quantum);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (int) (image->columns % 8); bit++)
{
quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);
SetPixelRed(q,quantum == 0 ? 0 : QuantumRange);
SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange);
SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange);
if (image->storage_class == PseudoClass)
SetPixelIndex(indexes+x+bit,quantum);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
if (image->storage_class == PseudoClass)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*p++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
{
/*
Convert DirectColor scanline.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p));
SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels)));
SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels)));
if (image->colors != 0)
{
ssize_t
index;
index=(ssize_t) GetPixelRed(q);
SetPixelRed(q,image->colormap[(ssize_t)
ConstrainColormapIndex(image,index)].red);
index=(ssize_t) GetPixelGreen(q);
SetPixelGreen(q,image->colormap[(ssize_t)
ConstrainColormapIndex(image,index)].green);
index=(ssize_t) GetPixelRed(q);
SetPixelBlue(q,image->colormap[(ssize_t)
ConstrainColormapIndex(image,index)].blue);
}
SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange-
ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity);
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (image->storage_class == PseudoClass)
(void) SyncImage(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
count=ReadBlob(image,1,&viff_info.identifier);
if ((count != 0) && (viff_info.identifier == 0xab))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (viff_info.identifier == 0xab));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r V I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterVIFFImage() adds properties for the VIFF 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 RegisterVIFFImage method is:
%
% size_t RegisterVIFFImage(void)
%
*/
ModuleExport size_t RegisterVIFFImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("VIFF");
entry->decoder=(DecodeImageHandler *) ReadVIFFImage;
entry->encoder=(EncodeImageHandler *) WriteVIFFImage;
entry->magick=(IsImageFormatHandler *) IsVIFF;
entry->description=ConstantString("Khoros Visualization image");
entry->module=ConstantString("VIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("XV");
entry->decoder=(DecodeImageHandler *) ReadVIFFImage;
entry->encoder=(EncodeImageHandler *) WriteVIFFImage;
entry->description=ConstantString("Khoros Visualization image");
entry->module=ConstantString("VIFF");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r V I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterVIFFImage() removes format registrations made by the
% VIFF module from the list of supported formats.
%
% The format of the UnregisterVIFFImage method is:
%
% UnregisterVIFFImage(void)
%
*/
ModuleExport void UnregisterVIFFImage(void)
{
(void) UnregisterMagickInfo("VIFF");
(void) UnregisterMagickInfo("XV");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e V I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteVIFFImage() writes an image to a file in the VIFF image format.
%
% The format of the WriteVIFFImage method is:
%
% MagickBooleanType WriteVIFFImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteVIFFImage(const ImageInfo *image_info,
Image *image)
{
#define VFF_CM_genericRGB 15
#define VFF_CM_NONE 0
#define VFF_DEP_IEEEORDER 0x2
#define VFF_DES_RAW 0
#define VFF_LOC_IMPLICIT 1
#define VFF_MAPTYP_NONE 0
#define VFF_MAPTYP_1_BYTE 1
#define VFF_MS_NONE 0
#define VFF_MS_ONEPERBAND 1
#define VFF_TYP_BIT 0
#define VFF_TYP_1_BYTE 1
typedef struct _ViffInfo
{
char
identifier,
file_type,
release,
version,
machine_dependency,
reserve[3],
comment[512];
size_t
rows,
columns,
subrows;
int
x_offset,
y_offset;
unsigned int
x_bits_per_pixel,
y_bits_per_pixel,
location_type,
location_dimension,
number_of_images,
number_data_bands,
data_storage_type,
data_encode_scheme,
map_scheme,
map_storage_type,
map_rows,
map_columns,
map_subrows,
map_enable,
maps_per_cycle,
color_space_model;
} ViffInfo;
const char
*value;
MagickBooleanType
status;
MagickOffsetType
scene;
MagickSizeType
number_pixels,
packets;
MemoryInfo
*pixel_info;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
x;
register ssize_t
i;
register unsigned char
*q;
ssize_t
y;
unsigned char
*pixels;
ViffInfo
viff_info;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) ResetMagickMemory(&viff_info,0,sizeof(ViffInfo));
scene=0;
do
{
/*
Initialize VIFF image structure.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
DisableMSCWarning(4310)
viff_info.identifier=(char) 0xab;
RestoreMSCWarning
viff_info.file_type=1;
viff_info.release=1;
viff_info.version=3;
viff_info.machine_dependency=VFF_DEP_IEEEORDER; /* IEEE byte ordering */
*viff_info.comment='\0';
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
(void) CopyMagickString(viff_info.comment,value,MagickMin(strlen(value),
511)+1);
viff_info.rows=image->columns;
viff_info.columns=image->rows;
viff_info.subrows=0;
viff_info.x_offset=(~0);
viff_info.y_offset=(~0);
viff_info.x_bits_per_pixel=0;
viff_info.y_bits_per_pixel=0;
viff_info.location_type=VFF_LOC_IMPLICIT;
viff_info.location_dimension=0;
viff_info.number_of_images=1;
viff_info.data_encode_scheme=VFF_DES_RAW;
viff_info.map_scheme=VFF_MS_NONE;
viff_info.map_storage_type=VFF_MAPTYP_NONE;
viff_info.map_rows=0;
viff_info.map_columns=0;
viff_info.map_subrows=0;
viff_info.map_enable=1; /* no colormap */
viff_info.maps_per_cycle=0;
number_pixels=(MagickSizeType) image->columns*image->rows;
if (image->storage_class == DirectClass)
{
/*
Full color VIFF raster.
*/
viff_info.number_data_bands=image->matte ? 4U : 3U;
viff_info.color_space_model=VFF_CM_genericRGB;
viff_info.data_storage_type=VFF_TYP_1_BYTE;
packets=viff_info.number_data_bands*number_pixels;
}
else
{
viff_info.number_data_bands=1;
viff_info.color_space_model=VFF_CM_NONE;
viff_info.data_storage_type=VFF_TYP_1_BYTE;
packets=number_pixels;
if (SetImageGray(image,&image->exception) == MagickFalse)
{
/*
Colormapped VIFF raster.
*/
viff_info.map_scheme=VFF_MS_ONEPERBAND;
viff_info.map_storage_type=VFF_MAPTYP_1_BYTE;
viff_info.map_rows=3;
viff_info.map_columns=(unsigned int) image->colors;
}
else
if (image->colors <= 2)
{
/*
Monochrome VIFF raster.
*/
viff_info.data_storage_type=VFF_TYP_BIT;
packets=((image->columns+7) >> 3)*image->rows;
}
}
/*
Write VIFF image header (pad to 1024 bytes).
*/
(void) WriteBlob(image,sizeof(viff_info.identifier),(unsigned char *)
&viff_info.identifier);
(void) WriteBlob(image,sizeof(viff_info.file_type),(unsigned char *)
&viff_info.file_type);
(void) WriteBlob(image,sizeof(viff_info.release),(unsigned char *)
&viff_info.release);
(void) WriteBlob(image,sizeof(viff_info.version),(unsigned char *)
&viff_info.version);
(void) WriteBlob(image,sizeof(viff_info.machine_dependency),
(unsigned char *) &viff_info.machine_dependency);
(void) WriteBlob(image,sizeof(viff_info.reserve),(unsigned char *)
viff_info.reserve);
(void) WriteBlob(image,512,(unsigned char *) viff_info.comment);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.rows);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.columns);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.subrows);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.x_offset);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.y_offset);
viff_info.x_bits_per_pixel=(unsigned int) ((63 << 24) | (128 << 16));
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.x_bits_per_pixel);
viff_info.y_bits_per_pixel=(unsigned int) ((63 << 24) | (128 << 16));
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.y_bits_per_pixel);
(void) WriteBlobMSBLong(image,viff_info.location_type);
(void) WriteBlobMSBLong(image,viff_info.location_dimension);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.number_of_images);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.number_data_bands);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.data_storage_type);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.data_encode_scheme);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_scheme);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_storage_type);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_rows);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_columns);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_subrows);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_enable);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.maps_per_cycle);
(void) WriteBlobMSBLong(image,(unsigned int) viff_info.color_space_model);
for (i=0; i < 420; i++)
(void) WriteBlobByte(image,'\0');
/*
Convert MIFF to VIFF raster pixels.
*/
pixel_info=AcquireVirtualMemory((size_t) packets,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
q=pixels;
if (image->storage_class == DirectClass)
{
/*
Convert DirectClass packet to VIFF RGB pixel.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q=ScaleQuantumToChar(GetPixelRed(p));
*(q+number_pixels)=ScaleQuantumToChar(GetPixelGreen(p));
*(q+number_pixels*2)=ScaleQuantumToChar(GetPixelBlue(p));
if (image->matte != MagickFalse)
*(q+number_pixels*3)=ScaleQuantumToChar((Quantum)
(GetPixelAlpha(p)));
p++;
q++;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
if (SetImageGray(image,&image->exception) == MagickFalse)
{
unsigned char
*viff_colormap;
/*
Dump colormap to file.
*/
viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
3*sizeof(*viff_colormap));
if (viff_colormap == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
q=viff_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
*q++=ScaleQuantumToChar(image->colormap[i].red);
for (i=0; i < (ssize_t) image->colors; i++)
*q++=ScaleQuantumToChar(image->colormap[i].green);
for (i=0; i < (ssize_t) image->colors; i++)
*q++=ScaleQuantumToChar(image->colormap[i].blue);
(void) WriteBlob(image,3*image->colors,viff_colormap);
viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap);
/*
Convert PseudoClass packet to VIFF colormapped pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
*q++=(unsigned char) GetPixelIndex(indexes+x);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
if (image->colors <= 2)
{
ssize_t
x,
y;
register unsigned char
bit,
byte;
/*
Convert PseudoClass image to a VIFF monochrome image.
*/
(void) SetImageType(image,BilevelType);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte>>=1;
if (GetPixelLuma(image,p) < (QuantumRange/2.0))
byte|=0x80;
bit++;
if (bit == 8)
{
*q++=byte;
bit=0;
byte=0;
}
}
if (bit != 0)
*q++=byte >> (8-bit);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Convert PseudoClass packet to VIFF grayscale pixel.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) ClampToQuantum(GetPixelLuma(image,p));
p++;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
(void) WriteBlob(image,(size_t) packets,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4788_1 |
crossvul-cpp_data_good_5733_9 | /*
* Copyright (c) 2011 Stefano Sabatini
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* filter for showing textual video frame information
*/
#include "libavutil/adler32.h"
#include "libavutil/imgutils.h"
#include "libavutil/internal.h"
#include "libavutil/pixdesc.h"
#include "libavutil/timestamp.h"
#include "avfilter.h"
#include "internal.h"
#include "video.h"
static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
{
AVFilterContext *ctx = inlink->dst;
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
uint32_t plane_checksum[4] = {0}, checksum = 0;
int i, plane, vsub = desc->log2_chroma_h;
for (plane = 0; plane < 4 && frame->data[plane] && frame->linesize[plane]; plane++) {
int64_t linesize = av_image_get_linesize(frame->format, frame->width, plane);
uint8_t *data = frame->data[plane];
int h = plane == 1 || plane == 2 ? FF_CEIL_RSHIFT(inlink->h, vsub) : inlink->h;
if (linesize < 0)
return linesize;
for (i = 0; i < h; i++) {
plane_checksum[plane] = av_adler32_update(plane_checksum[plane], data, linesize);
checksum = av_adler32_update(checksum, data, linesize);
data += frame->linesize[plane];
}
}
av_log(ctx, AV_LOG_INFO,
"n:%"PRId64" pts:%s pts_time:%s pos:%"PRId64" "
"fmt:%s sar:%d/%d s:%dx%d i:%c iskey:%d type:%c "
"checksum:%08X plane_checksum:[%08X",
inlink->frame_count,
av_ts2str(frame->pts), av_ts2timestr(frame->pts, &inlink->time_base), av_frame_get_pkt_pos(frame),
desc->name,
frame->sample_aspect_ratio.num, frame->sample_aspect_ratio.den,
frame->width, frame->height,
!frame->interlaced_frame ? 'P' : /* Progressive */
frame->top_field_first ? 'T' : 'B', /* Top / Bottom */
frame->key_frame,
av_get_picture_type_char(frame->pict_type),
checksum, plane_checksum[0]);
for (plane = 1; plane < 4 && frame->data[plane] && frame->linesize[plane]; plane++)
av_log(ctx, AV_LOG_INFO, " %08X", plane_checksum[plane]);
av_log(ctx, AV_LOG_INFO, "]\n");
return ff_filter_frame(inlink->dst->outputs[0], frame);
}
static const AVFilterPad avfilter_vf_showinfo_inputs[] = {
{
.name = "default",
.type = AVMEDIA_TYPE_VIDEO,
.get_video_buffer = ff_null_get_video_buffer,
.filter_frame = filter_frame,
},
{ NULL }
};
static const AVFilterPad avfilter_vf_showinfo_outputs[] = {
{
.name = "default",
.type = AVMEDIA_TYPE_VIDEO
},
{ NULL }
};
AVFilter avfilter_vf_showinfo = {
.name = "showinfo",
.description = NULL_IF_CONFIG_SMALL("Show textual information for each video frame."),
.inputs = avfilter_vf_showinfo_inputs,
.outputs = avfilter_vf_showinfo_outputs,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5733_9 |
crossvul-cpp_data_bad_1848_3 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS U U N N %
% SS U U NN N %
% SSS U U N N N %
% SS U U N NN %
% SSSSS UUU N N %
% %
% %
% Read/Write Sun Rasterfile Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/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/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteSUNImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s S U N %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsSUN() returns MagickTrue if the image format type, identified by the
% magick string, is SUN.
%
% The format of the IsSUN method is:
%
% MagickBooleanType IsSUN(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 IsSUN(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\131\246\152\225",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% 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(const unsigned char *compressed_pixels,
% const size_t length,unsigned char *pixels)
%
% A description of each parameter follows:
%
% o compressed_pixels: The address of a byte (8 bits) array of compressed
% pixel data.
%
% o length: An integer value that is the total number of bytes of the
% source image (as just read by ReadBlob)
%
% o pixels: The address of a byte (8 bits) array of pixel data created by
% the uncompression process. The number of bytes in this array
% must be at least equal to the number columns times the number of rows
% of the source pixels.
%
*/
static MagickBooleanType DecodeImage(const unsigned char *compressed_pixels,
const size_t length,unsigned char *pixels,size_t maxpixels)
{
register const unsigned char
*l,
*p;
register unsigned char
*q;
ssize_t
count;
unsigned char
byte;
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(compressed_pixels != (unsigned char *) NULL);
assert(pixels != (unsigned char *) NULL);
p=compressed_pixels;
q=pixels;
l=q+maxpixels;
while (((size_t) (p-compressed_pixels) < length) && (q < l))
{
byte=(*p++);
if (byte != 128U)
*q++=byte;
else
{
/*
Runlength-encoded packet: <count><byte>
*/
count=(ssize_t) (*p++);
if (count > 0)
byte=(*p++);
while ((count >= 0) && (q < l))
{
*q++=byte;
count--;
}
}
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d S U N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadSUNImage() reads a SUN 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 ReadSUNImage method is:
%
% Image *ReadSUNImage(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 *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define RMT_EQUAL_RGB 1
#define RMT_NONE 0
#define RMT_RAW 2
#define RT_STANDARD 1
#define RT_ENCODED 2
#define RT_FORMAT_RGB 3
typedef struct _SUNInfo
{
unsigned int
magic,
width,
height,
depth,
length,
type,
maptype,
maplength;
} SUNInfo;
Image
*image;
int
bit;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bytes_per_line,
extent,
length;
ssize_t
count,
y;
SUNInfo
sun_info;
unsigned char
*sun_data,
*sun_pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SUN raster header.
*/
(void) ResetMagickMemory(&sun_info,0,sizeof(sun_info));
sun_info.magic=ReadBlobMSBLong(image);
do
{
/*
Verify SUN identifier.
*/
if (sun_info.magic != 0x59a66a95)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
sun_info.width=ReadBlobMSBLong(image);
sun_info.height=ReadBlobMSBLong(image);
sun_info.depth=ReadBlobMSBLong(image);
sun_info.length=ReadBlobMSBLong(image);
sun_info.type=ReadBlobMSBLong(image);
sun_info.maptype=ReadBlobMSBLong(image);
sun_info.maplength=ReadBlobMSBLong(image);
extent=sun_info.height*sun_info.width;
if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) &&
(sun_info.type != RT_FORMAT_RGB))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.depth == 0) || (sun_info.depth > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) &&
(sun_info.maptype != RMT_RAW))
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
image->columns=sun_info.width;
image->rows=sun_info.height;
image->depth=sun_info.depth <= 8 ? sun_info.depth :
MAGICKCORE_QUANTUM_DEPTH;
if (sun_info.depth < 24)
{
size_t
one;
image->colors=sun_info.maplength;
one=1;
if (sun_info.maptype == RMT_NONE)
image->colors=one << sun_info.depth;
if (sun_info.maptype == RMT_EQUAL_RGB)
image->colors=sun_info.maplength/3;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
switch (sun_info.maptype)
{
case RMT_EQUAL_RGB:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
case RMT_RAW:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,sun_info.maplength,sun_colormap);
if (count != (ssize_t) sun_info.maplength)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
default:
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
}
image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=sun_info.width;
image->rows=sun_info.height;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) !=
sun_info.length || !sun_info.length)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((sun_info.type != RT_ENCODED) && (sun_info.depth >= 8) &&
((number_pixels*((sun_info.depth+7)/8)) > sun_info.length))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bytes_per_line=sun_info.width*sun_info.depth;
sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(
sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data));
if (sun_data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=(ssize_t) ReadBlob(image,sun_info.length,sun_data);
if (count != (ssize_t) sun_info.length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
sun_pixels=sun_data;
bytes_per_line=0;
if (sun_info.type == RT_ENCODED)
{
size_t
height;
/*
Read run-length encoded raster pixels.
*/
height=sun_info.height;
if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) ||
((bytes_per_line/sun_info.depth) != sun_info.width))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
bytes_per_line+=15;
bytes_per_line<<=1;
if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
bytes_per_line>>=4;
sun_pixels=(unsigned char *) AcquireQuantumMemory(height,
bytes_per_line*sizeof(*sun_pixels));
if (sun_pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line*
height);
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
}
/*
Convert SUN raster image to pixel packets.
*/
p=sun_pixels;
if (sun_info.depth == 1)
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-7); x+=8)
{
for (bit=7; bit >= 0; bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),
q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 :
0x01),q);
q+=GetPixelChannels(image);
}
p++;
}
if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (image->storage_class == PseudoClass)
{
if (bytes_per_line == 0)
bytes_per_line=image->columns;
length=image->rows*(image->columns+image->columns % 2);
if (((sun_info.type == RT_ENCODED) &&
(length > (bytes_per_line*image->rows))) ||
((sun_info.type != RT_ENCODED) && (length > sun_info.length)))
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
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++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if ((image->columns % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
size_t
bytes_per_pixel;
bytes_per_pixel=3;
if (image->alpha_trait != UndefinedPixelTrait)
bytes_per_pixel++;
if (bytes_per_line == 0)
bytes_per_line=bytes_per_pixel*image->columns;
length=image->rows*(bytes_per_line+image->columns % 2);
if (((sun_info.type == RT_ENCODED) &&
(length > (bytes_per_line*image->rows))) ||
((sun_info.type != RT_ENCODED) && (length > sun_info.length)))
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
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++)
{
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
if (sun_info.type == RT_STANDARD)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
}
else
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
}
if (image->colors != 0)
{
SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelRed(image,q)].red),q);
SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelGreen(image,q)].green),q);
SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelBlue(image,q)].blue),q);
}
q+=GetPixelChannels(image);
}
if (((bytes_per_pixel*image->columns) % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if (image->storage_class == PseudoClass)
(void) SyncImage(image,exception);
sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
sun_info.magic=ReadBlobMSBLong(image);
if (sun_info.magic == 0x59a66a95)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (sun_info.magic == 0x59a66a95);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r S U N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterSUNImage() adds attributes for the SUN 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 RegisterSUNImage method is:
%
% size_t RegisterSUNImage(void)
%
*/
ModuleExport size_t RegisterSUNImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("RAS");
entry->decoder=(DecodeImageHandler *) ReadSUNImage;
entry->encoder=(EncodeImageHandler *) WriteSUNImage;
entry->magick=(IsImageFormatHandler *) IsSUN;
entry->description=ConstantString("SUN Rasterfile");
entry->module=ConstantString("SUN");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("SUN");
entry->decoder=(DecodeImageHandler *) ReadSUNImage;
entry->encoder=(EncodeImageHandler *) WriteSUNImage;
entry->description=ConstantString("SUN Rasterfile");
entry->module=ConstantString("SUN");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r S U N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterSUNImage() removes format registrations made by the
% SUN module from the list of supported formats.
%
% The format of the UnregisterSUNImage method is:
%
% UnregisterSUNImage(void)
%
*/
ModuleExport void UnregisterSUNImage(void)
{
(void) UnregisterMagickInfo("RAS");
(void) UnregisterMagickInfo("SUN");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e S U N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteSUNImage() writes an image in the SUN rasterfile format.
%
% The format of the WriteSUNImage method is:
%
% MagickBooleanType WriteSUNImage(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 WriteSUNImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
#define RMT_EQUAL_RGB 1
#define RMT_NONE 0
#define RMT_RAW 2
#define RT_STANDARD 1
#define RT_FORMAT_RGB 3
typedef struct _SUNInfo
{
unsigned int
magic,
width,
height,
depth,
length,
type,
maptype,
maplength;
} SUNInfo;
MagickBooleanType
status;
MagickOffsetType
scene;
MagickSizeType
number_pixels;
register const Quantum
*p;
register ssize_t
i,
x;
ssize_t
y;
SUNInfo
sun_info;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
/*
Initialize SUN raster file header.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
sun_info.magic=0x59a66a95;
if ((image->columns != (unsigned int) image->columns) ||
(image->rows != (unsigned int) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
sun_info.width=(unsigned int) image->columns;
sun_info.height=(unsigned int) image->rows;
sun_info.type=(unsigned int)
(image->storage_class == DirectClass ? RT_FORMAT_RGB : RT_STANDARD);
sun_info.maptype=RMT_NONE;
sun_info.maplength=0;
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((4*number_pixels) != (size_t) (4*number_pixels))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (image->storage_class == DirectClass)
{
/*
Full color SUN raster.
*/
sun_info.depth=(unsigned int) image->alpha_trait != UndefinedPixelTrait ?
32U : 24U;
sun_info.length=(unsigned int) ((image->alpha_trait != UndefinedPixelTrait ?
4 : 3)*number_pixels);
sun_info.length+=sun_info.length & 0x01 ? (unsigned int) image->rows :
0;
}
else
if (IsImageMonochrome(image,exception) != MagickFalse)
{
/*
Monochrome SUN raster.
*/
sun_info.depth=1;
sun_info.length=(unsigned int) (((image->columns+7) >> 3)*
image->rows);
sun_info.length+=(unsigned int) (((image->columns/8)+(image->columns %
8 ? 1 : 0)) % 2 ? image->rows : 0);
}
else
{
/*
Colormapped SUN raster.
*/
sun_info.depth=8;
sun_info.length=(unsigned int) number_pixels;
sun_info.length+=(unsigned int) (image->columns & 0x01 ? image->rows :
0);
sun_info.maptype=RMT_EQUAL_RGB;
sun_info.maplength=(unsigned int) (3*image->colors);
}
/*
Write SUN header.
*/
(void) WriteBlobMSBLong(image,sun_info.magic);
(void) WriteBlobMSBLong(image,sun_info.width);
(void) WriteBlobMSBLong(image,sun_info.height);
(void) WriteBlobMSBLong(image,sun_info.depth);
(void) WriteBlobMSBLong(image,sun_info.length);
(void) WriteBlobMSBLong(image,sun_info.type);
(void) WriteBlobMSBLong(image,sun_info.maptype);
(void) WriteBlobMSBLong(image,sun_info.maplength);
/*
Convert MIFF to SUN raster pixels.
*/
x=0;
y=0;
if (image->storage_class == DirectClass)
{
register unsigned char
*q;
size_t
bytes_per_pixel,
length;
unsigned char
*pixels;
/*
Allocate memory for pixels.
*/
bytes_per_pixel=3;
if (image->alpha_trait != UndefinedPixelTrait)
bytes_per_pixel++;
length=image->columns;
pixels=(unsigned char *) AcquireQuantumMemory(length,4*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert DirectClass packet to SUN RGB 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;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->alpha_trait != UndefinedPixelTrait)
*q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
p+=GetPixelChannels(image);
}
if (((bytes_per_pixel*image->columns) & 0x01) != 0)
*q++='\0'; /* pad scanline */
(void) WriteBlob(image,(size_t) (q-pixels),pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
}
else
if (IsImageMonochrome(image,exception) != MagickFalse)
{
register unsigned char
bit,
byte;
/*
Convert PseudoClass image to a SUN monochrome image.
*/
(void) SetImageType(image,BilevelType,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte<<=1;
if (GetPixelLuma(image,p) < (QuantumRange/2.0))
byte|=0x01;
bit++;
if (bit == 8)
{
(void) WriteBlobByte(image,byte);
bit=0;
byte=0;
}
p+=GetPixelChannels(image);
}
if (bit != 0)
(void) WriteBlobByte(image,(unsigned char) (byte << (8-bit)));
if ((((image->columns/8)+
(image->columns % 8 ? 1 : 0)) % 2) != 0)
(void) WriteBlobByte(image,0); /* pad scanline */
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Dump colormap to file.
*/
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
ClampToQuantum(image->colormap[i].red)));
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
ClampToQuantum(image->colormap[i].green)));
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
ClampToQuantum(image->colormap[i].blue)));
/*
Convert PseudoClass packet to SUN colormapped 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;
for (x=0; x < (ssize_t) image->columns; x++)
{
(void) WriteBlobByte(image,(unsigned char)
GetPixelIndex(image,p));
p+=GetPixelChannels(image);
}
if (image->columns & 0x01)
(void) WriteBlobByte(image,0); /* pad scanline */
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1848_3 |
crossvul-cpp_data_bad_5283_3 | /*
+----------------------------------------------------------------------+
| ZIP archive support for Phar |
+----------------------------------------------------------------------+
| Copyright (c) 2007-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Gregory Beaver <cellog@php.net> |
+----------------------------------------------------------------------+
*/
#include "phar_internal.h"
#define PHAR_GET_16(var) ((php_uint16)((((php_uint16)var[0]) & 0xff) | \
(((php_uint16)var[1]) & 0xff) << 8))
#define PHAR_GET_32(var) ((php_uint32)((((php_uint32)var[0]) & 0xff) | \
(((php_uint32)var[1]) & 0xff) << 8 | \
(((php_uint32)var[2]) & 0xff) << 16 | \
(((php_uint32)var[3]) & 0xff) << 24))
static inline void phar_write_32(char buffer[4], php_uint32 value)
{
buffer[3] = (unsigned char) ((value & 0xff000000) >> 24);
buffer[2] = (unsigned char) ((value & 0xff0000) >> 16);
buffer[1] = (unsigned char) ((value & 0xff00) >> 8);
buffer[0] = (unsigned char) (value & 0xff);
}
static inline void phar_write_16(char buffer[2], php_uint32 value)
{
buffer[1] = (unsigned char) ((value & 0xff00) >> 8);
buffer[0] = (unsigned char) (value & 0xff);
}
# define PHAR_SET_32(var, value) phar_write_32(var, (php_uint32) (value));
# define PHAR_SET_16(var, value) phar_write_16(var, (php_uint16) (value));
static int phar_zip_process_extra(php_stream *fp, phar_entry_info *entry, php_uint16 len) /* {{{ */
{
union {
phar_zip_extra_field_header header;
phar_zip_unix3 unix3;
} h;
int read;
do {
if (sizeof(h.header) != php_stream_read(fp, (char *) &h.header, sizeof(h.header))) {
return FAILURE;
}
if (h.header.tag[0] != 'n' || h.header.tag[1] != 'u') {
/* skip to next header */
php_stream_seek(fp, PHAR_GET_16(h.header.size), SEEK_CUR);
len -= PHAR_GET_16(h.header.size) + 4;
continue;
}
/* unix3 header found */
read = php_stream_read(fp, (char *) &(h.unix3.crc32), sizeof(h.unix3) - sizeof(h.header));
len -= read + 4;
if (sizeof(h.unix3) - sizeof(h.header) != read) {
return FAILURE;
}
if (PHAR_GET_16(h.unix3.size) > sizeof(h.unix3) - 4) {
/* skip symlink filename - we may add this support in later */
php_stream_seek(fp, PHAR_GET_16(h.unix3.size) - sizeof(h.unix3.size), SEEK_CUR);
}
/* set permissions */
entry->flags &= PHAR_ENT_COMPRESSION_MASK;
if (entry->is_dir) {
entry->flags |= PHAR_GET_16(h.unix3.perms) & PHAR_ENT_PERM_MASK;
} else {
entry->flags |= PHAR_GET_16(h.unix3.perms) & PHAR_ENT_PERM_MASK;
}
} while (len);
return SUCCESS;
}
/* }}} */
/*
extracted from libzip
zip_dirent.c -- read directory entry (local or central), clean dirent
Copyright (C) 1999, 2003, 2004, 2005 Dieter Baron and Thomas Klausner
This function is part of libzip, a library to manipulate ZIP archives.
The authors can be contacted at <nih@giga.or.at>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The names of the authors may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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.
*/
static time_t phar_zip_d2u_time(char *cdtime, char *cddate) /* {{{ */
{
int dtime = PHAR_GET_16(cdtime), ddate = PHAR_GET_16(cddate);
struct tm *tm, tmbuf;
time_t now;
now = time(NULL);
tm = php_localtime_r(&now, &tmbuf);
tm->tm_year = ((ddate>>9)&127) + 1980 - 1900;
tm->tm_mon = ((ddate>>5)&15) - 1;
tm->tm_mday = ddate&31;
tm->tm_hour = (dtime>>11)&31;
tm->tm_min = (dtime>>5)&63;
tm->tm_sec = (dtime<<1)&62;
return mktime(tm);
}
/* }}} */
static void phar_zip_u2d_time(time_t time, char *dtime, char *ddate) /* {{{ */
{
php_uint16 ctime, cdate;
struct tm *tm, tmbuf;
tm = php_localtime_r(&time, &tmbuf);
cdate = ((tm->tm_year+1900-1980)<<9) + ((tm->tm_mon+1)<<5) + tm->tm_mday;
ctime = ((tm->tm_hour)<<11) + ((tm->tm_min)<<5) + ((tm->tm_sec)>>1);
PHAR_SET_16(dtime, ctime);
PHAR_SET_16(ddate, cdate);
}
/* }}} */
/**
* Does not check for a previously opened phar in the cache.
*
* Parse a new one and add it to the cache, returning either SUCCESS or
* FAILURE, and setting pphar to the pointer to the manifest entry
*
* This is used by phar_open_from_fp to process a zip-based phar, but can be called
* directly.
*/
int phar_parse_zipfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, char **error) /* {{{ */
{
phar_zip_dir_end locator;
char buf[sizeof(locator) + 65536];
zend_long size;
php_uint16 i;
phar_archive_data *mydata = NULL;
phar_entry_info entry = {0};
char *p = buf, *ext, *actual_alias = NULL;
char *metadata = NULL;
size = php_stream_tell(fp);
if (size > sizeof(locator) + 65536) {
/* seek to max comment length + end of central directory record */
size = sizeof(locator) + 65536;
if (FAILURE == php_stream_seek(fp, -size, SEEK_END)) {
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: unable to search for end of central directory in zip-based phar \"%s\"", fname);
}
return FAILURE;
}
} else {
php_stream_seek(fp, 0, SEEK_SET);
}
if (!php_stream_read(fp, buf, size)) {
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: unable to read in data to search for end of central directory in zip-based phar \"%s\"", fname);
}
return FAILURE;
}
while ((p=(char *) memchr(p + 1, 'P', (size_t) (size - (p + 1 - buf)))) != NULL) {
if ((p - buf) + sizeof(locator) <= size && !memcmp(p + 1, "K\5\6", 3)) {
memcpy((void *)&locator, (void *) p, sizeof(locator));
if (PHAR_GET_16(locator.centraldisk) != 0 || PHAR_GET_16(locator.disknumber) != 0) {
/* split archives not handled */
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: split archives spanning multiple zips cannot be processed in zip-based phar \"%s\"", fname);
}
return FAILURE;
}
if (PHAR_GET_16(locator.counthere) != PHAR_GET_16(locator.count)) {
if (error) {
spprintf(error, 4096, "phar error: corrupt zip archive, conflicting file count in end of central directory record in zip-based phar \"%s\"", fname);
}
php_stream_close(fp);
return FAILURE;
}
mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist));
mydata->is_persistent = PHAR_G(persist);
/* read in archive comment, if any */
if (PHAR_GET_16(locator.comment_len)) {
metadata = p + sizeof(locator);
if (PHAR_GET_16(locator.comment_len) != size - (metadata - buf)) {
if (error) {
spprintf(error, 4096, "phar error: corrupt zip archive, zip file comment truncated in zip-based phar \"%s\"", fname);
}
php_stream_close(fp);
pefree(mydata, mydata->is_persistent);
return FAILURE;
}
mydata->metadata_len = PHAR_GET_16(locator.comment_len);
if (phar_parse_metadata(&metadata, &mydata->metadata, PHAR_GET_16(locator.comment_len)) == FAILURE) {
mydata->metadata_len = 0;
/* if not valid serialized data, it is a regular string */
ZVAL_NEW_STR(&mydata->metadata, zend_string_init(metadata, PHAR_GET_16(locator.comment_len), mydata->is_persistent));
}
} else {
ZVAL_UNDEF(&mydata->metadata);
}
goto foundit;
}
}
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: end of central directory not found in zip-based phar \"%s\"", fname);
}
return FAILURE;
foundit:
mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent);
#ifdef PHP_WIN32
phar_unixify_path_separators(mydata->fname, fname_len);
#endif
mydata->is_zip = 1;
mydata->fname_len = fname_len;
ext = strrchr(mydata->fname, '/');
if (ext) {
mydata->ext = memchr(ext, '.', (mydata->fname + fname_len) - ext);
if (mydata->ext == ext) {
mydata->ext = memchr(ext + 1, '.', (mydata->fname + fname_len) - ext - 1);
}
if (mydata->ext) {
mydata->ext_len = (mydata->fname + fname_len) - mydata->ext;
}
}
/* clean up on big-endian systems */
/* seek to central directory */
php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET);
/* read in central directory */
zend_hash_init(&mydata->manifest, PHAR_GET_16(locator.count),
zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent);
zend_hash_init(&mydata->mounted_dirs, 5,
zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent);
zend_hash_init(&mydata->virtual_dirs, PHAR_GET_16(locator.count) * 2,
zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent);
entry.phar = mydata;
entry.is_zip = 1;
entry.fp_type = PHAR_FP;
entry.is_persistent = mydata->is_persistent;
#define PHAR_ZIP_FAIL_FREE(errmsg, save) \
zend_hash_destroy(&mydata->manifest); \
mydata->manifest.u.flags = 0; \
zend_hash_destroy(&mydata->mounted_dirs); \
mydata->mounted_dirs.u.flags = 0; \
zend_hash_destroy(&mydata->virtual_dirs); \
mydata->virtual_dirs.u.flags = 0; \
php_stream_close(fp); \
zval_dtor(&mydata->metadata); \
if (mydata->signature) { \
efree(mydata->signature); \
} \
if (error) { \
spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \
} \
pefree(mydata->fname, mydata->is_persistent); \
if (mydata->alias) { \
pefree(mydata->alias, mydata->is_persistent); \
} \
pefree(mydata, mydata->is_persistent); \
efree(save); \
return FAILURE;
#define PHAR_ZIP_FAIL(errmsg) \
zend_hash_destroy(&mydata->manifest); \
mydata->manifest.u.flags = 0; \
zend_hash_destroy(&mydata->mounted_dirs); \
mydata->mounted_dirs.u.flags = 0; \
zend_hash_destroy(&mydata->virtual_dirs); \
mydata->virtual_dirs.u.flags = 0; \
php_stream_close(fp); \
zval_dtor(&mydata->metadata); \
if (mydata->signature) { \
efree(mydata->signature); \
} \
if (error) { \
spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \
} \
pefree(mydata->fname, mydata->is_persistent); \
if (mydata->alias) { \
pefree(mydata->alias, mydata->is_persistent); \
} \
pefree(mydata, mydata->is_persistent); \
return FAILURE;
/* add each central directory item to the manifest */
for (i = 0; i < PHAR_GET_16(locator.count); ++i) {
phar_zip_central_dir_file zipentry;
zend_off_t beforeus = php_stream_tell(fp);
if (sizeof(zipentry) != php_stream_read(fp, (char *) &zipentry, sizeof(zipentry))) {
PHAR_ZIP_FAIL("unable to read central directory entry, truncated");
}
/* clean up for bigendian systems */
if (memcmp("PK\1\2", zipentry.signature, 4)) {
/* corrupted entry */
PHAR_ZIP_FAIL("corrupted central directory entry, no magic signature");
}
if (entry.is_persistent) {
entry.manifest_pos = i;
}
entry.compressed_filesize = PHAR_GET_32(zipentry.compsize);
entry.uncompressed_filesize = PHAR_GET_32(zipentry.uncompsize);
entry.crc32 = PHAR_GET_32(zipentry.crc32);
/* do not PHAR_GET_16 either on the next line */
entry.timestamp = phar_zip_d2u_time(zipentry.timestamp, zipentry.datestamp);
entry.flags = PHAR_ENT_PERM_DEF_FILE;
entry.header_offset = PHAR_GET_32(zipentry.offset);
entry.offset = entry.offset_abs = PHAR_GET_32(zipentry.offset) + sizeof(phar_zip_file_header) + PHAR_GET_16(zipentry.filename_len) +
PHAR_GET_16(zipentry.extra_len);
if (PHAR_GET_16(zipentry.flags) & PHAR_ZIP_FLAG_ENCRYPTED) {
PHAR_ZIP_FAIL("Cannot process encrypted zip files");
}
if (!PHAR_GET_16(zipentry.filename_len)) {
PHAR_ZIP_FAIL("Cannot process zips created from stdin (zero-length filename)");
}
entry.filename_len = PHAR_GET_16(zipentry.filename_len);
entry.filename = (char *) pemalloc(entry.filename_len + 1, entry.is_persistent);
if (entry.filename_len != php_stream_read(fp, entry.filename, entry.filename_len)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in filename from central directory, truncated");
}
entry.filename[entry.filename_len] = '\0';
if (entry.filename[entry.filename_len - 1] == '/') {
entry.is_dir = 1;
if(entry.filename_len > 1) {
entry.filename_len--;
}
entry.flags |= PHAR_ENT_PERM_DEF_DIR;
} else {
entry.is_dir = 0;
}
if (entry.filename_len == sizeof(".phar/signature.bin")-1 && !strncmp(entry.filename, ".phar/signature.bin", sizeof(".phar/signature.bin")-1)) {
size_t read;
php_stream *sigfile;
zend_off_t now;
char *sig;
now = php_stream_tell(fp);
pefree(entry.filename, entry.is_persistent);
sigfile = php_stream_fopen_tmpfile();
if (!sigfile) {
PHAR_ZIP_FAIL("couldn't open temporary file");
}
php_stream_seek(fp, 0, SEEK_SET);
/* copy file contents + local headers and zip comment, if any, to be hashed for signature */
php_stream_copy_to_stream_ex(fp, sigfile, entry.header_offset, NULL);
/* seek to central directory */
php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET);
/* copy central directory header */
php_stream_copy_to_stream_ex(fp, sigfile, beforeus - PHAR_GET_32(locator.cdir_offset), NULL);
if (metadata) {
php_stream_write(sigfile, metadata, PHAR_GET_16(locator.comment_len));
}
php_stream_seek(fp, sizeof(phar_zip_file_header) + entry.header_offset + entry.filename_len + PHAR_GET_16(zipentry.extra_len), SEEK_SET);
sig = (char *) emalloc(entry.uncompressed_filesize);
read = php_stream_read(fp, sig, entry.uncompressed_filesize);
if (read != entry.uncompressed_filesize) {
php_stream_close(sigfile);
efree(sig);
PHAR_ZIP_FAIL("signature cannot be read");
}
mydata->sig_flags = PHAR_GET_32(sig);
if (FAILURE == phar_verify_signature(sigfile, php_stream_tell(sigfile), mydata->sig_flags, sig + 8, entry.uncompressed_filesize - 8, fname, &mydata->signature, &mydata->sig_len, error)) {
efree(sig);
if (error) {
char *save;
php_stream_close(sigfile);
spprintf(&save, 4096, "signature cannot be verified: %s", *error);
efree(*error);
PHAR_ZIP_FAIL_FREE(save, save);
} else {
php_stream_close(sigfile);
PHAR_ZIP_FAIL("signature cannot be verified");
}
}
php_stream_close(sigfile);
efree(sig);
/* signature checked out, let's ensure this is the last file in the phar */
if (i != PHAR_GET_16(locator.count) - 1) {
PHAR_ZIP_FAIL("entries exist after signature, invalid phar");
}
continue;
}
phar_add_virtual_dirs(mydata, entry.filename, entry.filename_len);
if (PHAR_GET_16(zipentry.extra_len)) {
zend_off_t loc = php_stream_tell(fp);
if (FAILURE == phar_zip_process_extra(fp, &entry, PHAR_GET_16(zipentry.extra_len))) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("Unable to process extra field header for file in central directory");
}
php_stream_seek(fp, loc + PHAR_GET_16(zipentry.extra_len), SEEK_SET);
}
switch (PHAR_GET_16(zipentry.compressed)) {
case PHAR_ZIP_COMP_NONE :
/* compression flag already set */
break;
case PHAR_ZIP_COMP_DEFLATE :
entry.flags |= PHAR_ENT_COMPRESSED_GZ;
if (!PHAR_G(has_zlib)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("zlib extension is required");
}
break;
case PHAR_ZIP_COMP_BZIP2 :
entry.flags |= PHAR_ENT_COMPRESSED_BZ2;
if (!PHAR_G(has_bz2)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("bzip2 extension is required");
}
break;
case 1 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Shrunk) used in this zip");
case 2 :
case 3 :
case 4 :
case 5 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Reduce) used in this zip");
case 6 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Implode) used in this zip");
case 7 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Tokenize) used in this zip");
case 9 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Deflate64) used in this zip");
case 10 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (PKWare Implode/old IBM TERSE) used in this zip");
case 14 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (LZMA) used in this zip");
case 18 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (IBM TERSE) used in this zip");
case 19 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (IBM LZ77) used in this zip");
case 97 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (WavPack) used in this zip");
case 98 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (PPMd) used in this zip");
default :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (unknown) used in this zip");
}
/* get file metadata */
if (PHAR_GET_16(zipentry.comment_len)) {
if (PHAR_GET_16(zipentry.comment_len) != php_stream_read(fp, buf, PHAR_GET_16(zipentry.comment_len))) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in file comment, truncated");
}
p = buf;
entry.metadata_len = PHAR_GET_16(zipentry.comment_len);
if (phar_parse_metadata(&p, &(entry.metadata), PHAR_GET_16(zipentry.comment_len)) == FAILURE) {
entry.metadata_len = 0;
/* if not valid serialized data, it is a regular string */
ZVAL_NEW_STR(&entry.metadata, zend_string_init(buf, PHAR_GET_16(zipentry.comment_len), entry.is_persistent));
}
} else {
ZVAL_UNDEF(&entry.metadata);
}
if (!actual_alias && entry.filename_len == sizeof(".phar/alias.txt")-1 && !strncmp(entry.filename, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
php_stream_filter *filter;
zend_off_t saveloc;
/* verify local file header */
phar_zip_file_header local;
/* archive alias found */
saveloc = php_stream_tell(fp);
php_stream_seek(fp, PHAR_GET_32(zipentry.offset), SEEK_SET);
if (sizeof(local) != php_stream_read(fp, (char *) &local, sizeof(local))) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (cannot read local file header for alias)");
}
/* verify local header */
if (entry.filename_len != PHAR_GET_16(local.filename_len) || entry.crc32 != PHAR_GET_32(local.crc32) || entry.uncompressed_filesize != PHAR_GET_32(local.uncompsize) || entry.compressed_filesize != PHAR_GET_32(local.compsize)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (local header of alias does not match central directory)");
}
/* construct actual offset to file start - local extra_len can be different from central extra_len */
entry.offset = entry.offset_abs =
sizeof(local) + entry.header_offset + PHAR_GET_16(local.filename_len) + PHAR_GET_16(local.extra_len);
php_stream_seek(fp, entry.offset, SEEK_SET);
/* these next lines should be for php < 5.2.6 after 5.3 filters are fixed */
fp->writepos = 0;
fp->readpos = 0;
php_stream_seek(fp, entry.offset, SEEK_SET);
fp->writepos = 0;
fp->readpos = 0;
/* the above lines should be for php < 5.2.6 after 5.3 filters are fixed */
mydata->alias_len = entry.uncompressed_filesize;
if (entry.flags & PHAR_ENT_COMPRESSED_GZ) {
filter = php_stream_filter_create("zlib.inflate", NULL, php_stream_is_persistent(fp));
if (!filter) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to decompress alias, zlib filter creation failed");
}
php_stream_filter_append(&fp->readfilters, filter);
// TODO: refactor to avoid reallocation ???
//??? entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)
{
zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0);
if (str) {
entry.uncompressed_filesize = ZSTR_LEN(str);
actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release(str);
} else {
actual_alias = NULL;
entry.uncompressed_filesize = 0;
}
}
if (!entry.uncompressed_filesize || !actual_alias) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, truncated");
}
php_stream_filter_flush(filter, 1);
php_stream_filter_remove(filter, 1);
} else if (entry.flags & PHAR_ENT_COMPRESSED_BZ2) {
filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp));
if (!filter) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, bzip2 filter creation failed");
}
php_stream_filter_append(&fp->readfilters, filter);
// TODO: refactor to avoid reallocation ???
//??? entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)
{
zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0);
if (str) {
entry.uncompressed_filesize = ZSTR_LEN(str);
actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release(str);
} else {
actual_alias = NULL;
entry.uncompressed_filesize = 0;
}
}
if (!entry.uncompressed_filesize || !actual_alias) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, truncated");
}
php_stream_filter_flush(filter, 1);
php_stream_filter_remove(filter, 1);
} else {
// TODO: refactor to avoid reallocation ???
//??? entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)
{
zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0);
if (str) {
entry.uncompressed_filesize = ZSTR_LEN(str);
actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release(str);
} else {
actual_alias = NULL;
entry.uncompressed_filesize = 0;
}
}
if (!entry.uncompressed_filesize || !actual_alias) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, truncated");
}
}
/* return to central directory parsing */
php_stream_seek(fp, saveloc, SEEK_SET);
}
phar_set_inode(&entry);
zend_hash_str_add_mem(&mydata->manifest, entry.filename, entry.filename_len, (void *)&entry, sizeof(phar_entry_info));
}
mydata->fp = fp;
if (zend_hash_str_exists(&(mydata->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
mydata->is_data = 0;
} else {
mydata->is_data = 1;
}
zend_hash_str_add_ptr(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len, mydata);
if (actual_alias) {
phar_archive_data *fd_ptr;
if (!phar_validate_alias(actual_alias, mydata->alias_len)) {
if (error) {
spprintf(error, 4096, "phar error: invalid alias \"%s\" in zip-based phar \"%s\"", actual_alias, fname);
}
efree(actual_alias);
zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len);
return FAILURE;
}
mydata->is_temporary_alias = 0;
if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len))) {
if (SUCCESS != phar_free_alias(fd_ptr, actual_alias, mydata->alias_len)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with implicit alias, alias is already in use", fname);
}
efree(actual_alias);
zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len);
return FAILURE;
}
}
mydata->alias = entry.is_persistent ? pestrndup(actual_alias, mydata->alias_len, 1) : actual_alias;
if (entry.is_persistent) {
efree(actual_alias);
}
zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata);
} else {
phar_archive_data *fd_ptr;
if (alias_len) {
if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len))) {
if (SUCCESS != phar_free_alias(fd_ptr, alias, alias_len)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with explicit alias, alias is already in use", fname);
}
zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len);
return FAILURE;
}
}
zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata);
mydata->alias = pestrndup(alias, alias_len, mydata->is_persistent);
mydata->alias_len = alias_len;
} else {
mydata->alias = pestrndup(mydata->fname, fname_len, mydata->is_persistent);
mydata->alias_len = fname_len;
}
mydata->is_temporary_alias = 1;
}
if (pphar) {
*pphar = mydata;
}
return SUCCESS;
}
/* }}} */
/**
* Create or open a zip-based phar for writing
*/
int phar_open_or_create_zip(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error) /* {{{ */
{
phar_archive_data *phar;
int ret = phar_create_or_parse_filename(fname, fname_len, alias, alias_len, is_data, options, &phar, error);
if (FAILURE == ret) {
return FAILURE;
}
if (pphar) {
*pphar = phar;
}
phar->is_data = is_data;
if (phar->is_zip) {
return ret;
}
if (phar->is_brandnew) {
phar->internal_file_start = 0;
phar->is_zip = 1;
phar->is_tar = 0;
return SUCCESS;
}
/* we've reached here - the phar exists and is a regular phar */
if (error) {
spprintf(error, 4096, "phar zip error: phar \"%s\" already exists as a regular phar and must be deleted from disk prior to creating as a zip-based phar", fname);
}
return FAILURE;
}
/* }}} */
struct _phar_zip_pass {
php_stream *filefp;
php_stream *centralfp;
php_stream *old;
int free_fp;
int free_ufp;
char **error;
};
/* perform final modification of zip contents for each file in the manifest before saving */
static int phar_zip_changed_apply_int(phar_entry_info *entry, void *arg) /* {{{ */
{
phar_zip_file_header local;
phar_zip_unix3 perms;
phar_zip_central_dir_file central;
struct _phar_zip_pass *p;
php_uint32 newcrc32;
zend_off_t offset;
int not_really_modified = 0;
p = (struct _phar_zip_pass*) arg;
if (entry->is_mounted) {
return ZEND_HASH_APPLY_KEEP;
}
if (entry->is_deleted) {
if (entry->fp_refcount <= 0) {
return ZEND_HASH_APPLY_REMOVE;
} else {
/* we can't delete this in-memory until it is closed */
return ZEND_HASH_APPLY_KEEP;
}
}
phar_add_virtual_dirs(entry->phar, entry->filename, entry->filename_len);
memset(&local, 0, sizeof(local));
memset(¢ral, 0, sizeof(central));
memset(&perms, 0, sizeof(perms));
strncpy(local.signature, "PK\3\4", 4);
strncpy(central.signature, "PK\1\2", 4);
PHAR_SET_16(central.extra_len, sizeof(perms));
PHAR_SET_16(local.extra_len, sizeof(perms));
perms.tag[0] = 'n';
perms.tag[1] = 'u';
PHAR_SET_16(perms.size, sizeof(perms) - 4);
PHAR_SET_16(perms.perms, entry->flags & PHAR_ENT_PERM_MASK);
{
php_uint32 crc = (php_uint32) ~0;
CRC32(crc, perms.perms[0]);
CRC32(crc, perms.perms[1]);
PHAR_SET_32(perms.crc32, ~crc);
}
if (entry->flags & PHAR_ENT_COMPRESSED_GZ) {
PHAR_SET_16(central.compressed, PHAR_ZIP_COMP_DEFLATE);
PHAR_SET_16(local.compressed, PHAR_ZIP_COMP_DEFLATE);
}
if (entry->flags & PHAR_ENT_COMPRESSED_BZ2) {
PHAR_SET_16(central.compressed, PHAR_ZIP_COMP_BZIP2);
PHAR_SET_16(local.compressed, PHAR_ZIP_COMP_BZIP2);
}
/* do not use PHAR_GET_16 on either field of the next line */
phar_zip_u2d_time(entry->timestamp, local.timestamp, local.datestamp);
memcpy(central.timestamp, local.timestamp, sizeof(local.timestamp));
memcpy(central.datestamp, local.datestamp, sizeof(local.datestamp));
PHAR_SET_16(central.filename_len, entry->filename_len + (entry->is_dir ? 1 : 0));
PHAR_SET_16(local.filename_len, entry->filename_len + (entry->is_dir ? 1 : 0));
PHAR_SET_32(central.offset, php_stream_tell(p->filefp));
/* do extra field for perms later */
if (entry->is_modified) {
php_uint32 loc;
php_stream_filter *filter;
php_stream *efp;
if (entry->is_dir) {
entry->is_modified = 0;
if (entry->fp_type == PHAR_MOD && entry->fp != entry->phar->fp && entry->fp != entry->phar->ufp) {
php_stream_close(entry->fp);
entry->fp = NULL;
entry->fp_type = PHAR_FP;
}
goto continue_dir;
}
if (FAILURE == phar_open_entry_fp(entry, p->error, 0)) {
spprintf(p->error, 0, "unable to open file contents of file \"%s\" in zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
/* we can be modified and already be compressed, such as when chmod() is executed */
if (entry->flags & PHAR_ENT_COMPRESSION_MASK && (entry->old_flags == entry->flags || !entry->old_flags)) {
not_really_modified = 1;
goto is_compressed;
}
if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0)) {
spprintf(p->error, 0, "unable to seek to start of file \"%s\" to zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
efp = phar_get_efp(entry, 0);
newcrc32 = ~0;
for (loc = 0;loc < entry->uncompressed_filesize; ++loc) {
CRC32(newcrc32, php_stream_getc(efp));
}
entry->crc32 = ~newcrc32;
PHAR_SET_32(central.uncompsize, entry->uncompressed_filesize);
PHAR_SET_32(local.uncompsize, entry->uncompressed_filesize);
if (!(entry->flags & PHAR_ENT_COMPRESSION_MASK)) {
/* not compressed */
entry->compressed_filesize = entry->uncompressed_filesize;
PHAR_SET_32(central.compsize, entry->uncompressed_filesize);
PHAR_SET_32(local.compsize, entry->uncompressed_filesize);
goto not_compressed;
}
filter = php_stream_filter_create(phar_compress_filter(entry, 0), NULL, 0);
if (!filter) {
if (entry->flags & PHAR_ENT_COMPRESSED_GZ) {
spprintf(p->error, 0, "unable to gzip compress file \"%s\" to zip-based phar \"%s\"", entry->filename, entry->phar->fname);
} else {
spprintf(p->error, 0, "unable to bzip2 compress file \"%s\" to zip-based phar \"%s\"", entry->filename, entry->phar->fname);
}
return ZEND_HASH_APPLY_STOP;
}
/* create new file that holds the compressed version */
/* work around inability to specify freedom in write and strictness
in read count */
entry->cfp = php_stream_fopen_tmpfile();
if (!entry->cfp) {
spprintf(p->error, 0, "unable to create temporary file for file \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
php_stream_flush(efp);
if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0)) {
spprintf(p->error, 0, "unable to seek to start of file \"%s\" to zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
php_stream_filter_append((&entry->cfp->writefilters), filter);
if (SUCCESS != php_stream_copy_to_stream_ex(efp, entry->cfp, entry->uncompressed_filesize, NULL)) {
spprintf(p->error, 0, "unable to copy compressed file contents of file \"%s\" while creating new phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
php_stream_filter_flush(filter, 1);
php_stream_flush(entry->cfp);
php_stream_filter_remove(filter, 1);
php_stream_seek(entry->cfp, 0, SEEK_END);
entry->compressed_filesize = (php_uint32) php_stream_tell(entry->cfp);
PHAR_SET_32(central.compsize, entry->compressed_filesize);
PHAR_SET_32(local.compsize, entry->compressed_filesize);
/* generate crc on compressed file */
php_stream_rewind(entry->cfp);
entry->old_flags = entry->flags;
entry->is_modified = 1;
} else {
is_compressed:
PHAR_SET_32(central.uncompsize, entry->uncompressed_filesize);
PHAR_SET_32(local.uncompsize, entry->uncompressed_filesize);
PHAR_SET_32(central.compsize, entry->compressed_filesize);
PHAR_SET_32(local.compsize, entry->compressed_filesize);
if (p->old) {
if (-1 == php_stream_seek(p->old, entry->offset_abs, SEEK_SET)) {
spprintf(p->error, 0, "unable to seek to start of file \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
}
}
not_compressed:
PHAR_SET_32(central.crc32, entry->crc32);
PHAR_SET_32(local.crc32, entry->crc32);
continue_dir:
/* set file metadata */
if (Z_TYPE(entry->metadata) != IS_UNDEF) {
php_serialize_data_t metadata_hash;
if (entry->metadata_str.s) {
smart_str_free(&entry->metadata_str);
}
entry->metadata_str.s = NULL;
PHP_VAR_SERIALIZE_INIT(metadata_hash);
php_var_serialize(&entry->metadata_str, &entry->metadata, &metadata_hash);
PHP_VAR_SERIALIZE_DESTROY(metadata_hash);
PHAR_SET_16(central.comment_len, ZSTR_LEN(entry->metadata_str.s));
}
entry->header_offset = php_stream_tell(p->filefp);
offset = entry->header_offset + sizeof(local) + entry->filename_len + (entry->is_dir ? 1 : 0) + sizeof(perms);
if (sizeof(local) != php_stream_write(p->filefp, (char *)&local, sizeof(local))) {
spprintf(p->error, 0, "unable to write local file header of file \"%s\" to zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (sizeof(central) != php_stream_write(p->centralfp, (char *)¢ral, sizeof(central))) {
spprintf(p->error, 0, "unable to write central directory entry for file \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (entry->is_dir) {
if (entry->filename_len != php_stream_write(p->filefp, entry->filename, entry->filename_len)) {
spprintf(p->error, 0, "unable to write filename to local directory entry for directory \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (1 != php_stream_write(p->filefp, "/", 1)) {
spprintf(p->error, 0, "unable to write filename to local directory entry for directory \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (entry->filename_len != php_stream_write(p->centralfp, entry->filename, entry->filename_len)) {
spprintf(p->error, 0, "unable to write filename to central directory entry for directory \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (1 != php_stream_write(p->centralfp, "/", 1)) {
spprintf(p->error, 0, "unable to write filename to central directory entry for directory \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
} else {
if (entry->filename_len != php_stream_write(p->filefp, entry->filename, entry->filename_len)) {
spprintf(p->error, 0, "unable to write filename to local directory entry for file \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (entry->filename_len != php_stream_write(p->centralfp, entry->filename, entry->filename_len)) {
spprintf(p->error, 0, "unable to write filename to central directory entry for file \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
}
if (sizeof(perms) != php_stream_write(p->filefp, (char *)&perms, sizeof(perms))) {
spprintf(p->error, 0, "unable to write local extra permissions file header of file \"%s\" to zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (sizeof(perms) != php_stream_write(p->centralfp, (char *)&perms, sizeof(perms))) {
spprintf(p->error, 0, "unable to write central extra permissions file header of file \"%s\" to zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
if (!not_really_modified && entry->is_modified) {
if (entry->cfp) {
if (SUCCESS != php_stream_copy_to_stream_ex(entry->cfp, p->filefp, entry->compressed_filesize, NULL)) {
spprintf(p->error, 0, "unable to write compressed contents of file \"%s\" in zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
php_stream_close(entry->cfp);
entry->cfp = NULL;
} else {
if (FAILURE == phar_open_entry_fp(entry, p->error, 0)) {
return ZEND_HASH_APPLY_STOP;
}
phar_seek_efp(entry, 0, SEEK_SET, 0, 0);
if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(entry, 0), p->filefp, entry->uncompressed_filesize, NULL)) {
spprintf(p->error, 0, "unable to write contents of file \"%s\" in zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
}
if (entry->fp_type == PHAR_MOD && entry->fp != entry->phar->fp && entry->fp != entry->phar->ufp && entry->fp_refcount == 0) {
php_stream_close(entry->fp);
}
entry->is_modified = 0;
} else {
entry->is_modified = 0;
if (entry->fp_refcount) {
/* open file pointers refer to this fp, do not free the stream */
switch (entry->fp_type) {
case PHAR_FP:
p->free_fp = 0;
break;
case PHAR_UFP:
p->free_ufp = 0;
default:
break;
}
}
if (!entry->is_dir && entry->compressed_filesize && SUCCESS != php_stream_copy_to_stream_ex(p->old, p->filefp, entry->compressed_filesize, NULL)) {
spprintf(p->error, 0, "unable to copy contents of file \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
return ZEND_HASH_APPLY_STOP;
}
}
entry->fp = NULL;
entry->offset = entry->offset_abs = offset;
entry->fp_type = PHAR_FP;
if (entry->metadata_str.s) {
if (ZSTR_LEN(entry->metadata_str.s) != php_stream_write(p->centralfp, ZSTR_VAL(entry->metadata_str.s), ZSTR_LEN(entry->metadata_str.s))) {
spprintf(p->error, 0, "unable to write metadata as file comment for file \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
smart_str_free(&entry->metadata_str);
return ZEND_HASH_APPLY_STOP;
}
smart_str_free(&entry->metadata_str);
}
return ZEND_HASH_APPLY_KEEP;
}
/* }}} */
static int phar_zip_changed_apply(zval *zv, void *arg) /* {{{ */
{
return phar_zip_changed_apply_int(Z_PTR_P(zv), arg);
}
/* }}} */
static int phar_zip_applysignature(phar_archive_data *phar, struct _phar_zip_pass *pass,
smart_str *metadata) /* {{{ */
{
/* add signature for executable tars or tars explicitly set with setSignatureAlgorithm */
if (!phar->is_data || phar->sig_flags) {
int signature_length;
char *signature, sigbuf[8];
phar_entry_info entry = {0};
php_stream *newfile;
zend_off_t tell, st;
newfile = php_stream_fopen_tmpfile();
if (newfile == NULL) {
spprintf(pass->error, 0, "phar error: unable to create temporary file for the signature file");
return FAILURE;
}
st = tell = php_stream_tell(pass->filefp);
/* copy the local files, central directory, and the zip comment to generate the hash */
php_stream_seek(pass->filefp, 0, SEEK_SET);
php_stream_copy_to_stream_ex(pass->filefp, newfile, tell, NULL);
tell = php_stream_tell(pass->centralfp);
php_stream_seek(pass->centralfp, 0, SEEK_SET);
php_stream_copy_to_stream_ex(pass->centralfp, newfile, tell, NULL);
if (metadata->s) {
php_stream_write(newfile, ZSTR_VAL(metadata->s), ZSTR_LEN(metadata->s));
}
if (FAILURE == phar_create_signature(phar, newfile, &signature, &signature_length, pass->error)) {
if (pass->error) {
char *save = *(pass->error);
spprintf(pass->error, 0, "phar error: unable to write signature to zip-based phar: %s", save);
efree(save);
}
php_stream_close(newfile);
return FAILURE;
}
entry.filename = ".phar/signature.bin";
entry.filename_len = sizeof(".phar/signature.bin")-1;
entry.fp = php_stream_fopen_tmpfile();
entry.fp_type = PHAR_MOD;
entry.is_modified = 1;
if (entry.fp == NULL) {
spprintf(pass->error, 0, "phar error: unable to create temporary file for signature");
return FAILURE;
}
PHAR_SET_32(sigbuf, phar->sig_flags);
PHAR_SET_32(sigbuf + 4, signature_length);
if (8 != (int)php_stream_write(entry.fp, sigbuf, 8) || signature_length != (int)php_stream_write(entry.fp, signature, signature_length)) {
efree(signature);
if (pass->error) {
spprintf(pass->error, 0, "phar error: unable to write signature to zip-based phar %s", phar->fname);
}
php_stream_close(newfile);
return FAILURE;
}
efree(signature);
entry.uncompressed_filesize = entry.compressed_filesize = signature_length + 8;
entry.phar = phar;
/* throw out return value and write the signature */
phar_zip_changed_apply_int(&entry, (void *)pass);
php_stream_close(newfile);
if (pass->error && *(pass->error)) {
/* error is set by writeheaders */
php_stream_close(newfile);
return FAILURE;
}
} /* signature */
return SUCCESS;
}
/* }}} */
int phar_zip_flush(phar_archive_data *phar, char *user_stub, zend_long len, int defaultstub, char **error) /* {{{ */
{
char *pos;
smart_str main_metadata_str = {0};
static const char newstub[] = "<?php // zip-based phar archive stub file\n__HALT_COMPILER();";
char halt_stub[] = "__HALT_COMPILER();";
char *tmp;
php_stream *stubfile, *oldfile;
php_serialize_data_t metadata_hash;
int free_user_stub, closeoldfile = 0;
phar_entry_info entry = {0};
char *temperr = NULL;
struct _phar_zip_pass pass;
phar_zip_dir_end eocd;
php_uint32 cdir_size, cdir_offset;
pass.error = &temperr;
entry.flags = PHAR_ENT_PERM_DEF_FILE;
entry.timestamp = time(NULL);
entry.is_modified = 1;
entry.is_zip = 1;
entry.phar = phar;
entry.fp_type = PHAR_MOD;
if (phar->is_persistent) {
if (error) {
spprintf(error, 0, "internal error: attempt to flush cached zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
if (phar->is_data) {
goto nostub;
}
/* set alias */
if (!phar->is_temporary_alias && phar->alias_len) {
entry.fp = php_stream_fopen_tmpfile();
if (entry.fp == NULL) {
spprintf(error, 0, "phar error: unable to create temporary file");
return EOF;
}
if (phar->alias_len != (int)php_stream_write(entry.fp, phar->alias, phar->alias_len)) {
if (error) {
spprintf(error, 0, "unable to set alias in zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
entry.uncompressed_filesize = entry.compressed_filesize = phar->alias_len;
entry.filename = estrndup(".phar/alias.txt", sizeof(".phar/alias.txt")-1);
entry.filename_len = sizeof(".phar/alias.txt")-1;
if (NULL == zend_hash_str_update_mem(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info))) {
if (error) {
spprintf(error, 0, "unable to set alias in zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
} else {
zend_hash_str_del(&phar->manifest, ".phar/alias.txt", sizeof(".phar/alias.txt")-1);
}
/* register alias */
if (phar->alias_len) {
if (FAILURE == phar_get_archive(&phar, phar->fname, phar->fname_len, phar->alias, phar->alias_len, error)) {
return EOF;
}
}
/* set stub */
if (user_stub && !defaultstub) {
if (len < 0) {
/* resource passed in */
if (!(php_stream_from_zval_no_verify(stubfile, (zval *)user_stub))) {
if (error) {
spprintf(error, 0, "unable to access resource to copy stub to new zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
if (len == -1) {
len = PHP_STREAM_COPY_ALL;
} else {
len = -len;
}
user_stub = 0;
// TODO: refactor to avoid reallocation ???
//??? len = php_stream_copy_to_mem(stubfile, &user_stub, len, 0)
{
zend_string *str = php_stream_copy_to_mem(stubfile, len, 0);
if (str) {
len = ZSTR_LEN(str);
user_stub = estrndup(ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release(str);
} else {
user_stub = NULL;
len = 0;
}
}
if (!len || !user_stub) {
if (error) {
spprintf(error, 0, "unable to read resource to copy stub to new zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
free_user_stub = 1;
} else {
free_user_stub = 0;
}
tmp = estrndup(user_stub, len);
if ((pos = php_stristr(tmp, halt_stub, len, sizeof(halt_stub) - 1)) == NULL) {
efree(tmp);
if (error) {
spprintf(error, 0, "illegal stub for zip-based phar \"%s\"", phar->fname);
}
if (free_user_stub) {
efree(user_stub);
}
return EOF;
}
pos = user_stub + (pos - tmp);
efree(tmp);
len = pos - user_stub + 18;
entry.fp = php_stream_fopen_tmpfile();
if (entry.fp == NULL) {
spprintf(error, 0, "phar error: unable to create temporary file");
return EOF;
}
entry.uncompressed_filesize = len + 5;
if ((size_t)len != php_stream_write(entry.fp, user_stub, len)
|| 5 != php_stream_write(entry.fp, " ?>\r\n", 5)) {
if (error) {
spprintf(error, 0, "unable to create stub from string in new zip-based phar \"%s\"", phar->fname);
}
if (free_user_stub) {
efree(user_stub);
}
php_stream_close(entry.fp);
return EOF;
}
entry.filename = estrndup(".phar/stub.php", sizeof(".phar/stub.php")-1);
entry.filename_len = sizeof(".phar/stub.php")-1;
if (NULL == zend_hash_str_update_mem(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info))) {
if (free_user_stub) {
efree(user_stub);
}
if (error) {
spprintf(error, 0, "unable to set stub in zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
if (free_user_stub) {
efree(user_stub);
}
} else {
/* Either this is a brand new phar (add the stub), or the default stub is required (overwrite the stub) */
entry.fp = php_stream_fopen_tmpfile();
if (entry.fp == NULL) {
spprintf(error, 0, "phar error: unable to create temporary file");
return EOF;
}
if (sizeof(newstub)-1 != php_stream_write(entry.fp, newstub, sizeof(newstub)-1)) {
php_stream_close(entry.fp);
if (error) {
spprintf(error, 0, "unable to %s stub in%szip-based phar \"%s\", failed", user_stub ? "overwrite" : "create", user_stub ? " " : " new ", phar->fname);
}
return EOF;
}
entry.uncompressed_filesize = entry.compressed_filesize = sizeof(newstub) - 1;
entry.filename = estrndup(".phar/stub.php", sizeof(".phar/stub.php")-1);
entry.filename_len = sizeof(".phar/stub.php")-1;
if (!defaultstub) {
if (!zend_hash_str_exists(&phar->manifest, ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
if (NULL == zend_hash_str_add_mem(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info))) {
php_stream_close(entry.fp);
efree(entry.filename);
if (error) {
spprintf(error, 0, "unable to create stub in zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
} else {
php_stream_close(entry.fp);
efree(entry.filename);
}
} else {
if (NULL == zend_hash_str_update_mem(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info))) {
php_stream_close(entry.fp);
efree(entry.filename);
if (error) {
spprintf(error, 0, "unable to overwrite stub in zip-based phar \"%s\"", phar->fname);
}
return EOF;
}
}
}
nostub:
if (phar->fp && !phar->is_brandnew) {
oldfile = phar->fp;
closeoldfile = 0;
php_stream_rewind(oldfile);
} else {
oldfile = php_stream_open_wrapper(phar->fname, "rb", 0, NULL);
closeoldfile = oldfile != NULL;
}
/* save modified files to the zip */
pass.old = oldfile;
pass.filefp = php_stream_fopen_tmpfile();
if (!pass.filefp) {
fperror:
if (closeoldfile) {
php_stream_close(oldfile);
}
if (error) {
spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to open temporary file", phar->fname);
}
return EOF;
}
pass.centralfp = php_stream_fopen_tmpfile();
if (!pass.centralfp) {
goto fperror;
}
pass.free_fp = pass.free_ufp = 1;
memset(&eocd, 0, sizeof(eocd));
strncpy(eocd.signature, "PK\5\6", 4);
if (!phar->is_data && !phar->sig_flags) {
phar->sig_flags = PHAR_SIG_SHA1;
}
if (phar->sig_flags) {
PHAR_SET_16(eocd.counthere, zend_hash_num_elements(&phar->manifest) + 1);
PHAR_SET_16(eocd.count, zend_hash_num_elements(&phar->manifest) + 1);
} else {
PHAR_SET_16(eocd.counthere, zend_hash_num_elements(&phar->manifest));
PHAR_SET_16(eocd.count, zend_hash_num_elements(&phar->manifest));
}
zend_hash_apply_with_argument(&phar->manifest, phar_zip_changed_apply, (void *) &pass);
if (Z_TYPE(phar->metadata) != IS_UNDEF) {
/* set phar metadata */
PHP_VAR_SERIALIZE_INIT(metadata_hash);
php_var_serialize(&main_metadata_str, &phar->metadata, &metadata_hash);
PHP_VAR_SERIALIZE_DESTROY(metadata_hash);
}
if (temperr) {
if (error) {
spprintf(error, 4096, "phar zip flush of \"%s\" failed: %s", phar->fname, temperr);
}
efree(temperr);
temperror:
php_stream_close(pass.centralfp);
nocentralerror:
if (Z_TYPE(phar->metadata) != IS_UNDEF) {
smart_str_free(&main_metadata_str);
}
php_stream_close(pass.filefp);
if (closeoldfile) {
php_stream_close(oldfile);
}
return EOF;
}
if (FAILURE == phar_zip_applysignature(phar, &pass, &main_metadata_str)) {
goto temperror;
}
/* save zip */
cdir_size = php_stream_tell(pass.centralfp);
cdir_offset = php_stream_tell(pass.filefp);
PHAR_SET_32(eocd.cdir_size, cdir_size);
PHAR_SET_32(eocd.cdir_offset, cdir_offset);
php_stream_seek(pass.centralfp, 0, SEEK_SET);
{
size_t clen;
int ret = php_stream_copy_to_stream_ex(pass.centralfp, pass.filefp, PHP_STREAM_COPY_ALL, &clen);
if (SUCCESS != ret || clen != cdir_size) {
if (error) {
spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write central-directory", phar->fname);
}
goto temperror;
}
}
php_stream_close(pass.centralfp);
if (Z_TYPE(phar->metadata) != IS_UNDEF) {
/* set phar metadata */
PHAR_SET_16(eocd.comment_len, ZSTR_LEN(main_metadata_str.s));
if (sizeof(eocd) != php_stream_write(pass.filefp, (char *)&eocd, sizeof(eocd))) {
if (error) {
spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write end of central-directory", phar->fname);
}
goto nocentralerror;
}
if (ZSTR_LEN(main_metadata_str.s) != php_stream_write(pass.filefp, ZSTR_VAL(main_metadata_str.s), ZSTR_LEN(main_metadata_str.s))) {
if (error) {
spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write metadata to zip comment", phar->fname);
}
goto nocentralerror;
}
smart_str_free(&main_metadata_str);
} else {
if (sizeof(eocd) != php_stream_write(pass.filefp, (char *)&eocd, sizeof(eocd))) {
if (error) {
spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write end of central-directory", phar->fname);
}
goto nocentralerror;
}
}
if (phar->fp && pass.free_fp) {
php_stream_close(phar->fp);
}
if (phar->ufp) {
if (pass.free_ufp) {
php_stream_close(phar->ufp);
}
phar->ufp = NULL;
}
/* re-open */
phar->is_brandnew = 0;
if (phar->donotflush) {
/* deferred flush */
phar->fp = pass.filefp;
} else {
phar->fp = php_stream_open_wrapper(phar->fname, "w+b", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, NULL);
if (!phar->fp) {
if (closeoldfile) {
php_stream_close(oldfile);
}
phar->fp = pass.filefp;
if (error) {
spprintf(error, 4096, "unable to open new phar \"%s\" for writing", phar->fname);
}
return EOF;
}
php_stream_rewind(pass.filefp);
php_stream_copy_to_stream_ex(pass.filefp, phar->fp, PHP_STREAM_COPY_ALL, NULL);
/* we could also reopen the file in "rb" mode but there is no need for that */
php_stream_close(pass.filefp);
}
if (closeoldfile) {
php_stream_close(oldfile);
}
return EOF;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5283_3 |
crossvul-cpp_data_good_5733_10 | /*
* Copyright (c) 2013 Clément Bœsch
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <float.h> /* DBL_MAX */
#include "libavutil/opt.h"
#include "libavutil/eval.h"
#include "libavutil/avassert.h"
#include "libavutil/pixdesc.h"
#include "avfilter.h"
#include "formats.h"
#include "internal.h"
#include "video.h"
static const char *const var_names[] = {
"w", // stream width
"h", // stream height
"n", // frame count
"pts", // presentation timestamp expressed in AV_TIME_BASE units
"r", // frame rate
"t", // timestamp expressed in seconds
"tb", // timebase
NULL
};
enum var_name {
VAR_W,
VAR_H,
VAR_N,
VAR_PTS,
VAR_R,
VAR_T,
VAR_TB,
VAR_NB
};
typedef struct {
const AVClass *class;
const AVPixFmtDescriptor *desc;
int backward;
enum EvalMode { EVAL_MODE_INIT, EVAL_MODE_FRAME, EVAL_MODE_NB } eval_mode;
#define DEF_EXPR_FIELDS(name) AVExpr *name##_pexpr; char *name##_expr; double name
DEF_EXPR_FIELDS(angle);
DEF_EXPR_FIELDS(x0);
DEF_EXPR_FIELDS(y0);
double var_values[VAR_NB];
float *fmap;
int fmap_linesize;
double dmax;
float xscale, yscale;
uint32_t dither;
int do_dither;
AVRational aspect;
AVRational scale;
} VignetteContext;
#define OFFSET(x) offsetof(VignetteContext, x)
#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
static const AVOption vignette_options[] = {
{ "angle", "set lens angle", OFFSET(angle_expr), AV_OPT_TYPE_STRING, {.str="PI/5"}, .flags = FLAGS },
{ "a", "set lens angle", OFFSET(angle_expr), AV_OPT_TYPE_STRING, {.str="PI/5"}, .flags = FLAGS },
{ "x0", "set circle center position on x-axis", OFFSET(x0_expr), AV_OPT_TYPE_STRING, {.str="w/2"}, .flags = FLAGS },
{ "y0", "set circle center position on y-axis", OFFSET(y0_expr), AV_OPT_TYPE_STRING, {.str="h/2"}, .flags = FLAGS },
{ "mode", "set forward/backward mode", OFFSET(backward), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, FLAGS, "mode" },
{ "forward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 0}, INT_MIN, INT_MAX, FLAGS, "mode"},
{ "backward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1}, INT_MIN, INT_MAX, FLAGS, "mode"},
{ "eval", "specify when to evaluate expressions", OFFSET(eval_mode), AV_OPT_TYPE_INT, {.i64 = EVAL_MODE_INIT}, 0, EVAL_MODE_NB-1, FLAGS, "eval" },
{ "init", "eval expressions once during initialization", 0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_INIT}, .flags = FLAGS, .unit = "eval" },
{ "frame", "eval expressions for each frame", 0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_FRAME}, .flags = FLAGS, .unit = "eval" },
{ "dither", "set dithering", OFFSET(do_dither), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, FLAGS },
{ "aspect", "set aspect ratio", OFFSET(aspect), AV_OPT_TYPE_RATIONAL, {.dbl = 1}, 0, DBL_MAX, .flags = FLAGS },
{ NULL }
};
AVFILTER_DEFINE_CLASS(vignette);
static av_cold int init(AVFilterContext *ctx)
{
VignetteContext *s = ctx->priv;
#define PARSE_EXPR(name) do { \
int ret = av_expr_parse(&s->name##_pexpr, s->name##_expr, var_names, \
NULL, NULL, NULL, NULL, 0, ctx); \
if (ret < 0) { \
av_log(ctx, AV_LOG_ERROR, "Unable to parse expression for '" \
AV_STRINGIFY(name) "'\n"); \
return ret; \
} \
} while (0)
PARSE_EXPR(angle);
PARSE_EXPR(x0);
PARSE_EXPR(y0);
return 0;
}
static av_cold void uninit(AVFilterContext *ctx)
{
VignetteContext *s = ctx->priv;
av_freep(&s->fmap);
av_expr_free(s->angle_pexpr);
av_expr_free(s->x0_pexpr);
av_expr_free(s->y0_pexpr);
}
static int query_formats(AVFilterContext *ctx)
{
static const enum AVPixelFormat pix_fmts[] = {
AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV422P,
AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV411P,
AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV440P,
AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
AV_PIX_FMT_GRAY8,
AV_PIX_FMT_NONE
};
ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
return 0;
}
static double get_natural_factor(const VignetteContext *s, int x, int y)
{
const int xx = (x - s->x0) * s->xscale;
const int yy = (y - s->y0) * s->yscale;
const double dnorm = hypot(xx, yy) / s->dmax;
if (dnorm > 1) {
return 0;
} else {
const double c = cos(s->angle * dnorm);
return (c*c)*(c*c); // do not remove braces, it helps compilers
}
}
#define TS2D(ts) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts))
#define TS2T(ts, tb) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts) * av_q2d(tb))
static void update_context(VignetteContext *s, AVFilterLink *inlink, AVFrame *frame)
{
int x, y;
float *dst = s->fmap;
int dst_linesize = s->fmap_linesize;
if (frame) {
s->var_values[VAR_N] = inlink->frame_count;
s->var_values[VAR_T] = TS2T(frame->pts, inlink->time_base);
s->var_values[VAR_PTS] = TS2D(frame->pts);
} else {
s->var_values[VAR_N] = 0;
s->var_values[VAR_T] = NAN;
s->var_values[VAR_PTS] = NAN;
}
s->angle = av_clipf(av_expr_eval(s->angle_pexpr, s->var_values, NULL), 0, M_PI_2);
s->x0 = av_expr_eval(s->x0_pexpr, s->var_values, NULL);
s->y0 = av_expr_eval(s->y0_pexpr, s->var_values, NULL);
if (s->backward) {
for (y = 0; y < inlink->h; y++) {
for (x = 0; x < inlink->w; x++)
dst[x] = 1. / get_natural_factor(s, x, y);
dst += dst_linesize;
}
} else {
for (y = 0; y < inlink->h; y++) {
for (x = 0; x < inlink->w; x++)
dst[x] = get_natural_factor(s, x, y);
dst += dst_linesize;
}
}
}
static inline double get_dither_value(VignetteContext *s)
{
double dv = 0;
if (s->do_dither) {
dv = s->dither / (double)(1LL<<32);
s->dither = s->dither * 1664525 + 1013904223;
}
return dv;
}
static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
unsigned x, y;
AVFilterContext *ctx = inlink->dst;
VignetteContext *s = ctx->priv;
AVFilterLink *outlink = inlink->dst->outputs[0];
AVFrame *out;
out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
if (s->eval_mode == EVAL_MODE_FRAME)
update_context(s, inlink, in);
if (s->desc->flags & AV_PIX_FMT_FLAG_RGB) {
uint8_t *dst = out->data[0];
const uint8_t *src = in ->data[0];
const float *fmap = s->fmap;
const int dst_linesize = out->linesize[0];
const int src_linesize = in ->linesize[0];
const int fmap_linesize = s->fmap_linesize;
for (y = 0; y < inlink->h; y++) {
uint8_t *dstp = dst;
const uint8_t *srcp = src;
for (x = 0; x < inlink->w; x++, dstp += 3, srcp += 3) {
const float f = fmap[x];
dstp[0] = av_clip_uint8(srcp[0] * f + get_dither_value(s));
dstp[1] = av_clip_uint8(srcp[1] * f + get_dither_value(s));
dstp[2] = av_clip_uint8(srcp[2] * f + get_dither_value(s));
}
dst += dst_linesize;
src += src_linesize;
fmap += fmap_linesize;
}
} else {
int plane;
for (plane = 0; plane < 4 && in->data[plane] && in->linesize[plane]; plane++) {
uint8_t *dst = out->data[plane];
const uint8_t *src = in ->data[plane];
const float *fmap = s->fmap;
const int dst_linesize = out->linesize[plane];
const int src_linesize = in ->linesize[plane];
const int fmap_linesize = s->fmap_linesize;
const int chroma = plane == 1 || plane == 2;
const int hsub = chroma ? s->desc->log2_chroma_w : 0;
const int vsub = chroma ? s->desc->log2_chroma_h : 0;
const int w = FF_CEIL_RSHIFT(inlink->w, hsub);
const int h = FF_CEIL_RSHIFT(inlink->h, vsub);
for (y = 0; y < h; y++) {
uint8_t *dstp = dst;
const uint8_t *srcp = src;
for (x = 0; x < w; x++) {
const double dv = get_dither_value(s);
if (chroma) *dstp++ = av_clip_uint8(fmap[x << hsub] * (*srcp++ - 127) + 127 + dv);
else *dstp++ = av_clip_uint8(fmap[x ] * *srcp++ + dv);
}
dst += dst_linesize;
src += src_linesize;
fmap += fmap_linesize << vsub;
}
}
}
return ff_filter_frame(outlink, out);
}
static int config_props(AVFilterLink *inlink)
{
VignetteContext *s = inlink->dst->priv;
AVRational sar = inlink->sample_aspect_ratio;
s->desc = av_pix_fmt_desc_get(inlink->format);
s->var_values[VAR_W] = inlink->w;
s->var_values[VAR_H] = inlink->h;
s->var_values[VAR_TB] = av_q2d(inlink->time_base);
s->var_values[VAR_R] = inlink->frame_rate.num == 0 || inlink->frame_rate.den == 0 ?
NAN : av_q2d(inlink->frame_rate);
if (!sar.num || !sar.den)
sar.num = sar.den = 1;
if (sar.num > sar.den) {
s->xscale = av_q2d(av_div_q(sar, s->aspect));
s->yscale = 1;
} else {
s->yscale = av_q2d(av_div_q(s->aspect, sar));
s->xscale = 1;
}
s->dmax = hypot(inlink->w / 2., inlink->h / 2.);
av_log(s, AV_LOG_DEBUG, "xscale=%f yscale=%f dmax=%f\n",
s->xscale, s->yscale, s->dmax);
s->fmap_linesize = FFALIGN(inlink->w, 32);
s->fmap = av_malloc(s->fmap_linesize * inlink->h * sizeof(*s->fmap));
if (!s->fmap)
return AVERROR(ENOMEM);
if (s->eval_mode == EVAL_MODE_INIT)
update_context(s, inlink, NULL);
return 0;
}
static const AVFilterPad vignette_inputs[] = {
{
.name = "default",
.type = AVMEDIA_TYPE_VIDEO,
.filter_frame = filter_frame,
.config_props = config_props,
},
{ NULL }
};
static const AVFilterPad vignette_outputs[] = {
{
.name = "default",
.type = AVMEDIA_TYPE_VIDEO,
},
{ NULL }
};
AVFilter avfilter_vf_vignette = {
.name = "vignette",
.description = NULL_IF_CONFIG_SMALL("Make or reverse a vignette effect."),
.priv_size = sizeof(VignetteContext),
.init = init,
.uninit = uninit,
.query_formats = query_formats,
.inputs = vignette_inputs,
.outputs = vignette_outputs,
.priv_class = &vignette_class,
.flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5733_10 |
crossvul-cpp_data_good_3522_1 | /*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*/
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/pagemap.h>
#include <linux/uio.h>
#include <linux/blkdev.h>
#include <linux/mm.h>
#include <linux/mount.h>
#include <linux/fs.h>
#include <linux/gfs2_ondisk.h>
#include <linux/ext2_fs.h>
#include <linux/falloc.h>
#include <linux/swap.h>
#include <linux/crc32.h>
#include <linux/writeback.h>
#include <asm/uaccess.h>
#include <linux/dlm.h>
#include <linux/dlm_plock.h>
#include "gfs2.h"
#include "incore.h"
#include "bmap.h"
#include "dir.h"
#include "glock.h"
#include "glops.h"
#include "inode.h"
#include "log.h"
#include "meta_io.h"
#include "quota.h"
#include "rgrp.h"
#include "trans.h"
#include "util.h"
/**
* gfs2_llseek - seek to a location in a file
* @file: the file
* @offset: the offset
* @origin: Where to seek from (SEEK_SET, SEEK_CUR, or SEEK_END)
*
* SEEK_END requires the glock for the file because it references the
* file's size.
*
* Returns: The new offset, or errno
*/
static loff_t gfs2_llseek(struct file *file, loff_t offset, int origin)
{
struct gfs2_inode *ip = GFS2_I(file->f_mapping->host);
struct gfs2_holder i_gh;
loff_t error;
switch (origin) {
case SEEK_END: /* These reference inode->i_size */
case SEEK_DATA:
case SEEK_HOLE:
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY,
&i_gh);
if (!error) {
error = generic_file_llseek_unlocked(file, offset, origin);
gfs2_glock_dq_uninit(&i_gh);
}
break;
case SEEK_CUR:
case SEEK_SET:
error = generic_file_llseek_unlocked(file, offset, origin);
break;
default:
error = -EINVAL;
}
return error;
}
/**
* gfs2_readdir - Read directory entries from a directory
* @file: The directory to read from
* @dirent: Buffer for dirents
* @filldir: Function used to do the copying
*
* Returns: errno
*/
static int gfs2_readdir(struct file *file, void *dirent, filldir_t filldir)
{
struct inode *dir = file->f_mapping->host;
struct gfs2_inode *dip = GFS2_I(dir);
struct gfs2_holder d_gh;
u64 offset = file->f_pos;
int error;
gfs2_holder_init(dip->i_gl, LM_ST_SHARED, 0, &d_gh);
error = gfs2_glock_nq(&d_gh);
if (error) {
gfs2_holder_uninit(&d_gh);
return error;
}
error = gfs2_dir_read(dir, &offset, dirent, filldir);
gfs2_glock_dq_uninit(&d_gh);
file->f_pos = offset;
return error;
}
/**
* fsflags_cvt
* @table: A table of 32 u32 flags
* @val: a 32 bit value to convert
*
* This function can be used to convert between fsflags values and
* GFS2's own flags values.
*
* Returns: the converted flags
*/
static u32 fsflags_cvt(const u32 *table, u32 val)
{
u32 res = 0;
while(val) {
if (val & 1)
res |= *table;
table++;
val >>= 1;
}
return res;
}
static const u32 fsflags_to_gfs2[32] = {
[3] = GFS2_DIF_SYNC,
[4] = GFS2_DIF_IMMUTABLE,
[5] = GFS2_DIF_APPENDONLY,
[7] = GFS2_DIF_NOATIME,
[12] = GFS2_DIF_EXHASH,
[14] = GFS2_DIF_INHERIT_JDATA,
};
static const u32 gfs2_to_fsflags[32] = {
[gfs2fl_Sync] = FS_SYNC_FL,
[gfs2fl_Immutable] = FS_IMMUTABLE_FL,
[gfs2fl_AppendOnly] = FS_APPEND_FL,
[gfs2fl_NoAtime] = FS_NOATIME_FL,
[gfs2fl_ExHash] = FS_INDEX_FL,
[gfs2fl_InheritJdata] = FS_JOURNAL_DATA_FL,
};
static int gfs2_get_flags(struct file *filp, u32 __user *ptr)
{
struct inode *inode = filp->f_path.dentry->d_inode;
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
int error;
u32 fsflags;
gfs2_holder_init(ip->i_gl, LM_ST_SHARED, 0, &gh);
error = gfs2_glock_nq(&gh);
if (error)
return error;
fsflags = fsflags_cvt(gfs2_to_fsflags, ip->i_diskflags);
if (!S_ISDIR(inode->i_mode) && ip->i_diskflags & GFS2_DIF_JDATA)
fsflags |= FS_JOURNAL_DATA_FL;
if (put_user(fsflags, ptr))
error = -EFAULT;
gfs2_glock_dq(&gh);
gfs2_holder_uninit(&gh);
return error;
}
void gfs2_set_inode_flags(struct inode *inode)
{
struct gfs2_inode *ip = GFS2_I(inode);
unsigned int flags = inode->i_flags;
flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_NOSEC);
if ((ip->i_eattr == 0) && !is_sxid(inode->i_mode))
inode->i_flags |= S_NOSEC;
if (ip->i_diskflags & GFS2_DIF_IMMUTABLE)
flags |= S_IMMUTABLE;
if (ip->i_diskflags & GFS2_DIF_APPENDONLY)
flags |= S_APPEND;
if (ip->i_diskflags & GFS2_DIF_NOATIME)
flags |= S_NOATIME;
if (ip->i_diskflags & GFS2_DIF_SYNC)
flags |= S_SYNC;
inode->i_flags = flags;
}
/* Flags that can be set by user space */
#define GFS2_FLAGS_USER_SET (GFS2_DIF_JDATA| \
GFS2_DIF_IMMUTABLE| \
GFS2_DIF_APPENDONLY| \
GFS2_DIF_NOATIME| \
GFS2_DIF_SYNC| \
GFS2_DIF_SYSTEM| \
GFS2_DIF_INHERIT_JDATA)
/**
* gfs2_set_flags - set flags on an inode
* @inode: The inode
* @flags: The flags to set
* @mask: Indicates which flags are valid
*
*/
static int do_gfs2_set_flags(struct file *filp, u32 reqflags, u32 mask)
{
struct inode *inode = filp->f_path.dentry->d_inode;
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct buffer_head *bh;
struct gfs2_holder gh;
int error;
u32 new_flags, flags;
error = mnt_want_write(filp->f_path.mnt);
if (error)
return error;
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &gh);
if (error)
goto out_drop_write;
error = -EACCES;
if (!inode_owner_or_capable(inode))
goto out;
error = 0;
flags = ip->i_diskflags;
new_flags = (flags & ~mask) | (reqflags & mask);
if ((new_flags ^ flags) == 0)
goto out;
error = -EINVAL;
if ((new_flags ^ flags) & ~GFS2_FLAGS_USER_SET)
goto out;
error = -EPERM;
if (IS_IMMUTABLE(inode) && (new_flags & GFS2_DIF_IMMUTABLE))
goto out;
if (IS_APPEND(inode) && (new_flags & GFS2_DIF_APPENDONLY))
goto out;
if (((new_flags ^ flags) & GFS2_DIF_IMMUTABLE) &&
!capable(CAP_LINUX_IMMUTABLE))
goto out;
if (!IS_IMMUTABLE(inode)) {
error = gfs2_permission(inode, MAY_WRITE);
if (error)
goto out;
}
if ((flags ^ new_flags) & GFS2_DIF_JDATA) {
if (flags & GFS2_DIF_JDATA)
gfs2_log_flush(sdp, ip->i_gl);
error = filemap_fdatawrite(inode->i_mapping);
if (error)
goto out;
error = filemap_fdatawait(inode->i_mapping);
if (error)
goto out;
}
error = gfs2_trans_begin(sdp, RES_DINODE, 0);
if (error)
goto out;
error = gfs2_meta_inode_buffer(ip, &bh);
if (error)
goto out_trans_end;
gfs2_trans_add_bh(ip->i_gl, bh, 1);
ip->i_diskflags = new_flags;
gfs2_dinode_out(ip, bh->b_data);
brelse(bh);
gfs2_set_inode_flags(inode);
gfs2_set_aops(inode);
out_trans_end:
gfs2_trans_end(sdp);
out:
gfs2_glock_dq_uninit(&gh);
out_drop_write:
mnt_drop_write(filp->f_path.mnt);
return error;
}
static int gfs2_set_flags(struct file *filp, u32 __user *ptr)
{
struct inode *inode = filp->f_path.dentry->d_inode;
u32 fsflags, gfsflags;
if (get_user(fsflags, ptr))
return -EFAULT;
gfsflags = fsflags_cvt(fsflags_to_gfs2, fsflags);
if (!S_ISDIR(inode->i_mode)) {
if (gfsflags & GFS2_DIF_INHERIT_JDATA)
gfsflags ^= (GFS2_DIF_JDATA | GFS2_DIF_INHERIT_JDATA);
return do_gfs2_set_flags(filp, gfsflags, ~0);
}
return do_gfs2_set_flags(filp, gfsflags, ~GFS2_DIF_JDATA);
}
static long gfs2_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
switch(cmd) {
case FS_IOC_GETFLAGS:
return gfs2_get_flags(filp, (u32 __user *)arg);
case FS_IOC_SETFLAGS:
return gfs2_set_flags(filp, (u32 __user *)arg);
}
return -ENOTTY;
}
/**
* gfs2_allocate_page_backing - Use bmap to allocate blocks
* @page: The (locked) page to allocate backing for
*
* We try to allocate all the blocks required for the page in
* one go. This might fail for various reasons, so we keep
* trying until all the blocks to back this page are allocated.
* If some of the blocks are already allocated, thats ok too.
*/
static int gfs2_allocate_page_backing(struct page *page)
{
struct inode *inode = page->mapping->host;
struct buffer_head bh;
unsigned long size = PAGE_CACHE_SIZE;
u64 lblock = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
do {
bh.b_state = 0;
bh.b_size = size;
gfs2_block_map(inode, lblock, &bh, 1);
if (!buffer_mapped(&bh))
return -EIO;
size -= bh.b_size;
lblock += (bh.b_size >> inode->i_blkbits);
} while(size > 0);
return 0;
}
/**
* gfs2_page_mkwrite - Make a shared, mmap()ed, page writable
* @vma: The virtual memory area
* @page: The page which is about to become writable
*
* When the page becomes writable, we need to ensure that we have
* blocks allocated on disk to back that page.
*/
static int gfs2_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct page *page = vmf->page;
struct inode *inode = vma->vm_file->f_path.dentry->d_inode;
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
unsigned long last_index;
u64 pos = page->index << PAGE_CACHE_SHIFT;
unsigned int data_blocks, ind_blocks, rblocks;
struct gfs2_holder gh;
struct gfs2_alloc *al;
loff_t size;
int ret;
/* Wait if fs is frozen. This is racy so we check again later on
* and retry if the fs has been frozen after the page lock has
* been acquired
*/
vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &gh);
ret = gfs2_glock_nq(&gh);
if (ret)
goto out;
set_bit(GLF_DIRTY, &ip->i_gl->gl_flags);
set_bit(GIF_SW_PAGED, &ip->i_flags);
if (!gfs2_write_alloc_required(ip, pos, PAGE_CACHE_SIZE)) {
lock_page(page);
if (!PageUptodate(page) || page->mapping != inode->i_mapping) {
ret = -EAGAIN;
unlock_page(page);
}
goto out_unlock;
}
ret = -ENOMEM;
al = gfs2_alloc_get(ip);
if (al == NULL)
goto out_unlock;
ret = gfs2_quota_lock_check(ip);
if (ret)
goto out_alloc_put;
gfs2_write_calc_reserv(ip, PAGE_CACHE_SIZE, &data_blocks, &ind_blocks);
al->al_requested = data_blocks + ind_blocks;
ret = gfs2_inplace_reserve(ip);
if (ret)
goto out_quota_unlock;
rblocks = RES_DINODE + ind_blocks;
if (gfs2_is_jdata(ip))
rblocks += data_blocks ? data_blocks : 1;
if (ind_blocks || data_blocks) {
rblocks += RES_STATFS + RES_QUOTA;
rblocks += gfs2_rg_blocks(ip);
}
ret = gfs2_trans_begin(sdp, rblocks, 0);
if (ret)
goto out_trans_fail;
lock_page(page);
ret = -EINVAL;
size = i_size_read(inode);
last_index = (size - 1) >> PAGE_CACHE_SHIFT;
/* Check page index against inode size */
if (size == 0 || (page->index > last_index))
goto out_trans_end;
ret = -EAGAIN;
/* If truncated, we must retry the operation, we may have raced
* with the glock demotion code.
*/
if (!PageUptodate(page) || page->mapping != inode->i_mapping)
goto out_trans_end;
/* Unstuff, if required, and allocate backing blocks for page */
ret = 0;
if (gfs2_is_stuffed(ip))
ret = gfs2_unstuff_dinode(ip, page);
if (ret == 0)
ret = gfs2_allocate_page_backing(page);
out_trans_end:
if (ret)
unlock_page(page);
gfs2_trans_end(sdp);
out_trans_fail:
gfs2_inplace_release(ip);
out_quota_unlock:
gfs2_quota_unlock(ip);
out_alloc_put:
gfs2_alloc_put(ip);
out_unlock:
gfs2_glock_dq(&gh);
out:
gfs2_holder_uninit(&gh);
if (ret == 0) {
set_page_dirty(page);
/* This check must be post dropping of transaction lock */
if (inode->i_sb->s_frozen == SB_UNFROZEN) {
wait_on_page_writeback(page);
} else {
ret = -EAGAIN;
unlock_page(page);
}
}
return block_page_mkwrite_return(ret);
}
static const struct vm_operations_struct gfs2_vm_ops = {
.fault = filemap_fault,
.page_mkwrite = gfs2_page_mkwrite,
};
/**
* gfs2_mmap -
* @file: The file to map
* @vma: The VMA which described the mapping
*
* There is no need to get a lock here unless we should be updating
* atime. We ignore any locking errors since the only consequence is
* a missed atime update (which will just be deferred until later).
*
* Returns: 0
*/
static int gfs2_mmap(struct file *file, struct vm_area_struct *vma)
{
struct gfs2_inode *ip = GFS2_I(file->f_mapping->host);
if (!(file->f_flags & O_NOATIME) &&
!IS_NOATIME(&ip->i_inode)) {
struct gfs2_holder i_gh;
int error;
gfs2_holder_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY, &i_gh);
error = gfs2_glock_nq(&i_gh);
if (error == 0) {
file_accessed(file);
gfs2_glock_dq(&i_gh);
}
gfs2_holder_uninit(&i_gh);
if (error)
return error;
}
vma->vm_ops = &gfs2_vm_ops;
vma->vm_flags |= VM_CAN_NONLINEAR;
return 0;
}
/**
* gfs2_open - open a file
* @inode: the inode to open
* @file: the struct file for this opening
*
* Returns: errno
*/
static int gfs2_open(struct inode *inode, struct file *file)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder i_gh;
struct gfs2_file *fp;
int error;
fp = kzalloc(sizeof(struct gfs2_file), GFP_KERNEL);
if (!fp)
return -ENOMEM;
mutex_init(&fp->f_fl_mutex);
gfs2_assert_warn(GFS2_SB(inode), !file->private_data);
file->private_data = fp;
if (S_ISREG(ip->i_inode.i_mode)) {
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY,
&i_gh);
if (error)
goto fail;
if (!(file->f_flags & O_LARGEFILE) &&
i_size_read(inode) > MAX_NON_LFS) {
error = -EOVERFLOW;
goto fail_gunlock;
}
gfs2_glock_dq_uninit(&i_gh);
}
return 0;
fail_gunlock:
gfs2_glock_dq_uninit(&i_gh);
fail:
file->private_data = NULL;
kfree(fp);
return error;
}
/**
* gfs2_close - called to close a struct file
* @inode: the inode the struct file belongs to
* @file: the struct file being closed
*
* Returns: errno
*/
static int gfs2_close(struct inode *inode, struct file *file)
{
struct gfs2_sbd *sdp = inode->i_sb->s_fs_info;
struct gfs2_file *fp;
fp = file->private_data;
file->private_data = NULL;
if (gfs2_assert_warn(sdp, fp))
return -EIO;
kfree(fp);
return 0;
}
/**
* gfs2_fsync - sync the dirty data for a file (across the cluster)
* @file: the file that points to the dentry
* @start: the start position in the file to sync
* @end: the end position in the file to sync
* @datasync: set if we can ignore timestamp changes
*
* We split the data flushing here so that we don't wait for the data
* until after we've also sent the metadata to disk. Note that for
* data=ordered, we will write & wait for the data at the log flush
* stage anyway, so this is unlikely to make much of a difference
* except in the data=writeback case.
*
* If the fdatawrite fails due to any reason except -EIO, we will
* continue the remainder of the fsync, although we'll still report
* the error at the end. This is to match filemap_write_and_wait_range()
* behaviour.
*
* Returns: errno
*/
static int gfs2_fsync(struct file *file, loff_t start, loff_t end,
int datasync)
{
struct address_space *mapping = file->f_mapping;
struct inode *inode = mapping->host;
int sync_state = inode->i_state & (I_DIRTY_SYNC|I_DIRTY_DATASYNC);
struct gfs2_inode *ip = GFS2_I(inode);
int ret, ret1 = 0;
if (mapping->nrpages) {
ret1 = filemap_fdatawrite_range(mapping, start, end);
if (ret1 == -EIO)
return ret1;
}
if (datasync)
sync_state &= ~I_DIRTY_SYNC;
if (sync_state) {
ret = sync_inode_metadata(inode, 1);
if (ret)
return ret;
if (gfs2_is_jdata(ip))
filemap_write_and_wait(mapping);
gfs2_ail_flush(ip->i_gl, 1);
}
if (mapping->nrpages)
ret = filemap_fdatawait_range(mapping, start, end);
return ret ? ret : ret1;
}
/**
* gfs2_file_aio_write - Perform a write to a file
* @iocb: The io context
* @iov: The data to write
* @nr_segs: Number of @iov segments
* @pos: The file position
*
* We have to do a lock/unlock here to refresh the inode size for
* O_APPEND writes, otherwise we can land up writing at the wrong
* offset. There is still a race, but provided the app is using its
* own file locking, this will make O_APPEND work as expected.
*
*/
static ssize_t gfs2_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos)
{
struct file *file = iocb->ki_filp;
if (file->f_flags & O_APPEND) {
struct dentry *dentry = file->f_dentry;
struct gfs2_inode *ip = GFS2_I(dentry->d_inode);
struct gfs2_holder gh;
int ret;
ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, 0, &gh);
if (ret)
return ret;
gfs2_glock_dq_uninit(&gh);
}
return generic_file_aio_write(iocb, iov, nr_segs, pos);
}
static int fallocate_chunk(struct inode *inode, loff_t offset, loff_t len,
int mode)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct buffer_head *dibh;
int error;
unsigned int nr_blks;
sector_t lblock = offset >> inode->i_blkbits;
error = gfs2_meta_inode_buffer(ip, &dibh);
if (unlikely(error))
return error;
gfs2_trans_add_bh(ip->i_gl, dibh, 1);
if (gfs2_is_stuffed(ip)) {
error = gfs2_unstuff_dinode(ip, NULL);
if (unlikely(error))
goto out;
}
while (len) {
struct buffer_head bh_map = { .b_state = 0, .b_blocknr = 0 };
bh_map.b_size = len;
set_buffer_zeronew(&bh_map);
error = gfs2_block_map(inode, lblock, &bh_map, 1);
if (unlikely(error))
goto out;
len -= bh_map.b_size;
nr_blks = bh_map.b_size >> inode->i_blkbits;
lblock += nr_blks;
if (!buffer_new(&bh_map))
continue;
if (unlikely(!buffer_zeronew(&bh_map))) {
error = -EIO;
goto out;
}
}
if (offset + len > inode->i_size && !(mode & FALLOC_FL_KEEP_SIZE))
i_size_write(inode, offset + len);
mark_inode_dirty(inode);
out:
brelse(dibh);
return error;
}
static void calc_max_reserv(struct gfs2_inode *ip, loff_t max, loff_t *len,
unsigned int *data_blocks, unsigned int *ind_blocks)
{
const struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
unsigned int max_blocks = ip->i_rgd->rd_free_clone;
unsigned int tmp, max_data = max_blocks - 3 * (sdp->sd_max_height - 1);
for (tmp = max_data; tmp > sdp->sd_diptrs;) {
tmp = DIV_ROUND_UP(tmp, sdp->sd_inptrs);
max_data -= tmp;
}
/* This calculation isn't the exact reverse of gfs2_write_calc_reserve,
so it might end up with fewer data blocks */
if (max_data <= *data_blocks)
return;
*data_blocks = max_data;
*ind_blocks = max_blocks - max_data;
*len = ((loff_t)max_data - 3) << sdp->sd_sb.sb_bsize_shift;
if (*len > max) {
*len = max;
gfs2_write_calc_reserv(ip, max, data_blocks, ind_blocks);
}
}
static long gfs2_fallocate(struct file *file, int mode, loff_t offset,
loff_t len)
{
struct inode *inode = file->f_path.dentry->d_inode;
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_inode *ip = GFS2_I(inode);
unsigned int data_blocks = 0, ind_blocks = 0, rblocks;
loff_t bytes, max_bytes;
struct gfs2_alloc *al;
int error;
loff_t bsize_mask = ~((loff_t)sdp->sd_sb.sb_bsize - 1);
loff_t next = (offset + len - 1) >> sdp->sd_sb.sb_bsize_shift;
loff_t max_chunk_size = UINT_MAX & bsize_mask;
next = (next + 1) << sdp->sd_sb.sb_bsize_shift;
/* We only support the FALLOC_FL_KEEP_SIZE mode */
if (mode & ~FALLOC_FL_KEEP_SIZE)
return -EOPNOTSUPP;
offset &= bsize_mask;
len = next - offset;
bytes = sdp->sd_max_rg_data * sdp->sd_sb.sb_bsize / 2;
if (!bytes)
bytes = UINT_MAX;
bytes &= bsize_mask;
if (bytes == 0)
bytes = sdp->sd_sb.sb_bsize;
gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &ip->i_gh);
error = gfs2_glock_nq(&ip->i_gh);
if (unlikely(error))
goto out_uninit;
if (!gfs2_write_alloc_required(ip, offset, len))
goto out_unlock;
while (len > 0) {
if (len < bytes)
bytes = len;
al = gfs2_alloc_get(ip);
if (!al) {
error = -ENOMEM;
goto out_unlock;
}
error = gfs2_quota_lock_check(ip);
if (error)
goto out_alloc_put;
retry:
gfs2_write_calc_reserv(ip, bytes, &data_blocks, &ind_blocks);
al->al_requested = data_blocks + ind_blocks;
error = gfs2_inplace_reserve(ip);
if (error) {
if (error == -ENOSPC && bytes > sdp->sd_sb.sb_bsize) {
bytes >>= 1;
bytes &= bsize_mask;
if (bytes == 0)
bytes = sdp->sd_sb.sb_bsize;
goto retry;
}
goto out_qunlock;
}
max_bytes = bytes;
calc_max_reserv(ip, (len > max_chunk_size)? max_chunk_size: len,
&max_bytes, &data_blocks, &ind_blocks);
al->al_requested = data_blocks + ind_blocks;
rblocks = RES_DINODE + ind_blocks + RES_STATFS + RES_QUOTA +
RES_RG_HDR + gfs2_rg_blocks(ip);
if (gfs2_is_jdata(ip))
rblocks += data_blocks ? data_blocks : 1;
error = gfs2_trans_begin(sdp, rblocks,
PAGE_CACHE_SIZE/sdp->sd_sb.sb_bsize);
if (error)
goto out_trans_fail;
error = fallocate_chunk(inode, offset, max_bytes, mode);
gfs2_trans_end(sdp);
if (error)
goto out_trans_fail;
len -= max_bytes;
offset += max_bytes;
gfs2_inplace_release(ip);
gfs2_quota_unlock(ip);
gfs2_alloc_put(ip);
}
goto out_unlock;
out_trans_fail:
gfs2_inplace_release(ip);
out_qunlock:
gfs2_quota_unlock(ip);
out_alloc_put:
gfs2_alloc_put(ip);
out_unlock:
gfs2_glock_dq(&ip->i_gh);
out_uninit:
gfs2_holder_uninit(&ip->i_gh);
return error;
}
#ifdef CONFIG_GFS2_FS_LOCKING_DLM
/**
* gfs2_setlease - acquire/release a file lease
* @file: the file pointer
* @arg: lease type
* @fl: file lock
*
* We don't currently have a way to enforce a lease across the whole
* cluster; until we do, disable leases (by just returning -EINVAL),
* unless the administrator has requested purely local locking.
*
* Locking: called under lock_flocks
*
* Returns: errno
*/
static int gfs2_setlease(struct file *file, long arg, struct file_lock **fl)
{
return -EINVAL;
}
/**
* gfs2_lock - acquire/release a posix lock on a file
* @file: the file pointer
* @cmd: either modify or retrieve lock state, possibly wait
* @fl: type and range of lock
*
* Returns: errno
*/
static int gfs2_lock(struct file *file, int cmd, struct file_lock *fl)
{
struct gfs2_inode *ip = GFS2_I(file->f_mapping->host);
struct gfs2_sbd *sdp = GFS2_SB(file->f_mapping->host);
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
if (!(fl->fl_flags & FL_POSIX))
return -ENOLCK;
if (__mandatory_lock(&ip->i_inode) && fl->fl_type != F_UNLCK)
return -ENOLCK;
if (cmd == F_CANCELLK) {
/* Hack: */
cmd = F_SETLK;
fl->fl_type = F_UNLCK;
}
if (unlikely(test_bit(SDF_SHUTDOWN, &sdp->sd_flags)))
return -EIO;
if (IS_GETLK(cmd))
return dlm_posix_get(ls->ls_dlm, ip->i_no_addr, file, fl);
else if (fl->fl_type == F_UNLCK)
return dlm_posix_unlock(ls->ls_dlm, ip->i_no_addr, file, fl);
else
return dlm_posix_lock(ls->ls_dlm, ip->i_no_addr, file, cmd, fl);
}
static int do_flock(struct file *file, int cmd, struct file_lock *fl)
{
struct gfs2_file *fp = file->private_data;
struct gfs2_holder *fl_gh = &fp->f_fl_gh;
struct gfs2_inode *ip = GFS2_I(file->f_path.dentry->d_inode);
struct gfs2_glock *gl;
unsigned int state;
int flags;
int error = 0;
state = (fl->fl_type == F_WRLCK) ? LM_ST_EXCLUSIVE : LM_ST_SHARED;
flags = (IS_SETLKW(cmd) ? 0 : LM_FLAG_TRY) | GL_EXACT | GL_NOCACHE;
mutex_lock(&fp->f_fl_mutex);
gl = fl_gh->gh_gl;
if (gl) {
if (fl_gh->gh_state == state)
goto out;
flock_lock_file_wait(file,
&(struct file_lock){.fl_type = F_UNLCK});
gfs2_glock_dq_wait(fl_gh);
gfs2_holder_reinit(state, flags, fl_gh);
} else {
error = gfs2_glock_get(GFS2_SB(&ip->i_inode), ip->i_no_addr,
&gfs2_flock_glops, CREATE, &gl);
if (error)
goto out;
gfs2_holder_init(gl, state, flags, fl_gh);
gfs2_glock_put(gl);
}
error = gfs2_glock_nq(fl_gh);
if (error) {
gfs2_holder_uninit(fl_gh);
if (error == GLR_TRYFAILED)
error = -EAGAIN;
} else {
error = flock_lock_file_wait(file, fl);
gfs2_assert_warn(GFS2_SB(&ip->i_inode), !error);
}
out:
mutex_unlock(&fp->f_fl_mutex);
return error;
}
static void do_unflock(struct file *file, struct file_lock *fl)
{
struct gfs2_file *fp = file->private_data;
struct gfs2_holder *fl_gh = &fp->f_fl_gh;
mutex_lock(&fp->f_fl_mutex);
flock_lock_file_wait(file, fl);
if (fl_gh->gh_gl) {
gfs2_glock_dq_wait(fl_gh);
gfs2_holder_uninit(fl_gh);
}
mutex_unlock(&fp->f_fl_mutex);
}
/**
* gfs2_flock - acquire/release a flock lock on a file
* @file: the file pointer
* @cmd: either modify or retrieve lock state, possibly wait
* @fl: type and range of lock
*
* Returns: errno
*/
static int gfs2_flock(struct file *file, int cmd, struct file_lock *fl)
{
if (!(fl->fl_flags & FL_FLOCK))
return -ENOLCK;
if (fl->fl_type & LOCK_MAND)
return -EOPNOTSUPP;
if (fl->fl_type == F_UNLCK) {
do_unflock(file, fl);
return 0;
} else {
return do_flock(file, cmd, fl);
}
}
const struct file_operations gfs2_file_fops = {
.llseek = gfs2_llseek,
.read = do_sync_read,
.aio_read = generic_file_aio_read,
.write = do_sync_write,
.aio_write = gfs2_file_aio_write,
.unlocked_ioctl = gfs2_ioctl,
.mmap = gfs2_mmap,
.open = gfs2_open,
.release = gfs2_close,
.fsync = gfs2_fsync,
.lock = gfs2_lock,
.flock = gfs2_flock,
.splice_read = generic_file_splice_read,
.splice_write = generic_file_splice_write,
.setlease = gfs2_setlease,
.fallocate = gfs2_fallocate,
};
const struct file_operations gfs2_dir_fops = {
.readdir = gfs2_readdir,
.unlocked_ioctl = gfs2_ioctl,
.open = gfs2_open,
.release = gfs2_close,
.fsync = gfs2_fsync,
.lock = gfs2_lock,
.flock = gfs2_flock,
.llseek = default_llseek,
};
#endif /* CONFIG_GFS2_FS_LOCKING_DLM */
const struct file_operations gfs2_file_fops_nolock = {
.llseek = gfs2_llseek,
.read = do_sync_read,
.aio_read = generic_file_aio_read,
.write = do_sync_write,
.aio_write = gfs2_file_aio_write,
.unlocked_ioctl = gfs2_ioctl,
.mmap = gfs2_mmap,
.open = gfs2_open,
.release = gfs2_close,
.fsync = gfs2_fsync,
.splice_read = generic_file_splice_read,
.splice_write = generic_file_splice_write,
.setlease = generic_setlease,
.fallocate = gfs2_fallocate,
};
const struct file_operations gfs2_dir_fops_nolock = {
.readdir = gfs2_readdir,
.unlocked_ioctl = gfs2_ioctl,
.open = gfs2_open,
.release = gfs2_close,
.fsync = gfs2_fsync,
.llseek = default_llseek,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3522_1 |
crossvul-cpp_data_good_3163_0 | /* radare - LGPL - Copyright 2016 - Oscar Salvador */
#include <r_types.h>
#include <r_util.h>
#include <r_lib.h>
#include <r_bin.h>
#include <r_io.h>
#include "bflt/bflt.h"
static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loaddr, Sdb *sdb) {
if (!buf || !sz || sz == UT64_MAX) {
return NULL;
}
RBuffer *tbuf = r_buf_new ();
if (!tbuf) {
return NULL;
}
r_buf_set_bytes (tbuf, buf, sz);
struct r_bin_bflt_obj *res = r_bin_bflt_new_buf (tbuf);
r_buf_free (tbuf);
return res ? res : NULL;
}
static int load(RBinFile *arch) {
const ut8 *bytes = r_buf_buffer (arch->buf);
ut64 sz = r_buf_size (arch->buf);
arch->o->bin_obj = load_bytes (arch, bytes, sz, arch->o->loadaddr, arch->sdb);
return arch->o->bin_obj ? true : false;
}
static RList *entries(RBinFile *arch) {
struct r_bin_bflt_obj *obj = (struct r_bin_bflt_obj*)arch->o->bin_obj;
RList *ret;
RBinAddr *ptr;
if (!(ret = r_list_newf (free))) {
return NULL;
}
ptr = r_bflt_get_entry (obj);
if (!ptr) {
return NULL;
}
r_list_append (ret, ptr);
return ret;
}
static void __patch_reloc(RBuffer *buf, ut32 addr_to_patch, ut32 data_offset) {
ut8 val[4] = { 0 };
r_write_le32 (val, data_offset);
r_buf_write_at (buf, addr_to_patch, (void *)val, sizeof (val));
}
static int search_old_relocation (struct reloc_struct_t *reloc_table,
ut32 addr_to_patch, int n_reloc) {
int i;
for (i = 0; i < n_reloc; i++) {
if (addr_to_patch == reloc_table[i].data_offset) {
return i;
}
}
return -1;
}
static RList *patch_relocs(RBin *b) {
struct r_bin_bflt_obj *bin = NULL;
RList *list = NULL;
RBinObject *obj;
int i = 0;
if (!b || !b->iob.io || !b->iob.io->desc) {
return NULL;
}
if (!b->iob.io->cached) {
eprintf (
"Warning: please run r2 with -e io.cache=true to patch "
"relocations\n");
return list;
}
obj = r_bin_cur_object (b);
if (!obj) {
return NULL;
}
bin = obj->bin_obj;
list = r_list_newf ((RListFree)free);
if (!list) {
return NULL;
}
if (bin->got_table) {
struct reloc_struct_t *got_table = bin->got_table;
for (i = 0; i < bin->n_got; i++) {
__patch_reloc (bin->b, got_table[i].addr_to_patch,
got_table[i].data_offset);
RBinReloc *reloc = R_NEW0 (RBinReloc);
if (reloc) {
reloc->type = R_BIN_RELOC_32;
reloc->paddr = got_table[i].addr_to_patch;
reloc->vaddr = reloc->paddr;
r_list_append (list, reloc);
}
}
R_FREE (bin->got_table);
}
if (bin->reloc_table) {
struct reloc_struct_t *reloc_table = bin->reloc_table;
for (i = 0; i < bin->hdr->reloc_count; i++) {
int found = search_old_relocation (reloc_table,
reloc_table[i].addr_to_patch,
bin->hdr->reloc_count);
if (found != -1) {
__patch_reloc (bin->b, reloc_table[found].addr_to_patch,
reloc_table[i].data_offset);
} else {
__patch_reloc (bin->b, reloc_table[i].addr_to_patch,
reloc_table[i].data_offset);
}
RBinReloc *reloc = R_NEW0 (RBinReloc);
if (reloc) {
reloc->type = R_BIN_RELOC_32;
reloc->paddr = reloc_table[i].addr_to_patch;
reloc->vaddr = reloc->paddr;
r_list_append (list, reloc);
}
}
R_FREE (bin->reloc_table);
}
b->iob.write_at (b->iob.io, bin->b->base, bin->b->buf, bin->b->length);
return list;
}
static int get_ngot_entries(struct r_bin_bflt_obj *obj) {
ut32 data_size = obj->hdr->data_end - obj->hdr->data_start;
int i = 0, n_got = 0;
if (data_size > obj->size) {
return 0;
}
for (i = 0, n_got = 0; i < data_size ; i+= 4, n_got++) {
ut32 entry, offset = obj->hdr->data_start;
if (offset + i + sizeof (ut32) > obj->size ||
offset + i + sizeof (ut32) < offset) {
return 0;
}
int len = r_buf_read_at (obj->b, offset + i, (ut8 *)&entry,
sizeof (ut32));
if (len != sizeof (ut32)) {
return 0;
}
if (!VALID_GOT_ENTRY (entry)) {
break;
}
}
return n_got;
}
static RList *relocs(RBinFile *arch) {
struct r_bin_bflt_obj *obj = (struct r_bin_bflt_obj*)arch->o->bin_obj;
RList *list = r_list_newf ((RListFree)free);
int i, len, n_got, amount;
if (!list || !obj) {
r_list_free (list);
return NULL;
}
if (obj->hdr->flags & FLAT_FLAG_GOTPIC) {
n_got = get_ngot_entries (obj);
if (n_got) {
amount = n_got * sizeof (ut32);
if (amount < n_got || amount > UT32_MAX) {
goto out_error;
}
struct reloc_struct_t *got_table = calloc (
1, n_got * sizeof (struct reloc_struct_t));
if (got_table) {
ut32 offset = 0;
for (i = 0; i < n_got ; offset += 4, i++) {
ut32 got_entry;
if (obj->hdr->data_start + offset + 4 > obj->size ||
obj->hdr->data_start + offset + 4 < offset) {
break;
}
len = r_buf_read_at (obj->b, obj->hdr->data_start + offset,
(ut8 *)&got_entry, sizeof (ut32));
if (!VALID_GOT_ENTRY (got_entry) || len != sizeof (ut32)) {
break;
}
got_table[i].addr_to_patch = got_entry;
got_table[i].data_offset = got_entry + BFLT_HDR_SIZE;
}
obj->n_got = n_got;
obj->got_table = got_table;
}
}
}
if (obj->hdr->reloc_count > 0) {
int n_reloc = obj->hdr->reloc_count;
amount = n_reloc * sizeof (struct reloc_struct_t);
if (amount < n_reloc || amount > UT32_MAX) {
goto out_error;
}
struct reloc_struct_t *reloc_table = calloc (1, amount + 1);
if (!reloc_table) {
goto out_error;
}
amount = n_reloc * sizeof (ut32);
if (amount < n_reloc || amount > UT32_MAX) {
free (reloc_table);
goto out_error;
}
ut32 *reloc_pointer_table = calloc (1, amount + 1);
if (!reloc_pointer_table) {
free (reloc_table);
goto out_error;
}
if (obj->hdr->reloc_start + amount > obj->size ||
obj->hdr->reloc_start + amount < amount) {
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
len = r_buf_read_at (obj->b, obj->hdr->reloc_start,
(ut8 *)reloc_pointer_table, amount);
if (len != amount) {
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
for (i = 0; i < obj->hdr->reloc_count; i++) {
//XXX it doesn't take endian as consideration when swapping
ut32 reloc_offset =
r_swap_ut32 (reloc_pointer_table[i]) +
BFLT_HDR_SIZE;
if (reloc_offset < obj->hdr->bss_end && reloc_offset < obj->size) {
ut32 reloc_fixed, reloc_data_offset;
if (reloc_offset + sizeof (ut32) > obj->size ||
reloc_offset + sizeof (ut32) < reloc_offset) {
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
len = r_buf_read_at (obj->b, reloc_offset,
(ut8 *)&reloc_fixed,
sizeof (ut32));
if (len != sizeof (ut32)) {
eprintf ("problem while reading relocation entries\n");
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
reloc_data_offset = r_swap_ut32 (reloc_fixed) + BFLT_HDR_SIZE;
reloc_table[i].addr_to_patch = reloc_offset;
reloc_table[i].data_offset = reloc_data_offset;
RBinReloc *reloc = R_NEW0 (RBinReloc);
if (reloc) {
reloc->type = R_BIN_RELOC_32;
reloc->paddr = reloc_table[i].addr_to_patch;
reloc->vaddr = reloc->paddr;
r_list_append (list, reloc);
}
}
}
free (reloc_pointer_table);
obj->reloc_table = reloc_table;
}
return list;
out_error:
r_list_free (list);
return NULL;
}
static RBinInfo *info(RBinFile *arch) {
struct r_bin_bflt_obj *obj = NULL;
RBinInfo *info = NULL;
if (!arch || !arch->o || !arch->o->bin_obj) {
return NULL;
}
obj = (struct r_bin_bflt_obj*)arch->o->bin_obj;
if (!(info = R_NEW0 (RBinInfo))) {
return NULL;
}
info->file = arch->file ? strdup (arch->file) : NULL;
info->rclass = strdup ("bflt");
info->bclass = strdup ("bflt" );
info->type = strdup ("bFLT (Executable file)");
info->os = strdup ("Linux");
info->subsystem = strdup ("Linux");
info->arch = strdup ("arm");
info->big_endian = obj->endian;
info->bits = 32;
info->has_va = false;
info->dbg_info = 0;
info->machine = strdup ("unknown");
return info;
}
static int check_bytes(const ut8 *buf, ut64 length) {
return length > 4 && !memcmp (buf, "bFLT", 4);
}
static int check(RBinFile *arch) {
const ut8 *bytes = arch ? r_buf_buffer (arch->buf) : NULL;
ut64 sz = arch ? r_buf_size (arch->buf): 0;
if (!bytes || !sz) {
return false;
}
return check_bytes (bytes, sz);
}
static int destroy(RBinFile *arch) {
r_bin_bflt_free ((struct r_bin_bflt_obj*)arch->o->bin_obj);
return true;
}
RBinPlugin r_bin_plugin_bflt = {
.name = "bflt",
.desc = "bFLT format r_bin plugin",
.license = "LGPL3",
.load = &load,
.load_bytes = &load_bytes,
.destroy = &destroy,
.check = &check,
.check_bytes = &check_bytes,
.entries = &entries,
.info = &info,
.relocs = &relocs,
.patch_relocs = &patch_relocs,
};
#ifndef CORELIB
RLibStruct radare_plugin = {
.type = R_LIB_TYPE_BIN,
.data = &r_bin_plugin_bflt,
.version = R2_VERSION
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3163_0 |
crossvul-cpp_data_bad_3312_0 | /* DVB USB compliant linux driver for Conexant USB reference design.
*
* The Conexant reference design I saw on their website was only for analogue
* capturing (using the cx25842). The box I took to write this driver (reverse
* engineered) is the one labeled Medion MD95700. In addition to the cx25842
* for analogue capturing it also has a cx22702 DVB-T demodulator on the main
* board. Besides it has a atiremote (X10) and a USB2.0 hub onboard.
*
* Maybe it is a little bit premature to call this driver cxusb, but I assume
* the USB protocol is identical or at least inherited from the reference
* design, so it can be reused for the "analogue-only" device (if it will
* appear at all).
*
* TODO: Use the cx25840-driver for the analogue part
*
* Copyright (C) 2005 Patrick Boettcher (patrick.boettcher@posteo.de)
* Copyright (C) 2006 Michael Krufky (mkrufky@linuxtv.org)
* Copyright (C) 2006, 2007 Chris Pascoe (c.pascoe@itee.uq.edu.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, version 2.
*
* see Documentation/dvb/README.dvb-usb for more information
*/
#include <media/tuner.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include "cxusb.h"
#include "cx22702.h"
#include "lgdt330x.h"
#include "mt352.h"
#include "mt352_priv.h"
#include "zl10353.h"
#include "tuner-xc2028.h"
#include "tuner-simple.h"
#include "mxl5005s.h"
#include "max2165.h"
#include "dib7000p.h"
#include "dib0070.h"
#include "lgs8gxx.h"
#include "atbm8830.h"
#include "si2168.h"
#include "si2157.h"
/* debug */
static int dvb_usb_cxusb_debug;
module_param_named(debug, dvb_usb_cxusb_debug, int, 0644);
MODULE_PARM_DESC(debug, "set debugging level (1=rc (or-able))." DVB_USB_DEBUG_STATUS);
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
#define deb_info(args...) dprintk(dvb_usb_cxusb_debug, 0x03, args)
#define deb_i2c(args...) dprintk(dvb_usb_cxusb_debug, 0x02, args)
static int cxusb_ctrl_msg(struct dvb_usb_device *d,
u8 cmd, u8 *wbuf, int wlen, u8 *rbuf, int rlen)
{
struct cxusb_state *st = d->priv;
int ret, wo;
if (1 + wlen > MAX_XFER_SIZE) {
warn("i2c wr: len=%d is too big!\n", wlen);
return -EOPNOTSUPP;
}
wo = (rbuf == NULL || rlen == 0); /* write-only */
mutex_lock(&d->data_mutex);
st->data[0] = cmd;
memcpy(&st->data[1], wbuf, wlen);
if (wo)
ret = dvb_usb_generic_write(d, st->data, 1 + wlen);
else
ret = dvb_usb_generic_rw(d, st->data, 1 + wlen,
rbuf, rlen, 0);
mutex_unlock(&d->data_mutex);
return ret;
}
/* GPIO */
static void cxusb_gpio_tuner(struct dvb_usb_device *d, int onoff)
{
struct cxusb_state *st = d->priv;
u8 o[2], i;
if (st->gpio_write_state[GPIO_TUNER] == onoff)
return;
o[0] = GPIO_TUNER;
o[1] = onoff;
cxusb_ctrl_msg(d, CMD_GPIO_WRITE, o, 2, &i, 1);
if (i != 0x01)
deb_info("gpio_write failed.\n");
st->gpio_write_state[GPIO_TUNER] = onoff;
}
static int cxusb_bluebird_gpio_rw(struct dvb_usb_device *d, u8 changemask,
u8 newval)
{
u8 o[2], gpio_state;
int rc;
o[0] = 0xff & ~changemask; /* mask of bits to keep */
o[1] = newval & changemask; /* new values for bits */
rc = cxusb_ctrl_msg(d, CMD_BLUEBIRD_GPIO_RW, o, 2, &gpio_state, 1);
if (rc < 0 || (gpio_state & changemask) != (newval & changemask))
deb_info("bluebird_gpio_write failed.\n");
return rc < 0 ? rc : gpio_state;
}
static void cxusb_bluebird_gpio_pulse(struct dvb_usb_device *d, u8 pin, int low)
{
cxusb_bluebird_gpio_rw(d, pin, low ? 0 : pin);
msleep(5);
cxusb_bluebird_gpio_rw(d, pin, low ? pin : 0);
}
static void cxusb_nano2_led(struct dvb_usb_device *d, int onoff)
{
cxusb_bluebird_gpio_rw(d, 0x40, onoff ? 0 : 0x40);
}
static int cxusb_d680_dmb_gpio_tuner(struct dvb_usb_device *d,
u8 addr, int onoff)
{
u8 o[2] = {addr, onoff};
u8 i;
int rc;
rc = cxusb_ctrl_msg(d, CMD_GPIO_WRITE, o, 2, &i, 1);
if (rc < 0)
return rc;
if (i == 0x01)
return 0;
else {
deb_info("gpio_write failed.\n");
return -EIO;
}
}
/* I2C */
static int cxusb_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msg[],
int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adap);
int ret;
int i;
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
return -EAGAIN;
for (i = 0; i < num; i++) {
if (le16_to_cpu(d->udev->descriptor.idVendor) == USB_VID_MEDION)
switch (msg[i].addr) {
case 0x63:
cxusb_gpio_tuner(d, 0);
break;
default:
cxusb_gpio_tuner(d, 1);
break;
}
if (msg[i].flags & I2C_M_RD) {
/* read only */
u8 obuf[3], ibuf[MAX_XFER_SIZE];
if (1 + msg[i].len > sizeof(ibuf)) {
warn("i2c rd: len=%d is too big!\n",
msg[i].len);
ret = -EOPNOTSUPP;
goto unlock;
}
obuf[0] = 0;
obuf[1] = msg[i].len;
obuf[2] = msg[i].addr;
if (cxusb_ctrl_msg(d, CMD_I2C_READ,
obuf, 3,
ibuf, 1+msg[i].len) < 0) {
warn("i2c read failed");
break;
}
memcpy(msg[i].buf, &ibuf[1], msg[i].len);
} else if (i+1 < num && (msg[i+1].flags & I2C_M_RD) &&
msg[i].addr == msg[i+1].addr) {
/* write to then read from same address */
u8 obuf[MAX_XFER_SIZE], ibuf[MAX_XFER_SIZE];
if (3 + msg[i].len > sizeof(obuf)) {
warn("i2c wr: len=%d is too big!\n",
msg[i].len);
ret = -EOPNOTSUPP;
goto unlock;
}
if (1 + msg[i + 1].len > sizeof(ibuf)) {
warn("i2c rd: len=%d is too big!\n",
msg[i + 1].len);
ret = -EOPNOTSUPP;
goto unlock;
}
obuf[0] = msg[i].len;
obuf[1] = msg[i+1].len;
obuf[2] = msg[i].addr;
memcpy(&obuf[3], msg[i].buf, msg[i].len);
if (cxusb_ctrl_msg(d, CMD_I2C_READ,
obuf, 3+msg[i].len,
ibuf, 1+msg[i+1].len) < 0)
break;
if (ibuf[0] != 0x08)
deb_i2c("i2c read may have failed\n");
memcpy(msg[i+1].buf, &ibuf[1], msg[i+1].len);
i++;
} else {
/* write only */
u8 obuf[MAX_XFER_SIZE], ibuf;
if (2 + msg[i].len > sizeof(obuf)) {
warn("i2c wr: len=%d is too big!\n",
msg[i].len);
ret = -EOPNOTSUPP;
goto unlock;
}
obuf[0] = msg[i].addr;
obuf[1] = msg[i].len;
memcpy(&obuf[2], msg[i].buf, msg[i].len);
if (cxusb_ctrl_msg(d, CMD_I2C_WRITE, obuf,
2+msg[i].len, &ibuf,1) < 0)
break;
if (ibuf != 0x08)
deb_i2c("i2c write may have failed\n");
}
}
if (i == num)
ret = num;
else
ret = -EREMOTEIO;
unlock:
mutex_unlock(&d->i2c_mutex);
return ret;
}
static u32 cxusb_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
static struct i2c_algorithm cxusb_i2c_algo = {
.master_xfer = cxusb_i2c_xfer,
.functionality = cxusb_i2c_func,
};
static int cxusb_power_ctrl(struct dvb_usb_device *d, int onoff)
{
u8 b = 0;
if (onoff)
return cxusb_ctrl_msg(d, CMD_POWER_ON, &b, 1, NULL, 0);
else
return cxusb_ctrl_msg(d, CMD_POWER_OFF, &b, 1, NULL, 0);
}
static int cxusb_aver_power_ctrl(struct dvb_usb_device *d, int onoff)
{
int ret;
if (!onoff)
return cxusb_ctrl_msg(d, CMD_POWER_OFF, NULL, 0, NULL, 0);
if (d->state == DVB_USB_STATE_INIT &&
usb_set_interface(d->udev, 0, 0) < 0)
err("set interface failed");
do {} while (!(ret = cxusb_ctrl_msg(d, CMD_POWER_ON, NULL, 0, NULL, 0)) &&
!(ret = cxusb_ctrl_msg(d, 0x15, NULL, 0, NULL, 0)) &&
!(ret = cxusb_ctrl_msg(d, 0x17, NULL, 0, NULL, 0)) && 0);
if (!ret) {
/* FIXME: We don't know why, but we need to configure the
* lgdt3303 with the register settings below on resume */
int i;
u8 buf, bufs[] = {
0x0e, 0x2, 0x00, 0x7f,
0x0e, 0x2, 0x02, 0xfe,
0x0e, 0x2, 0x02, 0x01,
0x0e, 0x2, 0x00, 0x03,
0x0e, 0x2, 0x0d, 0x40,
0x0e, 0x2, 0x0e, 0x87,
0x0e, 0x2, 0x0f, 0x8e,
0x0e, 0x2, 0x10, 0x01,
0x0e, 0x2, 0x14, 0xd7,
0x0e, 0x2, 0x47, 0x88,
};
msleep(20);
for (i = 0; i < sizeof(bufs)/sizeof(u8); i += 4/sizeof(u8)) {
ret = cxusb_ctrl_msg(d, CMD_I2C_WRITE,
bufs+i, 4, &buf, 1);
if (ret)
break;
if (buf != 0x8)
return -EREMOTEIO;
}
}
return ret;
}
static int cxusb_bluebird_power_ctrl(struct dvb_usb_device *d, int onoff)
{
u8 b = 0;
if (onoff)
return cxusb_ctrl_msg(d, CMD_POWER_ON, &b, 1, NULL, 0);
else
return 0;
}
static int cxusb_nano2_power_ctrl(struct dvb_usb_device *d, int onoff)
{
int rc = 0;
rc = cxusb_power_ctrl(d, onoff);
if (!onoff)
cxusb_nano2_led(d, 0);
return rc;
}
static int cxusb_d680_dmb_power_ctrl(struct dvb_usb_device *d, int onoff)
{
int ret;
u8 b;
ret = cxusb_power_ctrl(d, onoff);
if (!onoff)
return ret;
msleep(128);
cxusb_ctrl_msg(d, CMD_DIGITAL, NULL, 0, &b, 1);
msleep(100);
return ret;
}
static int cxusb_streaming_ctrl(struct dvb_usb_adapter *adap, int onoff)
{
u8 buf[2] = { 0x03, 0x00 };
if (onoff)
cxusb_ctrl_msg(adap->dev, CMD_STREAMING_ON, buf, 2, NULL, 0);
else
cxusb_ctrl_msg(adap->dev, CMD_STREAMING_OFF, NULL, 0, NULL, 0);
return 0;
}
static int cxusb_aver_streaming_ctrl(struct dvb_usb_adapter *adap, int onoff)
{
if (onoff)
cxusb_ctrl_msg(adap->dev, CMD_AVER_STREAM_ON, NULL, 0, NULL, 0);
else
cxusb_ctrl_msg(adap->dev, CMD_AVER_STREAM_OFF,
NULL, 0, NULL, 0);
return 0;
}
static int cxusb_read_status(struct dvb_frontend *fe,
enum fe_status *status)
{
struct dvb_usb_adapter *adap = (struct dvb_usb_adapter *)fe->dvb->priv;
struct cxusb_state *state = (struct cxusb_state *)adap->dev->priv;
int ret;
ret = state->fe_read_status(fe, status);
/* it need resync slave fifo when signal change from unlock to lock.*/
if ((*status & FE_HAS_LOCK) && (!state->last_lock)) {
mutex_lock(&state->stream_mutex);
cxusb_streaming_ctrl(adap, 1);
mutex_unlock(&state->stream_mutex);
}
state->last_lock = (*status & FE_HAS_LOCK) ? 1 : 0;
return ret;
}
static void cxusb_d680_dmb_drain_message(struct dvb_usb_device *d)
{
int ep = d->props.generic_bulk_ctrl_endpoint;
const int timeout = 100;
const int junk_len = 32;
u8 *junk;
int rd_count;
/* Discard remaining data in video pipe */
junk = kmalloc(junk_len, GFP_KERNEL);
if (!junk)
return;
while (1) {
if (usb_bulk_msg(d->udev,
usb_rcvbulkpipe(d->udev, ep),
junk, junk_len, &rd_count, timeout) < 0)
break;
if (!rd_count)
break;
}
kfree(junk);
}
static void cxusb_d680_dmb_drain_video(struct dvb_usb_device *d)
{
struct usb_data_stream_properties *p = &d->props.adapter[0].fe[0].stream;
const int timeout = 100;
const int junk_len = p->u.bulk.buffersize;
u8 *junk;
int rd_count;
/* Discard remaining data in video pipe */
junk = kmalloc(junk_len, GFP_KERNEL);
if (!junk)
return;
while (1) {
if (usb_bulk_msg(d->udev,
usb_rcvbulkpipe(d->udev, p->endpoint),
junk, junk_len, &rd_count, timeout) < 0)
break;
if (!rd_count)
break;
}
kfree(junk);
}
static int cxusb_d680_dmb_streaming_ctrl(
struct dvb_usb_adapter *adap, int onoff)
{
if (onoff) {
u8 buf[2] = { 0x03, 0x00 };
cxusb_d680_dmb_drain_video(adap->dev);
return cxusb_ctrl_msg(adap->dev, CMD_STREAMING_ON,
buf, sizeof(buf), NULL, 0);
} else {
int ret = cxusb_ctrl_msg(adap->dev,
CMD_STREAMING_OFF, NULL, 0, NULL, 0);
return ret;
}
}
static int cxusb_rc_query(struct dvb_usb_device *d)
{
u8 ircode[4];
cxusb_ctrl_msg(d, CMD_GET_IR_CODE, NULL, 0, ircode, 4);
if (ircode[2] || ircode[3])
rc_keydown(d->rc_dev, RC_TYPE_UNKNOWN,
RC_SCANCODE_RC5(ircode[2], ircode[3]), 0);
return 0;
}
static int cxusb_bluebird2_rc_query(struct dvb_usb_device *d)
{
u8 ircode[4];
struct i2c_msg msg = { .addr = 0x6b, .flags = I2C_M_RD,
.buf = ircode, .len = 4 };
if (cxusb_i2c_xfer(&d->i2c_adap, &msg, 1) != 1)
return 0;
if (ircode[1] || ircode[2])
rc_keydown(d->rc_dev, RC_TYPE_UNKNOWN,
RC_SCANCODE_RC5(ircode[1], ircode[2]), 0);
return 0;
}
static int cxusb_d680_dmb_rc_query(struct dvb_usb_device *d)
{
u8 ircode[2];
if (cxusb_ctrl_msg(d, 0x10, NULL, 0, ircode, 2) < 0)
return 0;
if (ircode[0] || ircode[1])
rc_keydown(d->rc_dev, RC_TYPE_UNKNOWN,
RC_SCANCODE_RC5(ircode[0], ircode[1]), 0);
return 0;
}
static int cxusb_dee1601_demod_init(struct dvb_frontend* fe)
{
static u8 clock_config [] = { CLOCK_CTL, 0x38, 0x28 };
static u8 reset [] = { RESET, 0x80 };
static u8 adc_ctl_1_cfg [] = { ADC_CTL_1, 0x40 };
static u8 agc_cfg [] = { AGC_TARGET, 0x28, 0x20 };
static u8 gpp_ctl_cfg [] = { GPP_CTL, 0x33 };
static u8 capt_range_cfg[] = { CAPT_RANGE, 0x32 };
mt352_write(fe, clock_config, sizeof(clock_config));
udelay(200);
mt352_write(fe, reset, sizeof(reset));
mt352_write(fe, adc_ctl_1_cfg, sizeof(adc_ctl_1_cfg));
mt352_write(fe, agc_cfg, sizeof(agc_cfg));
mt352_write(fe, gpp_ctl_cfg, sizeof(gpp_ctl_cfg));
mt352_write(fe, capt_range_cfg, sizeof(capt_range_cfg));
return 0;
}
static int cxusb_mt352_demod_init(struct dvb_frontend* fe)
{ /* used in both lgz201 and th7579 */
static u8 clock_config [] = { CLOCK_CTL, 0x38, 0x29 };
static u8 reset [] = { RESET, 0x80 };
static u8 adc_ctl_1_cfg [] = { ADC_CTL_1, 0x40 };
static u8 agc_cfg [] = { AGC_TARGET, 0x24, 0x20 };
static u8 gpp_ctl_cfg [] = { GPP_CTL, 0x33 };
static u8 capt_range_cfg[] = { CAPT_RANGE, 0x32 };
mt352_write(fe, clock_config, sizeof(clock_config));
udelay(200);
mt352_write(fe, reset, sizeof(reset));
mt352_write(fe, adc_ctl_1_cfg, sizeof(adc_ctl_1_cfg));
mt352_write(fe, agc_cfg, sizeof(agc_cfg));
mt352_write(fe, gpp_ctl_cfg, sizeof(gpp_ctl_cfg));
mt352_write(fe, capt_range_cfg, sizeof(capt_range_cfg));
return 0;
}
static struct cx22702_config cxusb_cx22702_config = {
.demod_address = 0x63,
.output_mode = CX22702_PARALLEL_OUTPUT,
};
static struct lgdt330x_config cxusb_lgdt3303_config = {
.demod_address = 0x0e,
.demod_chip = LGDT3303,
};
static struct lgdt330x_config cxusb_aver_lgdt3303_config = {
.demod_address = 0x0e,
.demod_chip = LGDT3303,
.clock_polarity_flip = 2,
};
static struct mt352_config cxusb_dee1601_config = {
.demod_address = 0x0f,
.demod_init = cxusb_dee1601_demod_init,
};
static struct zl10353_config cxusb_zl10353_dee1601_config = {
.demod_address = 0x0f,
.parallel_ts = 1,
};
static struct mt352_config cxusb_mt352_config = {
/* used in both lgz201 and th7579 */
.demod_address = 0x0f,
.demod_init = cxusb_mt352_demod_init,
};
static struct zl10353_config cxusb_zl10353_xc3028_config = {
.demod_address = 0x0f,
.if2 = 45600,
.no_tuner = 1,
.parallel_ts = 1,
};
static struct zl10353_config cxusb_zl10353_xc3028_config_no_i2c_gate = {
.demod_address = 0x0f,
.if2 = 45600,
.no_tuner = 1,
.parallel_ts = 1,
.disable_i2c_gate_ctrl = 1,
};
static struct mt352_config cxusb_mt352_xc3028_config = {
.demod_address = 0x0f,
.if2 = 4560,
.no_tuner = 1,
.demod_init = cxusb_mt352_demod_init,
};
/* FIXME: needs tweaking */
static struct mxl5005s_config aver_a868r_tuner = {
.i2c_address = 0x63,
.if_freq = 6000000UL,
.xtal_freq = CRYSTAL_FREQ_16000000HZ,
.agc_mode = MXL_SINGLE_AGC,
.tracking_filter = MXL_TF_C,
.rssi_enable = MXL_RSSI_ENABLE,
.cap_select = MXL_CAP_SEL_ENABLE,
.div_out = MXL_DIV_OUT_4,
.clock_out = MXL_CLOCK_OUT_DISABLE,
.output_load = MXL5005S_IF_OUTPUT_LOAD_200_OHM,
.top = MXL5005S_TOP_25P2,
.mod_mode = MXL_DIGITAL_MODE,
.if_mode = MXL_ZERO_IF,
.AgcMasterByte = 0x00,
};
/* FIXME: needs tweaking */
static struct mxl5005s_config d680_dmb_tuner = {
.i2c_address = 0x63,
.if_freq = 36125000UL,
.xtal_freq = CRYSTAL_FREQ_16000000HZ,
.agc_mode = MXL_SINGLE_AGC,
.tracking_filter = MXL_TF_C,
.rssi_enable = MXL_RSSI_ENABLE,
.cap_select = MXL_CAP_SEL_ENABLE,
.div_out = MXL_DIV_OUT_4,
.clock_out = MXL_CLOCK_OUT_DISABLE,
.output_load = MXL5005S_IF_OUTPUT_LOAD_200_OHM,
.top = MXL5005S_TOP_25P2,
.mod_mode = MXL_DIGITAL_MODE,
.if_mode = MXL_ZERO_IF,
.AgcMasterByte = 0x00,
};
static struct max2165_config mygica_d689_max2165_cfg = {
.i2c_address = 0x60,
.osc_clk = 20
};
/* Callbacks for DVB USB */
static int cxusb_fmd1216me_tuner_attach(struct dvb_usb_adapter *adap)
{
dvb_attach(simple_tuner_attach, adap->fe_adap[0].fe,
&adap->dev->i2c_adap, 0x61,
TUNER_PHILIPS_FMD1216ME_MK3);
return 0;
}
static int cxusb_dee1601_tuner_attach(struct dvb_usb_adapter *adap)
{
dvb_attach(dvb_pll_attach, adap->fe_adap[0].fe, 0x61,
NULL, DVB_PLL_THOMSON_DTT7579);
return 0;
}
static int cxusb_lgz201_tuner_attach(struct dvb_usb_adapter *adap)
{
dvb_attach(dvb_pll_attach, adap->fe_adap[0].fe, 0x61, NULL, DVB_PLL_LG_Z201);
return 0;
}
static int cxusb_dtt7579_tuner_attach(struct dvb_usb_adapter *adap)
{
dvb_attach(dvb_pll_attach, adap->fe_adap[0].fe, 0x60,
NULL, DVB_PLL_THOMSON_DTT7579);
return 0;
}
static int cxusb_lgh064f_tuner_attach(struct dvb_usb_adapter *adap)
{
dvb_attach(simple_tuner_attach, adap->fe_adap[0].fe,
&adap->dev->i2c_adap, 0x61, TUNER_LG_TDVS_H06XF);
return 0;
}
static int dvico_bluebird_xc2028_callback(void *ptr, int component,
int command, int arg)
{
struct dvb_usb_adapter *adap = ptr;
struct dvb_usb_device *d = adap->dev;
switch (command) {
case XC2028_TUNER_RESET:
deb_info("%s: XC2028_TUNER_RESET %d\n", __func__, arg);
cxusb_bluebird_gpio_pulse(d, 0x01, 1);
break;
case XC2028_RESET_CLK:
deb_info("%s: XC2028_RESET_CLK %d\n", __func__, arg);
break;
default:
deb_info("%s: unknown command %d, arg %d\n", __func__,
command, arg);
return -EINVAL;
}
return 0;
}
static int cxusb_dvico_xc3028_tuner_attach(struct dvb_usb_adapter *adap)
{
struct dvb_frontend *fe;
struct xc2028_config cfg = {
.i2c_adap = &adap->dev->i2c_adap,
.i2c_addr = 0x61,
};
static struct xc2028_ctrl ctl = {
.fname = XC2028_DEFAULT_FIRMWARE,
.max_len = 64,
.demod = XC3028_FE_ZARLINK456,
};
/* FIXME: generalize & move to common area */
adap->fe_adap[0].fe->callback = dvico_bluebird_xc2028_callback;
fe = dvb_attach(xc2028_attach, adap->fe_adap[0].fe, &cfg);
if (fe == NULL || fe->ops.tuner_ops.set_config == NULL)
return -EIO;
fe->ops.tuner_ops.set_config(fe, &ctl);
return 0;
}
static int cxusb_mxl5003s_tuner_attach(struct dvb_usb_adapter *adap)
{
dvb_attach(mxl5005s_attach, adap->fe_adap[0].fe,
&adap->dev->i2c_adap, &aver_a868r_tuner);
return 0;
}
static int cxusb_d680_dmb_tuner_attach(struct dvb_usb_adapter *adap)
{
struct dvb_frontend *fe;
fe = dvb_attach(mxl5005s_attach, adap->fe_adap[0].fe,
&adap->dev->i2c_adap, &d680_dmb_tuner);
return (fe == NULL) ? -EIO : 0;
}
static int cxusb_mygica_d689_tuner_attach(struct dvb_usb_adapter *adap)
{
struct dvb_frontend *fe;
fe = dvb_attach(max2165_attach, adap->fe_adap[0].fe,
&adap->dev->i2c_adap, &mygica_d689_max2165_cfg);
return (fe == NULL) ? -EIO : 0;
}
static int cxusb_cx22702_frontend_attach(struct dvb_usb_adapter *adap)
{
u8 b;
if (usb_set_interface(adap->dev->udev, 0, 6) < 0)
err("set interface failed");
cxusb_ctrl_msg(adap->dev, CMD_DIGITAL, NULL, 0, &b, 1);
adap->fe_adap[0].fe = dvb_attach(cx22702_attach, &cxusb_cx22702_config,
&adap->dev->i2c_adap);
if ((adap->fe_adap[0].fe) != NULL)
return 0;
return -EIO;
}
static int cxusb_lgdt3303_frontend_attach(struct dvb_usb_adapter *adap)
{
if (usb_set_interface(adap->dev->udev, 0, 7) < 0)
err("set interface failed");
cxusb_ctrl_msg(adap->dev, CMD_DIGITAL, NULL, 0, NULL, 0);
adap->fe_adap[0].fe = dvb_attach(lgdt330x_attach,
&cxusb_lgdt3303_config,
&adap->dev->i2c_adap);
if ((adap->fe_adap[0].fe) != NULL)
return 0;
return -EIO;
}
static int cxusb_aver_lgdt3303_frontend_attach(struct dvb_usb_adapter *adap)
{
adap->fe_adap[0].fe = dvb_attach(lgdt330x_attach, &cxusb_aver_lgdt3303_config,
&adap->dev->i2c_adap);
if (adap->fe_adap[0].fe != NULL)
return 0;
return -EIO;
}
static int cxusb_mt352_frontend_attach(struct dvb_usb_adapter *adap)
{
/* used in both lgz201 and th7579 */
if (usb_set_interface(adap->dev->udev, 0, 0) < 0)
err("set interface failed");
cxusb_ctrl_msg(adap->dev, CMD_DIGITAL, NULL, 0, NULL, 0);
adap->fe_adap[0].fe = dvb_attach(mt352_attach, &cxusb_mt352_config,
&adap->dev->i2c_adap);
if ((adap->fe_adap[0].fe) != NULL)
return 0;
return -EIO;
}
static int cxusb_dee1601_frontend_attach(struct dvb_usb_adapter *adap)
{
if (usb_set_interface(adap->dev->udev, 0, 0) < 0)
err("set interface failed");
cxusb_ctrl_msg(adap->dev, CMD_DIGITAL, NULL, 0, NULL, 0);
adap->fe_adap[0].fe = dvb_attach(mt352_attach, &cxusb_dee1601_config,
&adap->dev->i2c_adap);
if ((adap->fe_adap[0].fe) != NULL)
return 0;
adap->fe_adap[0].fe = dvb_attach(zl10353_attach,
&cxusb_zl10353_dee1601_config,
&adap->dev->i2c_adap);
if ((adap->fe_adap[0].fe) != NULL)
return 0;
return -EIO;
}
static int cxusb_dualdig4_frontend_attach(struct dvb_usb_adapter *adap)
{
u8 ircode[4];
int i;
struct i2c_msg msg = { .addr = 0x6b, .flags = I2C_M_RD,
.buf = ircode, .len = 4 };
if (usb_set_interface(adap->dev->udev, 0, 1) < 0)
err("set interface failed");
cxusb_ctrl_msg(adap->dev, CMD_DIGITAL, NULL, 0, NULL, 0);
/* reset the tuner and demodulator */
cxusb_bluebird_gpio_rw(adap->dev, 0x04, 0);
cxusb_bluebird_gpio_pulse(adap->dev, 0x01, 1);
cxusb_bluebird_gpio_pulse(adap->dev, 0x02, 1);
adap->fe_adap[0].fe =
dvb_attach(zl10353_attach,
&cxusb_zl10353_xc3028_config_no_i2c_gate,
&adap->dev->i2c_adap);
if ((adap->fe_adap[0].fe) == NULL)
return -EIO;
/* try to determine if there is no IR decoder on the I2C bus */
for (i = 0; adap->dev->props.rc.core.rc_codes && i < 5; i++) {
msleep(20);
if (cxusb_i2c_xfer(&adap->dev->i2c_adap, &msg, 1) != 1)
goto no_IR;
if (ircode[0] == 0 && ircode[1] == 0)
continue;
if (ircode[2] + ircode[3] != 0xff) {
no_IR:
adap->dev->props.rc.core.rc_codes = NULL;
info("No IR receiver detected on this device.");
break;
}
}
return 0;
}
static struct dibx000_agc_config dib7070_agc_config = {
.band_caps = BAND_UHF | BAND_VHF | BAND_LBAND | BAND_SBAND,
/*
* P_agc_use_sd_mod1=0, P_agc_use_sd_mod2=0, P_agc_freq_pwm_div=5,
* P_agc_inv_pwm1=0, P_agc_inv_pwm2=0, P_agc_inh_dc_rv_est=0,
* P_agc_time_est=3, P_agc_freeze=0, P_agc_nb_est=5, P_agc_write=0
*/
.setup = (0 << 15) | (0 << 14) | (5 << 11) | (0 << 10) | (0 << 9) |
(0 << 8) | (3 << 5) | (0 << 4) | (5 << 1) | (0 << 0),
.inv_gain = 600,
.time_stabiliz = 10,
.alpha_level = 0,
.thlock = 118,
.wbd_inv = 0,
.wbd_ref = 3530,
.wbd_sel = 1,
.wbd_alpha = 5,
.agc1_max = 65535,
.agc1_min = 0,
.agc2_max = 65535,
.agc2_min = 0,
.agc1_pt1 = 0,
.agc1_pt2 = 40,
.agc1_pt3 = 183,
.agc1_slope1 = 206,
.agc1_slope2 = 255,
.agc2_pt1 = 72,
.agc2_pt2 = 152,
.agc2_slope1 = 88,
.agc2_slope2 = 90,
.alpha_mant = 17,
.alpha_exp = 27,
.beta_mant = 23,
.beta_exp = 51,
.perform_agc_softsplit = 0,
};
static struct dibx000_bandwidth_config dib7070_bw_config_12_mhz = {
.internal = 60000,
.sampling = 15000,
.pll_prediv = 1,
.pll_ratio = 20,
.pll_range = 3,
.pll_reset = 1,
.pll_bypass = 0,
.enable_refdiv = 0,
.bypclk_div = 0,
.IO_CLK_en_core = 1,
.ADClkSrc = 1,
.modulo = 2,
/* refsel, sel, freq_15k */
.sad_cfg = (3 << 14) | (1 << 12) | (524 << 0),
.ifreq = (0 << 25) | 0,
.timf = 20452225,
.xtal_hz = 12000000,
};
static struct dib7000p_config cxusb_dualdig4_rev2_config = {
.output_mode = OUTMODE_MPEG2_PAR_GATED_CLK,
.output_mpeg2_in_188_bytes = 1,
.agc_config_count = 1,
.agc = &dib7070_agc_config,
.bw = &dib7070_bw_config_12_mhz,
.tuner_is_baseband = 1,
.spur_protect = 1,
.gpio_dir = 0xfcef,
.gpio_val = 0x0110,
.gpio_pwm_pos = DIB7000P_GPIO_DEFAULT_PWM_POS,
.hostbus_diversity = 1,
};
struct dib0700_adapter_state {
int (*set_param_save)(struct dvb_frontend *);
struct dib7000p_ops dib7000p_ops;
};
static int cxusb_dualdig4_rev2_frontend_attach(struct dvb_usb_adapter *adap)
{
struct dib0700_adapter_state *state = adap->priv;
if (usb_set_interface(adap->dev->udev, 0, 1) < 0)
err("set interface failed");
cxusb_ctrl_msg(adap->dev, CMD_DIGITAL, NULL, 0, NULL, 0);
cxusb_bluebird_gpio_pulse(adap->dev, 0x02, 1);
if (!dvb_attach(dib7000p_attach, &state->dib7000p_ops))
return -ENODEV;
if (state->dib7000p_ops.i2c_enumeration(&adap->dev->i2c_adap, 1, 18,
&cxusb_dualdig4_rev2_config) < 0) {
printk(KERN_WARNING "Unable to enumerate dib7000p\n");
return -ENODEV;
}
adap->fe_adap[0].fe = state->dib7000p_ops.init(&adap->dev->i2c_adap, 0x80,
&cxusb_dualdig4_rev2_config);
if (adap->fe_adap[0].fe == NULL)
return -EIO;
return 0;
}
static int dib7070_tuner_reset(struct dvb_frontend *fe, int onoff)
{
struct dvb_usb_adapter *adap = fe->dvb->priv;
struct dib0700_adapter_state *state = adap->priv;
return state->dib7000p_ops.set_gpio(fe, 8, 0, !onoff);
}
static int dib7070_tuner_sleep(struct dvb_frontend *fe, int onoff)
{
return 0;
}
static struct dib0070_config dib7070p_dib0070_config = {
.i2c_address = DEFAULT_DIB0070_I2C_ADDRESS,
.reset = dib7070_tuner_reset,
.sleep = dib7070_tuner_sleep,
.clock_khz = 12000,
};
static int dib7070_set_param_override(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
struct dvb_usb_adapter *adap = fe->dvb->priv;
struct dib0700_adapter_state *state = adap->priv;
u16 offset;
u8 band = BAND_OF_FREQUENCY(p->frequency/1000);
switch (band) {
case BAND_VHF: offset = 950; break;
default:
case BAND_UHF: offset = 550; break;
}
state->dib7000p_ops.set_wbd_ref(fe, offset + dib0070_wbd_offset(fe));
return state->set_param_save(fe);
}
static int cxusb_dualdig4_rev2_tuner_attach(struct dvb_usb_adapter *adap)
{
struct dib0700_adapter_state *st = adap->priv;
struct i2c_adapter *tun_i2c;
/*
* No need to call dvb7000p_attach here, as it was called
* already, as frontend_attach method is called first, and
* tuner_attach is only called on sucess.
*/
tun_i2c = st->dib7000p_ops.get_i2c_master(adap->fe_adap[0].fe,
DIBX000_I2C_INTERFACE_TUNER, 1);
if (dvb_attach(dib0070_attach, adap->fe_adap[0].fe, tun_i2c,
&dib7070p_dib0070_config) == NULL)
return -ENODEV;
st->set_param_save = adap->fe_adap[0].fe->ops.tuner_ops.set_params;
adap->fe_adap[0].fe->ops.tuner_ops.set_params = dib7070_set_param_override;
return 0;
}
static int cxusb_nano2_frontend_attach(struct dvb_usb_adapter *adap)
{
if (usb_set_interface(adap->dev->udev, 0, 1) < 0)
err("set interface failed");
cxusb_ctrl_msg(adap->dev, CMD_DIGITAL, NULL, 0, NULL, 0);
/* reset the tuner and demodulator */
cxusb_bluebird_gpio_rw(adap->dev, 0x04, 0);
cxusb_bluebird_gpio_pulse(adap->dev, 0x01, 1);
cxusb_bluebird_gpio_pulse(adap->dev, 0x02, 1);
adap->fe_adap[0].fe = dvb_attach(zl10353_attach,
&cxusb_zl10353_xc3028_config,
&adap->dev->i2c_adap);
if ((adap->fe_adap[0].fe) != NULL)
return 0;
adap->fe_adap[0].fe = dvb_attach(mt352_attach,
&cxusb_mt352_xc3028_config,
&adap->dev->i2c_adap);
if ((adap->fe_adap[0].fe) != NULL)
return 0;
return -EIO;
}
static struct lgs8gxx_config d680_lgs8gl5_cfg = {
.prod = LGS8GXX_PROD_LGS8GL5,
.demod_address = 0x19,
.serial_ts = 0,
.ts_clk_pol = 0,
.ts_clk_gated = 1,
.if_clk_freq = 30400, /* 30.4 MHz */
.if_freq = 5725, /* 5.725 MHz */
.if_neg_center = 0,
.ext_adc = 0,
.adc_signed = 0,
.if_neg_edge = 0,
};
static int cxusb_d680_dmb_frontend_attach(struct dvb_usb_adapter *adap)
{
struct dvb_usb_device *d = adap->dev;
int n;
/* Select required USB configuration */
if (usb_set_interface(d->udev, 0, 0) < 0)
err("set interface failed");
/* Unblock all USB pipes */
usb_clear_halt(d->udev,
usb_sndbulkpipe(d->udev, d->props.generic_bulk_ctrl_endpoint));
usb_clear_halt(d->udev,
usb_rcvbulkpipe(d->udev, d->props.generic_bulk_ctrl_endpoint));
usb_clear_halt(d->udev,
usb_rcvbulkpipe(d->udev, d->props.adapter[0].fe[0].stream.endpoint));
/* Drain USB pipes to avoid hang after reboot */
for (n = 0; n < 5; n++) {
cxusb_d680_dmb_drain_message(d);
cxusb_d680_dmb_drain_video(d);
msleep(200);
}
/* Reset the tuner */
if (cxusb_d680_dmb_gpio_tuner(d, 0x07, 0) < 0) {
err("clear tuner gpio failed");
return -EIO;
}
msleep(100);
if (cxusb_d680_dmb_gpio_tuner(d, 0x07, 1) < 0) {
err("set tuner gpio failed");
return -EIO;
}
msleep(100);
/* Attach frontend */
adap->fe_adap[0].fe = dvb_attach(lgs8gxx_attach, &d680_lgs8gl5_cfg, &d->i2c_adap);
if (adap->fe_adap[0].fe == NULL)
return -EIO;
return 0;
}
static struct atbm8830_config mygica_d689_atbm8830_cfg = {
.prod = ATBM8830_PROD_8830,
.demod_address = 0x40,
.serial_ts = 0,
.ts_sampling_edge = 1,
.ts_clk_gated = 0,
.osc_clk_freq = 30400, /* in kHz */
.if_freq = 0, /* zero IF */
.zif_swap_iq = 1,
.agc_min = 0x2E,
.agc_max = 0x90,
.agc_hold_loop = 0,
};
static int cxusb_mygica_d689_frontend_attach(struct dvb_usb_adapter *adap)
{
struct dvb_usb_device *d = adap->dev;
/* Select required USB configuration */
if (usb_set_interface(d->udev, 0, 0) < 0)
err("set interface failed");
/* Unblock all USB pipes */
usb_clear_halt(d->udev,
usb_sndbulkpipe(d->udev, d->props.generic_bulk_ctrl_endpoint));
usb_clear_halt(d->udev,
usb_rcvbulkpipe(d->udev, d->props.generic_bulk_ctrl_endpoint));
usb_clear_halt(d->udev,
usb_rcvbulkpipe(d->udev, d->props.adapter[0].fe[0].stream.endpoint));
/* Reset the tuner */
if (cxusb_d680_dmb_gpio_tuner(d, 0x07, 0) < 0) {
err("clear tuner gpio failed");
return -EIO;
}
msleep(100);
if (cxusb_d680_dmb_gpio_tuner(d, 0x07, 1) < 0) {
err("set tuner gpio failed");
return -EIO;
}
msleep(100);
/* Attach frontend */
adap->fe_adap[0].fe = dvb_attach(atbm8830_attach, &mygica_d689_atbm8830_cfg,
&d->i2c_adap);
if (adap->fe_adap[0].fe == NULL)
return -EIO;
return 0;
}
static int cxusb_mygica_t230_frontend_attach(struct dvb_usb_adapter *adap)
{
struct dvb_usb_device *d = adap->dev;
struct cxusb_state *st = d->priv;
struct i2c_adapter *adapter;
struct i2c_client *client_demod;
struct i2c_client *client_tuner;
struct i2c_board_info info;
struct si2168_config si2168_config;
struct si2157_config si2157_config;
/* Select required USB configuration */
if (usb_set_interface(d->udev, 0, 0) < 0)
err("set interface failed");
/* Unblock all USB pipes */
usb_clear_halt(d->udev,
usb_sndbulkpipe(d->udev, d->props.generic_bulk_ctrl_endpoint));
usb_clear_halt(d->udev,
usb_rcvbulkpipe(d->udev, d->props.generic_bulk_ctrl_endpoint));
usb_clear_halt(d->udev,
usb_rcvbulkpipe(d->udev, d->props.adapter[0].fe[0].stream.endpoint));
/* attach frontend */
si2168_config.i2c_adapter = &adapter;
si2168_config.fe = &adap->fe_adap[0].fe;
si2168_config.ts_mode = SI2168_TS_PARALLEL;
si2168_config.ts_clock_inv = 1;
memset(&info, 0, sizeof(struct i2c_board_info));
strlcpy(info.type, "si2168", I2C_NAME_SIZE);
info.addr = 0x64;
info.platform_data = &si2168_config;
request_module(info.type);
client_demod = i2c_new_device(&d->i2c_adap, &info);
if (client_demod == NULL || client_demod->dev.driver == NULL)
return -ENODEV;
if (!try_module_get(client_demod->dev.driver->owner)) {
i2c_unregister_device(client_demod);
return -ENODEV;
}
st->i2c_client_demod = client_demod;
/* attach tuner */
memset(&si2157_config, 0, sizeof(si2157_config));
si2157_config.fe = adap->fe_adap[0].fe;
si2157_config.if_port = 1;
memset(&info, 0, sizeof(struct i2c_board_info));
strlcpy(info.type, "si2157", I2C_NAME_SIZE);
info.addr = 0x60;
info.platform_data = &si2157_config;
request_module(info.type);
client_tuner = i2c_new_device(adapter, &info);
if (client_tuner == NULL || client_tuner->dev.driver == NULL) {
module_put(client_demod->dev.driver->owner);
i2c_unregister_device(client_demod);
return -ENODEV;
}
if (!try_module_get(client_tuner->dev.driver->owner)) {
i2c_unregister_device(client_tuner);
module_put(client_demod->dev.driver->owner);
i2c_unregister_device(client_demod);
return -ENODEV;
}
st->i2c_client_tuner = client_tuner;
/* hook fe: need to resync the slave fifo when signal locks. */
mutex_init(&st->stream_mutex);
st->last_lock = 0;
st->fe_read_status = adap->fe_adap[0].fe->ops.read_status;
adap->fe_adap[0].fe->ops.read_status = cxusb_read_status;
return 0;
}
/*
* DViCO has shipped two devices with the same USB ID, but only one of them
* needs a firmware download. Check the device class details to see if they
* have non-default values to decide whether the device is actually cold or
* not, and forget a match if it turns out we selected the wrong device.
*/
static int bluebird_fx2_identify_state(struct usb_device *udev,
struct dvb_usb_device_properties *props,
struct dvb_usb_device_description **desc,
int *cold)
{
int wascold = *cold;
*cold = udev->descriptor.bDeviceClass == 0xff &&
udev->descriptor.bDeviceSubClass == 0xff &&
udev->descriptor.bDeviceProtocol == 0xff;
if (*cold && !wascold)
*desc = NULL;
return 0;
}
/*
* DViCO bluebird firmware needs the "warm" product ID to be patched into the
* firmware file before download.
*/
static const int dvico_firmware_id_offsets[] = { 6638, 3204 };
static int bluebird_patch_dvico_firmware_download(struct usb_device *udev,
const struct firmware *fw)
{
int pos;
for (pos = 0; pos < ARRAY_SIZE(dvico_firmware_id_offsets); pos++) {
int idoff = dvico_firmware_id_offsets[pos];
if (fw->size < idoff + 4)
continue;
if (fw->data[idoff] == (USB_VID_DVICO & 0xff) &&
fw->data[idoff + 1] == USB_VID_DVICO >> 8) {
struct firmware new_fw;
u8 *new_fw_data = vmalloc(fw->size);
int ret;
if (!new_fw_data)
return -ENOMEM;
memcpy(new_fw_data, fw->data, fw->size);
new_fw.size = fw->size;
new_fw.data = new_fw_data;
new_fw_data[idoff + 2] =
le16_to_cpu(udev->descriptor.idProduct) + 1;
new_fw_data[idoff + 3] =
le16_to_cpu(udev->descriptor.idProduct) >> 8;
ret = usb_cypress_load_firmware(udev, &new_fw,
CYPRESS_FX2);
vfree(new_fw_data);
return ret;
}
}
return -EINVAL;
}
/* DVB USB Driver stuff */
static struct dvb_usb_device_properties cxusb_medion_properties;
static struct dvb_usb_device_properties cxusb_bluebird_lgh064f_properties;
static struct dvb_usb_device_properties cxusb_bluebird_dee1601_properties;
static struct dvb_usb_device_properties cxusb_bluebird_lgz201_properties;
static struct dvb_usb_device_properties cxusb_bluebird_dtt7579_properties;
static struct dvb_usb_device_properties cxusb_bluebird_dualdig4_properties;
static struct dvb_usb_device_properties cxusb_bluebird_dualdig4_rev2_properties;
static struct dvb_usb_device_properties cxusb_bluebird_nano2_properties;
static struct dvb_usb_device_properties cxusb_bluebird_nano2_needsfirmware_properties;
static struct dvb_usb_device_properties cxusb_aver_a868r_properties;
static struct dvb_usb_device_properties cxusb_d680_dmb_properties;
static struct dvb_usb_device_properties cxusb_mygica_d689_properties;
static struct dvb_usb_device_properties cxusb_mygica_t230_properties;
static int cxusb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
if (0 == dvb_usb_device_init(intf, &cxusb_medion_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &cxusb_bluebird_lgh064f_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &cxusb_bluebird_dee1601_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &cxusb_bluebird_lgz201_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &cxusb_bluebird_dtt7579_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &cxusb_bluebird_dualdig4_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &cxusb_bluebird_nano2_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf,
&cxusb_bluebird_nano2_needsfirmware_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &cxusb_aver_a868r_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf,
&cxusb_bluebird_dualdig4_rev2_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &cxusb_d680_dmb_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &cxusb_mygica_d689_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &cxusb_mygica_t230_properties,
THIS_MODULE, NULL, adapter_nr) ||
0)
return 0;
return -EINVAL;
}
static void cxusb_disconnect(struct usb_interface *intf)
{
struct dvb_usb_device *d = usb_get_intfdata(intf);
struct cxusb_state *st = d->priv;
struct i2c_client *client;
/* remove I2C client for tuner */
client = st->i2c_client_tuner;
if (client) {
module_put(client->dev.driver->owner);
i2c_unregister_device(client);
}
/* remove I2C client for demodulator */
client = st->i2c_client_demod;
if (client) {
module_put(client->dev.driver->owner);
i2c_unregister_device(client);
}
dvb_usb_device_exit(intf);
}
enum cxusb_table_index {
MEDION_MD95700,
DVICO_BLUEBIRD_LG064F_COLD,
DVICO_BLUEBIRD_LG064F_WARM,
DVICO_BLUEBIRD_DUAL_1_COLD,
DVICO_BLUEBIRD_DUAL_1_WARM,
DVICO_BLUEBIRD_LGZ201_COLD,
DVICO_BLUEBIRD_LGZ201_WARM,
DVICO_BLUEBIRD_TH7579_COLD,
DVICO_BLUEBIRD_TH7579_WARM,
DIGITALNOW_BLUEBIRD_DUAL_1_COLD,
DIGITALNOW_BLUEBIRD_DUAL_1_WARM,
DVICO_BLUEBIRD_DUAL_2_COLD,
DVICO_BLUEBIRD_DUAL_2_WARM,
DVICO_BLUEBIRD_DUAL_4,
DVICO_BLUEBIRD_DVB_T_NANO_2,
DVICO_BLUEBIRD_DVB_T_NANO_2_NFW_WARM,
AVERMEDIA_VOLAR_A868R,
DVICO_BLUEBIRD_DUAL_4_REV_2,
CONEXANT_D680_DMB,
MYGICA_D689,
MYGICA_T230,
NR__cxusb_table_index
};
static struct usb_device_id cxusb_table[NR__cxusb_table_index + 1] = {
[MEDION_MD95700] = {
USB_DEVICE(USB_VID_MEDION, USB_PID_MEDION_MD95700)
},
[DVICO_BLUEBIRD_LG064F_COLD] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DVICO_BLUEBIRD_LG064F_COLD)
},
[DVICO_BLUEBIRD_LG064F_WARM] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DVICO_BLUEBIRD_LG064F_WARM)
},
[DVICO_BLUEBIRD_DUAL_1_COLD] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DVICO_BLUEBIRD_DUAL_1_COLD)
},
[DVICO_BLUEBIRD_DUAL_1_WARM] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DVICO_BLUEBIRD_DUAL_1_WARM)
},
[DVICO_BLUEBIRD_LGZ201_COLD] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DVICO_BLUEBIRD_LGZ201_COLD)
},
[DVICO_BLUEBIRD_LGZ201_WARM] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DVICO_BLUEBIRD_LGZ201_WARM)
},
[DVICO_BLUEBIRD_TH7579_COLD] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DVICO_BLUEBIRD_TH7579_COLD)
},
[DVICO_BLUEBIRD_TH7579_WARM] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DVICO_BLUEBIRD_TH7579_WARM)
},
[DIGITALNOW_BLUEBIRD_DUAL_1_COLD] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DIGITALNOW_BLUEBIRD_DUAL_1_COLD)
},
[DIGITALNOW_BLUEBIRD_DUAL_1_WARM] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DIGITALNOW_BLUEBIRD_DUAL_1_WARM)
},
[DVICO_BLUEBIRD_DUAL_2_COLD] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DVICO_BLUEBIRD_DUAL_2_COLD)
},
[DVICO_BLUEBIRD_DUAL_2_WARM] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DVICO_BLUEBIRD_DUAL_2_WARM)
},
[DVICO_BLUEBIRD_DUAL_4] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DVICO_BLUEBIRD_DUAL_4)
},
[DVICO_BLUEBIRD_DVB_T_NANO_2] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DVICO_BLUEBIRD_DVB_T_NANO_2)
},
[DVICO_BLUEBIRD_DVB_T_NANO_2_NFW_WARM] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DVICO_BLUEBIRD_DVB_T_NANO_2_NFW_WARM)
},
[AVERMEDIA_VOLAR_A868R] = {
USB_DEVICE(USB_VID_AVERMEDIA, USB_PID_AVERMEDIA_VOLAR_A868R)
},
[DVICO_BLUEBIRD_DUAL_4_REV_2] = {
USB_DEVICE(USB_VID_DVICO, USB_PID_DVICO_BLUEBIRD_DUAL_4_REV_2)
},
[CONEXANT_D680_DMB] = {
USB_DEVICE(USB_VID_CONEXANT, USB_PID_CONEXANT_D680_DMB)
},
[MYGICA_D689] = {
USB_DEVICE(USB_VID_CONEXANT, USB_PID_MYGICA_D689)
},
[MYGICA_T230] = {
USB_DEVICE(USB_VID_CONEXANT, USB_PID_MYGICA_T230)
},
{} /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, cxusb_table);
static struct dvb_usb_device_properties cxusb_medion_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = CYPRESS_FX2,
.size_of_priv = sizeof(struct cxusb_state),
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.streaming_ctrl = cxusb_streaming_ctrl,
.frontend_attach = cxusb_cx22702_frontend_attach,
.tuner_attach = cxusb_fmd1216me_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 5,
.endpoint = 0x02,
.u = {
.bulk = {
.buffersize = 8192,
}
}
},
}},
},
},
.power_ctrl = cxusb_power_ctrl,
.i2c_algo = &cxusb_i2c_algo,
.generic_bulk_ctrl_endpoint = 0x01,
.num_device_descs = 1,
.devices = {
{ "Medion MD95700 (MDUSBTV-HYBRID)",
{ NULL },
{ &cxusb_table[MEDION_MD95700], NULL },
},
}
};
static struct dvb_usb_device_properties cxusb_bluebird_lgh064f_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.firmware = "dvb-usb-bluebird-01.fw",
.download_firmware = bluebird_patch_dvico_firmware_download,
/* use usb alt setting 0 for EP4 transfer (dvb-t),
use usb alt setting 7 for EP2 transfer (atsc) */
.size_of_priv = sizeof(struct cxusb_state),
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.streaming_ctrl = cxusb_streaming_ctrl,
.frontend_attach = cxusb_lgdt3303_frontend_attach,
.tuner_attach = cxusb_lgh064f_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 5,
.endpoint = 0x02,
.u = {
.bulk = {
.buffersize = 8192,
}
}
},
}},
},
},
.power_ctrl = cxusb_bluebird_power_ctrl,
.i2c_algo = &cxusb_i2c_algo,
.rc.core = {
.rc_interval = 100,
.rc_codes = RC_MAP_DVICO_PORTABLE,
.module_name = KBUILD_MODNAME,
.rc_query = cxusb_rc_query,
.allowed_protos = RC_BIT_UNKNOWN,
},
.generic_bulk_ctrl_endpoint = 0x01,
.num_device_descs = 1,
.devices = {
{ "DViCO FusionHDTV5 USB Gold",
{ &cxusb_table[DVICO_BLUEBIRD_LG064F_COLD], NULL },
{ &cxusb_table[DVICO_BLUEBIRD_LG064F_WARM], NULL },
},
}
};
static struct dvb_usb_device_properties cxusb_bluebird_dee1601_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.firmware = "dvb-usb-bluebird-01.fw",
.download_firmware = bluebird_patch_dvico_firmware_download,
/* use usb alt setting 0 for EP4 transfer (dvb-t),
use usb alt setting 7 for EP2 transfer (atsc) */
.size_of_priv = sizeof(struct cxusb_state),
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.streaming_ctrl = cxusb_streaming_ctrl,
.frontend_attach = cxusb_dee1601_frontend_attach,
.tuner_attach = cxusb_dee1601_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 5,
.endpoint = 0x04,
.u = {
.bulk = {
.buffersize = 8192,
}
}
},
}},
},
},
.power_ctrl = cxusb_bluebird_power_ctrl,
.i2c_algo = &cxusb_i2c_algo,
.rc.core = {
.rc_interval = 100,
.rc_codes = RC_MAP_DVICO_MCE,
.module_name = KBUILD_MODNAME,
.rc_query = cxusb_rc_query,
.allowed_protos = RC_BIT_UNKNOWN,
},
.generic_bulk_ctrl_endpoint = 0x01,
.num_device_descs = 3,
.devices = {
{ "DViCO FusionHDTV DVB-T Dual USB",
{ &cxusb_table[DVICO_BLUEBIRD_DUAL_1_COLD], NULL },
{ &cxusb_table[DVICO_BLUEBIRD_DUAL_1_WARM], NULL },
},
{ "DigitalNow DVB-T Dual USB",
{ &cxusb_table[DIGITALNOW_BLUEBIRD_DUAL_1_COLD], NULL },
{ &cxusb_table[DIGITALNOW_BLUEBIRD_DUAL_1_WARM], NULL },
},
{ "DViCO FusionHDTV DVB-T Dual Digital 2",
{ &cxusb_table[DVICO_BLUEBIRD_DUAL_2_COLD], NULL },
{ &cxusb_table[DVICO_BLUEBIRD_DUAL_2_WARM], NULL },
},
}
};
static struct dvb_usb_device_properties cxusb_bluebird_lgz201_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.firmware = "dvb-usb-bluebird-01.fw",
.download_firmware = bluebird_patch_dvico_firmware_download,
/* use usb alt setting 0 for EP4 transfer (dvb-t),
use usb alt setting 7 for EP2 transfer (atsc) */
.size_of_priv = sizeof(struct cxusb_state),
.num_adapters = 2,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.streaming_ctrl = cxusb_streaming_ctrl,
.frontend_attach = cxusb_mt352_frontend_attach,
.tuner_attach = cxusb_lgz201_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 5,
.endpoint = 0x04,
.u = {
.bulk = {
.buffersize = 8192,
}
}
},
}},
},
},
.power_ctrl = cxusb_bluebird_power_ctrl,
.i2c_algo = &cxusb_i2c_algo,
.rc.core = {
.rc_interval = 100,
.rc_codes = RC_MAP_DVICO_PORTABLE,
.module_name = KBUILD_MODNAME,
.rc_query = cxusb_rc_query,
.allowed_protos = RC_BIT_UNKNOWN,
},
.generic_bulk_ctrl_endpoint = 0x01,
.num_device_descs = 1,
.devices = {
{ "DViCO FusionHDTV DVB-T USB (LGZ201)",
{ &cxusb_table[DVICO_BLUEBIRD_LGZ201_COLD], NULL },
{ &cxusb_table[DVICO_BLUEBIRD_LGZ201_WARM], NULL },
},
}
};
static struct dvb_usb_device_properties cxusb_bluebird_dtt7579_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.firmware = "dvb-usb-bluebird-01.fw",
.download_firmware = bluebird_patch_dvico_firmware_download,
/* use usb alt setting 0 for EP4 transfer (dvb-t),
use usb alt setting 7 for EP2 transfer (atsc) */
.size_of_priv = sizeof(struct cxusb_state),
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.streaming_ctrl = cxusb_streaming_ctrl,
.frontend_attach = cxusb_mt352_frontend_attach,
.tuner_attach = cxusb_dtt7579_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 5,
.endpoint = 0x04,
.u = {
.bulk = {
.buffersize = 8192,
}
}
},
}},
},
},
.power_ctrl = cxusb_bluebird_power_ctrl,
.i2c_algo = &cxusb_i2c_algo,
.rc.core = {
.rc_interval = 100,
.rc_codes = RC_MAP_DVICO_PORTABLE,
.module_name = KBUILD_MODNAME,
.rc_query = cxusb_rc_query,
.allowed_protos = RC_BIT_UNKNOWN,
},
.generic_bulk_ctrl_endpoint = 0x01,
.num_device_descs = 1,
.devices = {
{ "DViCO FusionHDTV DVB-T USB (TH7579)",
{ &cxusb_table[DVICO_BLUEBIRD_TH7579_COLD], NULL },
{ &cxusb_table[DVICO_BLUEBIRD_TH7579_WARM], NULL },
},
}
};
static struct dvb_usb_device_properties cxusb_bluebird_dualdig4_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = CYPRESS_FX2,
.size_of_priv = sizeof(struct cxusb_state),
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.streaming_ctrl = cxusb_streaming_ctrl,
.frontend_attach = cxusb_dualdig4_frontend_attach,
.tuner_attach = cxusb_dvico_xc3028_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 5,
.endpoint = 0x02,
.u = {
.bulk = {
.buffersize = 8192,
}
}
},
}},
},
},
.power_ctrl = cxusb_power_ctrl,
.i2c_algo = &cxusb_i2c_algo,
.generic_bulk_ctrl_endpoint = 0x01,
.rc.core = {
.rc_interval = 100,
.rc_codes = RC_MAP_DVICO_MCE,
.module_name = KBUILD_MODNAME,
.rc_query = cxusb_bluebird2_rc_query,
.allowed_protos = RC_BIT_UNKNOWN,
},
.num_device_descs = 1,
.devices = {
{ "DViCO FusionHDTV DVB-T Dual Digital 4",
{ NULL },
{ &cxusb_table[DVICO_BLUEBIRD_DUAL_4], NULL },
},
}
};
static struct dvb_usb_device_properties cxusb_bluebird_nano2_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = CYPRESS_FX2,
.identify_state = bluebird_fx2_identify_state,
.size_of_priv = sizeof(struct cxusb_state),
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.streaming_ctrl = cxusb_streaming_ctrl,
.frontend_attach = cxusb_nano2_frontend_attach,
.tuner_attach = cxusb_dvico_xc3028_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 5,
.endpoint = 0x02,
.u = {
.bulk = {
.buffersize = 8192,
}
}
},
}},
},
},
.power_ctrl = cxusb_nano2_power_ctrl,
.i2c_algo = &cxusb_i2c_algo,
.generic_bulk_ctrl_endpoint = 0x01,
.rc.core = {
.rc_interval = 100,
.rc_codes = RC_MAP_DVICO_PORTABLE,
.module_name = KBUILD_MODNAME,
.rc_query = cxusb_bluebird2_rc_query,
.allowed_protos = RC_BIT_UNKNOWN,
},
.num_device_descs = 1,
.devices = {
{ "DViCO FusionHDTV DVB-T NANO2",
{ NULL },
{ &cxusb_table[DVICO_BLUEBIRD_DVB_T_NANO_2], NULL },
},
}
};
static struct dvb_usb_device_properties cxusb_bluebird_nano2_needsfirmware_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.firmware = "dvb-usb-bluebird-02.fw",
.download_firmware = bluebird_patch_dvico_firmware_download,
.identify_state = bluebird_fx2_identify_state,
.size_of_priv = sizeof(struct cxusb_state),
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.streaming_ctrl = cxusb_streaming_ctrl,
.frontend_attach = cxusb_nano2_frontend_attach,
.tuner_attach = cxusb_dvico_xc3028_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 5,
.endpoint = 0x02,
.u = {
.bulk = {
.buffersize = 8192,
}
}
},
}},
},
},
.power_ctrl = cxusb_nano2_power_ctrl,
.i2c_algo = &cxusb_i2c_algo,
.generic_bulk_ctrl_endpoint = 0x01,
.rc.core = {
.rc_interval = 100,
.rc_codes = RC_MAP_DVICO_PORTABLE,
.module_name = KBUILD_MODNAME,
.rc_query = cxusb_rc_query,
.allowed_protos = RC_BIT_UNKNOWN,
},
.num_device_descs = 1,
.devices = {
{ "DViCO FusionHDTV DVB-T NANO2 w/o firmware",
{ &cxusb_table[DVICO_BLUEBIRD_DVB_T_NANO_2], NULL },
{ &cxusb_table[DVICO_BLUEBIRD_DVB_T_NANO_2_NFW_WARM], NULL },
},
}
};
static struct dvb_usb_device_properties cxusb_aver_a868r_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = CYPRESS_FX2,
.size_of_priv = sizeof(struct cxusb_state),
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.streaming_ctrl = cxusb_aver_streaming_ctrl,
.frontend_attach = cxusb_aver_lgdt3303_frontend_attach,
.tuner_attach = cxusb_mxl5003s_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 5,
.endpoint = 0x04,
.u = {
.bulk = {
.buffersize = 8192,
}
}
},
}},
},
},
.power_ctrl = cxusb_aver_power_ctrl,
.i2c_algo = &cxusb_i2c_algo,
.generic_bulk_ctrl_endpoint = 0x01,
.num_device_descs = 1,
.devices = {
{ "AVerMedia AVerTVHD Volar (A868R)",
{ NULL },
{ &cxusb_table[AVERMEDIA_VOLAR_A868R], NULL },
},
}
};
static
struct dvb_usb_device_properties cxusb_bluebird_dualdig4_rev2_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = CYPRESS_FX2,
.size_of_priv = sizeof(struct cxusb_state),
.num_adapters = 1,
.adapter = {
{
.size_of_priv = sizeof(struct dib0700_adapter_state),
.num_frontends = 1,
.fe = {{
.streaming_ctrl = cxusb_streaming_ctrl,
.frontend_attach = cxusb_dualdig4_rev2_frontend_attach,
.tuner_attach = cxusb_dualdig4_rev2_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 7,
.endpoint = 0x02,
.u = {
.bulk = {
.buffersize = 4096,
}
}
},
}},
},
},
.power_ctrl = cxusb_bluebird_power_ctrl,
.i2c_algo = &cxusb_i2c_algo,
.generic_bulk_ctrl_endpoint = 0x01,
.rc.core = {
.rc_interval = 100,
.rc_codes = RC_MAP_DVICO_MCE,
.module_name = KBUILD_MODNAME,
.rc_query = cxusb_rc_query,
.allowed_protos = RC_BIT_UNKNOWN,
},
.num_device_descs = 1,
.devices = {
{ "DViCO FusionHDTV DVB-T Dual Digital 4 (rev 2)",
{ NULL },
{ &cxusb_table[DVICO_BLUEBIRD_DUAL_4_REV_2], NULL },
},
}
};
static struct dvb_usb_device_properties cxusb_d680_dmb_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = CYPRESS_FX2,
.size_of_priv = sizeof(struct cxusb_state),
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.streaming_ctrl = cxusb_d680_dmb_streaming_ctrl,
.frontend_attach = cxusb_d680_dmb_frontend_attach,
.tuner_attach = cxusb_d680_dmb_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 5,
.endpoint = 0x02,
.u = {
.bulk = {
.buffersize = 8192,
}
}
},
}},
},
},
.power_ctrl = cxusb_d680_dmb_power_ctrl,
.i2c_algo = &cxusb_i2c_algo,
.generic_bulk_ctrl_endpoint = 0x01,
.rc.core = {
.rc_interval = 100,
.rc_codes = RC_MAP_D680_DMB,
.module_name = KBUILD_MODNAME,
.rc_query = cxusb_d680_dmb_rc_query,
.allowed_protos = RC_BIT_UNKNOWN,
},
.num_device_descs = 1,
.devices = {
{
"Conexant DMB-TH Stick",
{ NULL },
{ &cxusb_table[CONEXANT_D680_DMB], NULL },
},
}
};
static struct dvb_usb_device_properties cxusb_mygica_d689_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = CYPRESS_FX2,
.size_of_priv = sizeof(struct cxusb_state),
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.streaming_ctrl = cxusb_d680_dmb_streaming_ctrl,
.frontend_attach = cxusb_mygica_d689_frontend_attach,
.tuner_attach = cxusb_mygica_d689_tuner_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 5,
.endpoint = 0x02,
.u = {
.bulk = {
.buffersize = 8192,
}
}
},
}},
},
},
.power_ctrl = cxusb_d680_dmb_power_ctrl,
.i2c_algo = &cxusb_i2c_algo,
.generic_bulk_ctrl_endpoint = 0x01,
.rc.core = {
.rc_interval = 100,
.rc_codes = RC_MAP_D680_DMB,
.module_name = KBUILD_MODNAME,
.rc_query = cxusb_d680_dmb_rc_query,
.allowed_protos = RC_BIT_UNKNOWN,
},
.num_device_descs = 1,
.devices = {
{
"Mygica D689 DMB-TH",
{ NULL },
{ &cxusb_table[MYGICA_D689], NULL },
},
}
};
static struct dvb_usb_device_properties cxusb_mygica_t230_properties = {
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = CYPRESS_FX2,
.size_of_priv = sizeof(struct cxusb_state),
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {{
.streaming_ctrl = cxusb_streaming_ctrl,
.frontend_attach = cxusb_mygica_t230_frontend_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 5,
.endpoint = 0x02,
.u = {
.bulk = {
.buffersize = 8192,
}
}
},
} },
},
},
.power_ctrl = cxusb_d680_dmb_power_ctrl,
.i2c_algo = &cxusb_i2c_algo,
.generic_bulk_ctrl_endpoint = 0x01,
.rc.core = {
.rc_interval = 100,
.rc_codes = RC_MAP_D680_DMB,
.module_name = KBUILD_MODNAME,
.rc_query = cxusb_d680_dmb_rc_query,
.allowed_protos = RC_BIT_UNKNOWN,
},
.num_device_descs = 1,
.devices = {
{
"Mygica T230 DVB-T/T2/C",
{ NULL },
{ &cxusb_table[MYGICA_T230], NULL },
},
}
};
static struct usb_driver cxusb_driver = {
.name = "dvb_usb_cxusb",
.probe = cxusb_probe,
.disconnect = cxusb_disconnect,
.id_table = cxusb_table,
};
module_usb_driver(cxusb_driver);
MODULE_AUTHOR("Patrick Boettcher <patrick.boettcher@posteo.de>");
MODULE_AUTHOR("Michael Krufky <mkrufky@linuxtv.org>");
MODULE_AUTHOR("Chris Pascoe <c.pascoe@itee.uq.edu.au>");
MODULE_DESCRIPTION("Driver for Conexant USB2.0 hybrid reference design");
MODULE_VERSION("1.0-alpha");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3312_0 |
crossvul-cpp_data_bad_342_5 | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Initially written by David Mattes <david.mattes@boeing.com> */
/* Support for multiple key containers by Lukas Wunner <lukas@wunner.de> */
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "internal.h"
#include "pkcs15.h"
#define MANU_ID "Gemplus"
#define APPLET_NAME "GemSAFE V1"
#define DRIVER_SERIAL_NUMBER "v0.9"
#define GEMSAFE_APP_PATH "3F001600"
#define GEMSAFE_PATH "3F0016000004"
/* Apparently, the Applet max read "quanta" is 248 bytes
* Gemalto ClassicClient reads files in chunks of 238 bytes
*/
#define GEMSAFE_READ_QUANTUM 248
#define GEMSAFE_MAX_OBJLEN 28672
int sc_pkcs15emu_gemsafeV1_init_ex(sc_pkcs15_card_t *, struct sc_aid *,sc_pkcs15emu_opt_t *);
static int
sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card,
int type, int authority,
const sc_path_t *path,
const sc_pkcs15_id_t *id,
const char *label, int obj_flags);
static int
sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id, const char *label,
const sc_path_t *path, int ref, int type,
unsigned int min_length,
unsigned int max_length,
int flags, int tries_left, const char pad_char, int obj_flags);
static int
sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id,
const char *label,
int type, unsigned int modulus_length, int usage,
const sc_path_t *path, int ref,
const sc_pkcs15_id_t *auth_id, int obj_flags);
typedef struct cdata_st {
char *label;
int authority;
const char *path;
size_t index;
size_t count;
const char *id;
int obj_flags;
} cdata;
const unsigned int gemsafe_cert_max = 12;
cdata gemsafe_cert[] = {
{"DS certificate #1", 0, GEMSAFE_PATH, 0, 0, "45", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #2", 0, GEMSAFE_PATH, 0, 0, "46", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #3", 0, GEMSAFE_PATH, 0, 0, "47", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #4", 0, GEMSAFE_PATH, 0, 0, "48", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #5", 0, GEMSAFE_PATH, 0, 0, "49", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #6", 0, GEMSAFE_PATH, 0, 0, "50", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #7", 0, GEMSAFE_PATH, 0, 0, "51", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #8", 0, GEMSAFE_PATH, 0, 0, "52", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #9", 0, GEMSAFE_PATH, 0, 0, "53", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #10", 0, GEMSAFE_PATH, 0, 0, "54", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #11", 0, GEMSAFE_PATH, 0, 0, "55", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #12", 0, GEMSAFE_PATH, 0, 0, "56", SC_PKCS15_CO_FLAG_MODIFIABLE},
};
typedef struct pdata_st {
const u8 atr[SC_MAX_ATR_SIZE];
const size_t atr_len;
const char *id;
const char *label;
const char *path;
const int ref;
const int type;
const unsigned int maxlen;
const unsigned int minlen;
const int flags;
const int tries_left;
const char pad_char;
const int obj_flags;
} pindata;
const unsigned int gemsafe_pin_max = 2;
const pindata gemsafe_pin[] = {
/* ATR-specific PIN policies, first match found is used: */
{ {0x3B, 0x7D, 0x96, 0x00, 0x00, 0x80, 0x31, 0x80, 0x65,
0xB0, 0x83, 0x11, 0x48, 0xC8, 0x83, 0x00, 0x90, 0x00}, 18,
"01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_ASCII_NUMERIC,
8, 4, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL,
3, 0x00, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE },
/* default PIN policy comes last: */
{ { 0 }, 0,
"01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_BCD,
16, 6, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL,
3, 0xFF, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE }
};
typedef struct prdata_st {
const char *id;
char *label;
unsigned int modulus_len;
int usage;
const char *path;
int ref;
const char *auth_id;
int obj_flags;
} prdata;
#define USAGE_NONREP SC_PKCS15_PRKEY_USAGE_NONREPUDIATION
#define USAGE_KE SC_PKCS15_PRKEY_USAGE_ENCRYPT | \
SC_PKCS15_PRKEY_USAGE_DECRYPT | \
SC_PKCS15_PRKEY_USAGE_WRAP | \
SC_PKCS15_PRKEY_USAGE_UNWRAP
#define USAGE_AUT SC_PKCS15_PRKEY_USAGE_ENCRYPT | \
SC_PKCS15_PRKEY_USAGE_DECRYPT | \
SC_PKCS15_PRKEY_USAGE_WRAP | \
SC_PKCS15_PRKEY_USAGE_UNWRAP | \
SC_PKCS15_PRKEY_USAGE_SIGN
prdata gemsafe_prkeys[] = {
{ "45", "DS key #1", 1024, USAGE_AUT, GEMSAFE_PATH, 0x03, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "46", "DS key #2", 1024, USAGE_AUT, GEMSAFE_PATH, 0x04, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "47", "DS key #3", 1024, USAGE_AUT, GEMSAFE_PATH, 0x05, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "48", "DS key #4", 1024, USAGE_AUT, GEMSAFE_PATH, 0x06, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "49", "DS key #5", 1024, USAGE_AUT, GEMSAFE_PATH, 0x07, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "50", "DS key #6", 1024, USAGE_AUT, GEMSAFE_PATH, 0x08, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "51", "DS key #7", 1024, USAGE_AUT, GEMSAFE_PATH, 0x09, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "52", "DS key #8", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0a, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "53", "DS key #9", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0b, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "54", "DS key #10", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0c, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "55", "DS key #11", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0d, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "56", "DS key #12", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0e, "01", SC_PKCS15_CO_FLAG_PRIVATE},
};
static int gemsafe_get_cert_len(sc_card_t *card)
{
int r;
u8 ibuf[GEMSAFE_MAX_OBJLEN];
u8 *iptr;
struct sc_path path;
struct sc_file *file;
size_t objlen, certlen;
unsigned int ind, i=0;
sc_format_path(GEMSAFE_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* Initial read */
r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0);
if (r < 0)
return SC_ERROR_INTERNAL;
/* Actual stored object size is encoded in first 2 bytes
* (allocated EF space is much greater!)
*/
objlen = (((size_t) ibuf[0]) << 8) | ibuf[1];
sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) {
sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
return SC_ERROR_INTERNAL;
}
/* It looks like the first thing in the block is a table of
* which keys are allocated. The table is small and is in the
* first 248 bytes. Example for a card with 10 key containers:
* 01 f0 00 03 03 b0 00 03 <= 1st key unallocated
* 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated
* 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated
* 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated
* 01 f0 00 07 03 b0 00 07 <= 5th key unallocated
* ...
* 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated
* For allocated keys, the fourth byte seems to indicate the
* default key and the fifth byte indicates the key_ref of
* the private key.
*/
ind = 2; /* skip length */
while (ibuf[ind] == 0x01) {
if (ibuf[ind+1] == 0xFE) {
gemsafe_prkeys[i].ref = ibuf[ind+4];
sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d",
i+1, gemsafe_prkeys[i].ref);
ind += 9;
}
else {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
sc_log(card->ctx, "Key container %d is unallocated", i+1);
ind += 8;
}
i++;
}
/* Delete additional key containers from the data structures if
* this card can't accommodate them.
*/
for (; i < gemsafe_cert_max; i++) {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
/* Read entire file, then dissect in memory.
* Gemalto ClassicClient seems to do it the same way.
*/
iptr = ibuf + GEMSAFE_READ_QUANTUM;
while ((size_t)(iptr - ibuf) < objlen) {
r = sc_read_binary(card, iptr - ibuf, iptr,
MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0);
if (r < 0) {
sc_log(card->ctx, "Could not read cert object");
return SC_ERROR_INTERNAL;
}
iptr += GEMSAFE_READ_QUANTUM;
}
/* Search buffer for certificates, they start with 0x3082. */
i = 0;
while (ind < objlen - 1) {
if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) {
/* Find next allocated key container */
while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL)
i++;
if (i == gemsafe_cert_max) {
sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind);
return SC_SUCCESS;
}
/* DER cert len is encoded this way */
if (ind+3 >= sizeof ibuf)
return SC_ERROR_INVALID_DATA;
certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4;
sc_log(card->ctx,
"Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u",
i+1, ind, certlen);
gemsafe_cert[i].index = ind;
gemsafe_cert[i].count = certlen;
ind += certlen;
i++;
} else
ind++;
}
/* Delete additional key containers from the data structures if
* they're missing on the card.
*/
for (; i < gemsafe_cert_max; i++) {
if (gemsafe_cert[i].label) {
sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1);
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
}
return SC_SUCCESS;
}
static int gemsafe_detect_card( sc_pkcs15_card_t *p15card)
{
if (strcmp(p15card->card->name, "GemSAFE V1"))
return SC_ERROR_WRONG_CARD;
return SC_SUCCESS;
}
static int sc_pkcs15emu_gemsafeV1_init( sc_pkcs15_card_t *p15card)
{
int r;
unsigned int i;
struct sc_path path;
struct sc_file *file = NULL;
struct sc_card *card = p15card->card;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_log(p15card->card->ctx, "Setting pkcs15 parameters");
if (p15card->tokeninfo->label)
free(p15card->tokeninfo->label);
p15card->tokeninfo->label = malloc(strlen(APPLET_NAME) + 1);
if (!p15card->tokeninfo->label)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->label, APPLET_NAME);
if (p15card->tokeninfo->serial_number)
free(p15card->tokeninfo->serial_number);
p15card->tokeninfo->serial_number = malloc(strlen(DRIVER_SERIAL_NUMBER) + 1);
if (!p15card->tokeninfo->serial_number)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->serial_number, DRIVER_SERIAL_NUMBER);
/* the GemSAFE applet version number */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0xdf, 0x03);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
/* Manual says Le=0x05, but should be 0x08 to return full version number */
apdu.le = 0x08;
apdu.lc = 0;
apdu.datalen = 0;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00)
return SC_ERROR_INTERNAL;
if (r != SC_SUCCESS)
return SC_ERROR_INTERNAL;
/* the manufacturer ID, in this case GemPlus */
if (p15card->tokeninfo->manufacturer_id)
free(p15card->tokeninfo->manufacturer_id);
p15card->tokeninfo->manufacturer_id = malloc(strlen(MANU_ID) + 1);
if (!p15card->tokeninfo->manufacturer_id)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->manufacturer_id, MANU_ID);
/* determine allocated key containers and length of certificates */
r = gemsafe_get_cert_len(card);
if (r != SC_SUCCESS)
return SC_ERROR_INTERNAL;
/* set certs */
sc_log(p15card->card->ctx, "Setting certificates");
for (i = 0; i < gemsafe_cert_max; i++) {
struct sc_pkcs15_id p15Id;
struct sc_path path;
if (gemsafe_cert[i].label == NULL)
continue;
sc_format_path(gemsafe_cert[i].path, &path);
sc_pkcs15_format_id(gemsafe_cert[i].id, &p15Id);
path.index = gemsafe_cert[i].index;
path.count = gemsafe_cert[i].count;
sc_pkcs15emu_add_cert(p15card, SC_PKCS15_TYPE_CERT_X509,
gemsafe_cert[i].authority, &path, &p15Id,
gemsafe_cert[i].label, gemsafe_cert[i].obj_flags);
}
/* set gemsafe_pin */
sc_log(p15card->card->ctx, "Setting PIN");
for (i=0; i < gemsafe_pin_max; i++) {
struct sc_pkcs15_id p15Id;
struct sc_path path;
sc_pkcs15_format_id(gemsafe_pin[i].id, &p15Id);
sc_format_path(gemsafe_pin[i].path, &path);
if (gemsafe_pin[i].atr_len == 0 ||
(gemsafe_pin[i].atr_len == p15card->card->atr.len &&
memcmp(p15card->card->atr.value, gemsafe_pin[i].atr,
p15card->card->atr.len) == 0)) {
sc_pkcs15emu_add_pin(p15card, &p15Id, gemsafe_pin[i].label,
&path, gemsafe_pin[i].ref, gemsafe_pin[i].type,
gemsafe_pin[i].minlen, gemsafe_pin[i].maxlen,
gemsafe_pin[i].flags, gemsafe_pin[i].tries_left,
gemsafe_pin[i].pad_char, gemsafe_pin[i].obj_flags);
break;
}
};
/* set private keys */
sc_log(p15card->card->ctx, "Setting private keys");
for (i = 0; i < gemsafe_cert_max; i++) {
struct sc_pkcs15_id p15Id, authId, *pauthId;
struct sc_path path;
int key_ref = 0x03;
if (gemsafe_prkeys[i].label == NULL)
continue;
sc_pkcs15_format_id(gemsafe_prkeys[i].id, &p15Id);
if (gemsafe_prkeys[i].auth_id) {
sc_pkcs15_format_id(gemsafe_prkeys[i].auth_id, &authId);
pauthId = &authId;
} else
pauthId = NULL;
sc_format_path(gemsafe_prkeys[i].path, &path);
/*
* The key ref may be different for different sites;
* by adding flags=n where the low order 4 bits can be
* the key ref we can force it.
*/
if ( p15card->card->flags & 0x0F) {
key_ref = p15card->card->flags & 0x0F;
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Overriding key_ref %d with %d\n",
gemsafe_prkeys[i].ref, key_ref);
} else
key_ref = gemsafe_prkeys[i].ref;
sc_pkcs15emu_add_prkey(p15card, &p15Id, gemsafe_prkeys[i].label,
SC_PKCS15_TYPE_PRKEY_RSA,
gemsafe_prkeys[i].modulus_len, gemsafe_prkeys[i].usage,
&path, key_ref, pauthId,
gemsafe_prkeys[i].obj_flags);
}
/* select the application DF */
sc_log(p15card->card->ctx, "Selecting application DF");
sc_format_path(GEMSAFE_APP_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* set the application DF */
if (p15card->file_app)
free(p15card->file_app);
p15card->file_app = file;
return SC_SUCCESS;
}
int sc_pkcs15emu_gemsafeV1_init_ex( sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)
return sc_pkcs15emu_gemsafeV1_init(p15card);
else {
int r = gemsafe_detect_card(p15card);
if (r)
return SC_ERROR_WRONG_CARD;
return sc_pkcs15emu_gemsafeV1_init(p15card);
}
}
static sc_pkcs15_df_t *
sc_pkcs15emu_get_df(sc_pkcs15_card_t *p15card, unsigned int type)
{
sc_pkcs15_df_t *df;
sc_file_t *file;
int created = 0;
while (1) {
for (df = p15card->df_list; df; df = df->next) {
if (df->type == type) {
if (created)
df->enumerated = 1;
return df;
}
}
assert(created == 0);
file = sc_file_new();
if (!file)
return NULL;
sc_format_path("11001101", &file->path);
sc_pkcs15_add_df(p15card, type, &file->path);
sc_file_free(file);
created++;
}
}
static int
sc_pkcs15emu_add_object(sc_pkcs15_card_t *p15card, int type,
const char *label, void *data,
const sc_pkcs15_id_t *auth_id, int obj_flags)
{
sc_pkcs15_object_t *obj;
int df_type;
obj = calloc(1, sizeof(*obj));
obj->type = type;
obj->data = data;
if (label)
strncpy(obj->label, label, sizeof(obj->label)-1);
obj->flags = obj_flags;
if (auth_id)
obj->auth_id = *auth_id;
switch (type & SC_PKCS15_TYPE_CLASS_MASK) {
case SC_PKCS15_TYPE_AUTH:
df_type = SC_PKCS15_AODF;
break;
case SC_PKCS15_TYPE_PRKEY:
df_type = SC_PKCS15_PRKDF;
break;
case SC_PKCS15_TYPE_PUBKEY:
df_type = SC_PKCS15_PUKDF;
break;
case SC_PKCS15_TYPE_CERT:
df_type = SC_PKCS15_CDF;
break;
default:
sc_log(p15card->card->ctx, "Unknown PKCS15 object type %d", type);
free(obj);
return SC_ERROR_INVALID_ARGUMENTS;
}
obj->df = sc_pkcs15emu_get_df(p15card, df_type);
sc_pkcs15_add_object(p15card, obj);
return 0;
}
static int
sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id, const char *label,
const sc_path_t *path, int ref, int type,
unsigned int min_length,
unsigned int max_length,
int flags, int tries_left, const char pad_char, int obj_flags)
{
sc_pkcs15_auth_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
info->auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
info->auth_method = SC_AC_CHV;
info->auth_id = *id;
info->attrs.pin.min_length = min_length;
info->attrs.pin.max_length = max_length;
info->attrs.pin.stored_length = max_length;
info->attrs.pin.type = type;
info->attrs.pin.reference = ref;
info->attrs.pin.flags = flags;
info->attrs.pin.pad_char = pad_char;
info->tries_left = tries_left;
info->logged_in = SC_PIN_STATE_UNKNOWN;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, SC_PKCS15_TYPE_AUTH_PIN, label, info, NULL, obj_flags);
}
static int
sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card,
int type, int authority,
const sc_path_t *path,
const sc_pkcs15_id_t *id,
const char *label, int obj_flags)
{
sc_pkcs15_cert_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
{
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
info->id = *id;
info->authority = authority;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, type, label, info, NULL, obj_flags);
}
static int
sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id,
const char *label,
int type, unsigned int modulus_length, int usage,
const sc_path_t *path, int ref,
const sc_pkcs15_id_t *auth_id, int obj_flags)
{
sc_pkcs15_prkey_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
{
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
info->id = *id;
info->modulus_length = modulus_length;
info->usage = usage;
info->native = 1;
info->access_flags = SC_PKCS15_PRKEY_ACCESS_SENSITIVE
| SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE
| SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE
| SC_PKCS15_PRKEY_ACCESS_LOCAL;
info->key_reference = ref;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, type, label,
info, auth_id, obj_flags);
}
/* SC_IMPLEMENT_DRIVER_VERSION("0.9.4") */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_342_5 |
crossvul-cpp_data_good_715_0 | /*
Legal Notice: Some portions of the source code contained in this file were
derived from the source code of TrueCrypt 7.1a, which is
Copyright (c) 2003-2012 TrueCrypt Developers Association and which is
governed by the TrueCrypt License 3.0, also from the source code of
Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux
and which is governed by the 'License Agreement for Encryption for the Masses'
Modifications and additions to the original source code (contained in this file)
and all other portions of this file are Copyright (c) 2013-2017 IDRIX
and are governed by the Apache License 2.0 the full text of which is
contained in the file License.txt included in VeraCrypt binary and source
code distribution packages. */
#include "TCdefs.h"
#include <ntddk.h>
#include "Crypto.h"
#include "Fat.h"
#include "Tests.h"
#include "cpu.h"
#include "Crc.h"
#include "Apidrvr.h"
#include "Boot/Windows/BootDefs.h"
#include "EncryptedIoQueue.h"
#include "EncryptionThreadPool.h"
#include "Ntdriver.h"
#include "Ntvol.h"
#include "DriveFilter.h"
#include "DumpFilter.h"
#include "Cache.h"
#include "Volumes.h"
#include "VolumeFilter.h"
#include <tchar.h>
#include <initguid.h>
#include <mountmgr.h>
#include <mountdev.h>
#include <ntddvol.h>
#include <Ntstrsafe.h>
#include <Intsafe.h>
#ifndef IOCTL_DISK_GET_CLUSTER_INFO
#define IOCTL_DISK_GET_CLUSTER_INFO CTL_CODE(IOCTL_DISK_BASE, 0x0085, METHOD_BUFFERED, FILE_ANY_ACCESS)
#endif
#ifndef IOCTL_DISK_ARE_VOLUMES_READY
#define IOCTL_DISK_ARE_VOLUMES_READY CTL_CODE(IOCTL_DISK_BASE, 0x0087, METHOD_BUFFERED, FILE_READ_ACCESS)
#endif
#ifndef FT_BALANCED_READ_MODE
#define FTTYPE ((ULONG)'f')
#define FT_BALANCED_READ_MODE CTL_CODE(FTTYPE, 6, METHOD_NEITHER, FILE_ANY_ACCESS)
#endif
#ifndef IOCTL_VOLUME_QUERY_ALLOCATION_HINT
#define IOCTL_VOLUME_QUERY_ALLOCATION_HINT CTL_CODE(IOCTL_VOLUME_BASE, 20, METHOD_OUT_DIRECT, FILE_READ_ACCESS)
#endif
#ifndef IOCTL_DISK_IS_CLUSTERED
#define IOCTL_DISK_IS_CLUSTERED CTL_CODE(IOCTL_DISK_BASE, 0x003e, METHOD_BUFFERED, FILE_ANY_ACCESS)
#endif
#ifndef IOCTL_VOLUME_POST_ONLINE
#define IOCTL_VOLUME_POST_ONLINE CTL_CODE(IOCTL_VOLUME_BASE, 25, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#endif
#ifndef IOCTL_VOLUME_IS_DYNAMIC
#define IOCTL_VOLUME_IS_DYNAMIC CTL_CODE(IOCTL_VOLUME_BASE, 18, METHOD_BUFFERED, FILE_ANY_ACCESS)
#endif
#ifndef StorageDeviceLBProvisioningProperty
#define StorageDeviceLBProvisioningProperty 11
#endif
#ifndef DeviceDsmAction_OffloadRead
#define DeviceDsmAction_OffloadRead ( 3 | DeviceDsmActionFlag_NonDestructive)
#endif
#ifndef DeviceDsmAction_OffloadWrite
#define DeviceDsmAction_OffloadWrite 4
#endif
#ifndef DeviceDsmAction_Allocation
#define DeviceDsmAction_Allocation ( 5 | DeviceDsmActionFlag_NonDestructive)
#endif
#ifndef DeviceDsmAction_Repair
#define DeviceDsmAction_Repair ( 6 | DeviceDsmActionFlag_NonDestructive)
#endif
#ifndef DeviceDsmAction_Scrub
#define DeviceDsmAction_Scrub ( 7 | DeviceDsmActionFlag_NonDestructive)
#endif
#ifndef DeviceDsmAction_DrtQuery
#define DeviceDsmAction_DrtQuery ( 8 | DeviceDsmActionFlag_NonDestructive)
#endif
#ifndef DeviceDsmAction_DrtClear
#define DeviceDsmAction_DrtClear ( 9 | DeviceDsmActionFlag_NonDestructive)
#endif
#ifndef DeviceDsmAction_DrtDisable
#define DeviceDsmAction_DrtDisable (10 | DeviceDsmActionFlag_NonDestructive)
#endif
/* Init section, which is thrown away as soon as DriverEntry returns */
#pragma alloc_text(INIT,DriverEntry)
#pragma alloc_text(INIT,TCCreateRootDeviceObject)
/* We need to silence 'type cast' warning in order to use MmGetSystemRoutineAddress.
* MmGetSystemRoutineAddress() should have been declare FARPROC instead of PVOID.
*/
#pragma warning(disable:4055)
PDRIVER_OBJECT TCDriverObject;
PDEVICE_OBJECT RootDeviceObject = NULL;
static KMUTEX RootDeviceControlMutex;
BOOL DriverShuttingDown = FALSE;
BOOL SelfTestsPassed;
int LastUniqueVolumeId;
ULONG OsMajorVersion = 0;
ULONG OsMinorVersion;
BOOL DriverUnloadDisabled = FALSE;
BOOL PortableMode = FALSE;
BOOL VolumeClassFilterRegistered = FALSE;
BOOL CacheBootPassword = FALSE;
BOOL CacheBootPim = FALSE;
BOOL NonAdminSystemFavoritesAccessDisabled = FALSE;
BOOL BlockSystemTrimCommand = FALSE;
BOOL AllowWindowsDefrag = FALSE;
static size_t EncryptionThreadPoolFreeCpuCountLimit = 0;
static BOOL SystemFavoriteVolumeDirty = FALSE;
static BOOL PagingFileCreationPrevented = FALSE;
static BOOL EnableExtendedIoctlSupport = FALSE;
static BOOL AllowTrimCommand = FALSE;
static KeSaveExtendedProcessorStateFn KeSaveExtendedProcessorStatePtr = NULL;
static KeRestoreExtendedProcessorStateFn KeRestoreExtendedProcessorStatePtr = NULL;
POOL_TYPE ExDefaultNonPagedPoolType = NonPagedPool;
ULONG ExDefaultMdlProtection = 0;
PDEVICE_OBJECT VirtualVolumeDeviceObjects[MAX_MOUNTED_VOLUME_DRIVE_NUMBER + 1];
NTSTATUS DriverEntry (PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath)
{
PKEY_VALUE_PARTIAL_INFORMATION startKeyValue;
LONG version;
int i;
Dump ("DriverEntry " TC_APP_NAME " " VERSION_STRING "\n");
DetectX86Features ();
PsGetVersion (&OsMajorVersion, &OsMinorVersion, NULL, NULL);
Dump ("OsMajorVersion=%d OsMinorVersion=%d\n", OsMajorVersion, OsMinorVersion);
// NX pool support is available starting from Windows 8
if ((OsMajorVersion > 6) || (OsMajorVersion == 6 && OsMinorVersion >= 2))
{
ExDefaultNonPagedPoolType = (POOL_TYPE) NonPagedPoolNx;
ExDefaultMdlProtection = MdlMappingNoExecute;
}
// KeSaveExtendedProcessorState/KeRestoreExtendedProcessorState are available starting from Windows 7
if ((OsMajorVersion > 6) || (OsMajorVersion == 6 && OsMinorVersion >= 1))
{
UNICODE_STRING saveFuncName, restoreFuncName;
RtlInitUnicodeString(&saveFuncName, L"KeSaveExtendedProcessorState");
RtlInitUnicodeString(&restoreFuncName, L"KeRestoreExtendedProcessorState");
KeSaveExtendedProcessorStatePtr = (KeSaveExtendedProcessorStateFn) MmGetSystemRoutineAddress(&saveFuncName);
KeRestoreExtendedProcessorStatePtr = (KeRestoreExtendedProcessorStateFn) MmGetSystemRoutineAddress(&restoreFuncName);
}
// Load dump filter if the main driver is already loaded
if (NT_SUCCESS (TCDeviceIoControl (NT_ROOT_PREFIX, TC_IOCTL_GET_DRIVER_VERSION, NULL, 0, &version, sizeof (version))))
return DumpFilterEntry ((PFILTER_EXTENSION) DriverObject, (PFILTER_INITIALIZATION_DATA) RegistryPath);
TCDriverObject = DriverObject;
memset (VirtualVolumeDeviceObjects, 0, sizeof (VirtualVolumeDeviceObjects));
ReadRegistryConfigFlags (TRUE);
EncryptionThreadPoolStart (EncryptionThreadPoolFreeCpuCountLimit);
SelfTestsPassed = AutoTestAlgorithms();
// Enable device class filters and load boot arguments if the driver is set to start at system boot
if (NT_SUCCESS (TCReadRegistryKey (RegistryPath, L"Start", &startKeyValue)))
{
if (startKeyValue->Type == REG_DWORD && *((uint32 *) startKeyValue->Data) == SERVICE_BOOT_START)
{
if (!SelfTestsPassed)
{
// in case of system encryption, if self-tests fail, disable all extended CPU
// features and try again in order to workaround faulty configurations
DisableCPUExtendedFeatures ();
SelfTestsPassed = AutoTestAlgorithms();
// BUG CHECK if the self-tests still fail
if (!SelfTestsPassed)
TC_BUG_CHECK (STATUS_INVALID_PARAMETER);
}
LoadBootArguments();
VolumeClassFilterRegistered = IsVolumeClassFilterRegistered();
DriverObject->DriverExtension->AddDevice = DriverAddDevice;
}
TCfree (startKeyValue);
}
for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; ++i)
{
DriverObject->MajorFunction[i] = TCDispatchQueueIRP;
}
DriverObject->DriverUnload = TCUnloadDriver;
return TCCreateRootDeviceObject (DriverObject);
}
NTSTATUS DriverAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo)
{
#if defined(DEBUG) || defined (DEBUG_TRACE)
char nameInfoBuffer[128];
POBJECT_NAME_INFORMATION nameInfo = (POBJECT_NAME_INFORMATION) nameInfoBuffer;
ULONG nameInfoSize;
Dump ("AddDevice pdo=%p type=%x name=%ws\n", pdo, pdo->DeviceType, NT_SUCCESS (ObQueryNameString (pdo, nameInfo, sizeof (nameInfoBuffer), &nameInfoSize)) ? nameInfo->Name.Buffer : L"?");
#endif
if (VolumeClassFilterRegistered && BootArgsValid && BootArgs.HiddenSystemPartitionStart != 0)
{
PWSTR interfaceLinks = NULL;
if (NT_SUCCESS (IoGetDeviceInterfaces (&GUID_DEVINTERFACE_VOLUME, pdo, DEVICE_INTERFACE_INCLUDE_NONACTIVE, &interfaceLinks)) && interfaceLinks)
{
if (interfaceLinks[0] != UNICODE_NULL)
{
Dump ("Volume pdo=%p interface=%ws\n", pdo, interfaceLinks);
ExFreePool (interfaceLinks);
return VolumeFilterAddDevice (driverObject, pdo);
}
ExFreePool (interfaceLinks);
}
}
return DriveFilterAddDevice (driverObject, pdo);
}
// Dumps a memory region to debug output
void DumpMemory (void *mem, int size)
{
unsigned char str[20];
unsigned char *m = mem;
int i,j;
for (j = 0; j < size / 8; j++)
{
memset (str,0,sizeof str);
for (i = 0; i < 8; i++)
{
if (m[i] > ' ' && m[i] <= '~')
str[i]=m[i];
else
str[i]='.';
}
Dump ("0x%08p %02x %02x %02x %02x %02x %02x %02x %02x %s\n",
m, m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], str);
m+=8;
}
}
BOOL IsAllZeroes (unsigned char* pbData, DWORD dwDataLen)
{
while (dwDataLen--)
{
if (*pbData)
return FALSE;
pbData++;
}
return TRUE;
}
BOOL ValidateIOBufferSize (PIRP irp, size_t requiredBufferSize, ValidateIOBufferSizeType type)
{
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (irp);
BOOL input = (type == ValidateInput || type == ValidateInputOutput);
BOOL output = (type == ValidateOutput || type == ValidateInputOutput);
if ((input && irpSp->Parameters.DeviceIoControl.InputBufferLength < requiredBufferSize)
|| (output && irpSp->Parameters.DeviceIoControl.OutputBufferLength < requiredBufferSize))
{
Dump ("STATUS_BUFFER_TOO_SMALL ioctl=0x%x,%d in=%d out=%d reqsize=%d insize=%d outsize=%d\n", (int) (irpSp->Parameters.DeviceIoControl.IoControlCode >> 16), (int) ((irpSp->Parameters.DeviceIoControl.IoControlCode & 0x1FFF) >> 2), input, output, requiredBufferSize, irpSp->Parameters.DeviceIoControl.InputBufferLength, irpSp->Parameters.DeviceIoControl.OutputBufferLength);
irp->IoStatus.Status = STATUS_BUFFER_TOO_SMALL;
irp->IoStatus.Information = 0;
return FALSE;
}
if (!input && output)
memset (irp->AssociatedIrp.SystemBuffer, 0, irpSp->Parameters.DeviceIoControl.OutputBufferLength);
return TRUE;
}
PDEVICE_OBJECT GetVirtualVolumeDeviceObject (int driveNumber)
{
if (driveNumber < MIN_MOUNTED_VOLUME_DRIVE_NUMBER || driveNumber > MAX_MOUNTED_VOLUME_DRIVE_NUMBER)
return NULL;
return VirtualVolumeDeviceObjects[driveNumber];
}
/* TCDispatchQueueIRP queues any IRP's so that they can be processed later
by the thread -- or in some cases handles them immediately! */
NTSTATUS TCDispatchQueueIRP (PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
PEXTENSION Extension = (PEXTENSION) DeviceObject->DeviceExtension;
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp);
NTSTATUS ntStatus;
#if defined(_DEBUG) || defined (_DEBUG_TRACE)
if (irpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL && (Extension->bRootDevice || Extension->IsVolumeDevice))
{
switch (irpSp->Parameters.DeviceIoControl.IoControlCode)
{
case TC_IOCTL_GET_MOUNTED_VOLUMES:
case TC_IOCTL_GET_PASSWORD_CACHE_STATUS:
case TC_IOCTL_GET_PORTABLE_MODE_STATUS:
case TC_IOCTL_SET_PORTABLE_MODE_STATUS:
case TC_IOCTL_OPEN_TEST:
case TC_IOCTL_GET_RESOLVED_SYMLINK:
case TC_IOCTL_GET_DEVICE_REFCOUNT:
case TC_IOCTL_GET_DRIVE_PARTITION_INFO:
case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES:
case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS:
case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS:
case TC_IOCTL_GET_WARNING_FLAGS:
case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING:
case IOCTL_DISK_CHECK_VERIFY:
break;
default:
Dump ("%ls (0x%x %d)\n",
TCTranslateCode (irpSp->Parameters.DeviceIoControl.IoControlCode),
(int) (irpSp->Parameters.DeviceIoControl.IoControlCode >> 16),
(int) ((irpSp->Parameters.DeviceIoControl.IoControlCode & 0x1FFF) >> 2));
}
}
#endif
if (!Extension->bRootDevice)
{
// Drive filter IRP
if (Extension->IsDriveFilterDevice)
return DriveFilterDispatchIrp (DeviceObject, Irp);
// Volume filter IRP
if (Extension->IsVolumeFilterDevice)
return VolumeFilterDispatchIrp (DeviceObject, Irp);
}
switch (irpSp->MajorFunction)
{
case IRP_MJ_CLOSE:
case IRP_MJ_CREATE:
case IRP_MJ_CLEANUP:
return COMPLETE_IRP (DeviceObject, Irp, STATUS_SUCCESS, 0);
case IRP_MJ_SHUTDOWN:
if (Extension->bRootDevice)
{
Dump ("Driver shutting down\n");
DriverShuttingDown = TRUE;
if (EncryptionSetupThread)
while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP, NULL, 0, NULL, 0) == STATUS_INSUFFICIENT_RESOURCES);
if (DecoySystemWipeThread)
while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE, NULL, 0, NULL, 0) == STATUS_INSUFFICIENT_RESOURCES);
OnShutdownPending();
}
return COMPLETE_IRP (DeviceObject, Irp, STATUS_SUCCESS, 0);
case IRP_MJ_FLUSH_BUFFERS:
case IRP_MJ_READ:
case IRP_MJ_WRITE:
case IRP_MJ_DEVICE_CONTROL:
if (Extension->bRootDevice)
{
if (irpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL)
{
NTSTATUS status = KeWaitForMutexObject (&RootDeviceControlMutex, Executive, KernelMode, FALSE, NULL);
if (!NT_SUCCESS (status))
return status;
status = ProcessMainDeviceControlIrp (DeviceObject, Extension, Irp);
KeReleaseMutex (&RootDeviceControlMutex, FALSE);
return status;
}
break;
}
if (Extension->bShuttingDown)
{
Dump ("Device %d shutting down: STATUS_DELETE_PENDING\n", Extension->nDosDriveNo);
return TCCompleteDiskIrp (Irp, STATUS_DELETE_PENDING, 0);
}
if (Extension->bRemovable
&& (DeviceObject->Flags & DO_VERIFY_VOLUME)
&& !(irpSp->Flags & SL_OVERRIDE_VERIFY_VOLUME)
&& irpSp->MajorFunction != IRP_MJ_FLUSH_BUFFERS)
{
Dump ("Removable device %d has DO_VERIFY_VOLUME flag: STATUS_DEVICE_NOT_READY\n", Extension->nDosDriveNo);
return TCCompleteDiskIrp (Irp, STATUS_DEVICE_NOT_READY, 0);
}
switch (irpSp->MajorFunction)
{
case IRP_MJ_READ:
case IRP_MJ_WRITE:
ntStatus = EncryptedIoQueueAddIrp (&Extension->Queue, Irp);
if (ntStatus != STATUS_PENDING)
TCCompleteDiskIrp (Irp, ntStatus, 0);
return ntStatus;
case IRP_MJ_DEVICE_CONTROL:
ntStatus = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp);
if (!NT_SUCCESS (ntStatus))
return TCCompleteIrp (Irp, ntStatus, 0);
IoMarkIrpPending (Irp);
ExInterlockedInsertTailList (&Extension->ListEntry, &Irp->Tail.Overlay.ListEntry, &Extension->ListSpinLock);
KeReleaseSemaphore (&Extension->RequestSemaphore, IO_DISK_INCREMENT, 1, FALSE);
return STATUS_PENDING;
case IRP_MJ_FLUSH_BUFFERS:
return TCCompleteDiskIrp (Irp, STATUS_SUCCESS, 0);
}
break;
case IRP_MJ_PNP:
if (!Extension->bRootDevice
&& Extension->IsVolumeDevice
&& irpSp->MinorFunction == IRP_MN_DEVICE_USAGE_NOTIFICATION
&& irpSp->Parameters.UsageNotification.Type == DeviceUsageTypePaging
&& irpSp->Parameters.UsageNotification.InPath)
{
PagingFileCreationPrevented = TRUE;
return TCCompleteIrp (Irp, STATUS_UNSUCCESSFUL, 0);
}
break;
}
return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0);
}
NTSTATUS TCCreateRootDeviceObject (PDRIVER_OBJECT DriverObject)
{
UNICODE_STRING Win32NameString, ntUnicodeString;
WCHAR dosname[32], ntname[32];
PDEVICE_OBJECT DeviceObject;
NTSTATUS ntStatus;
BOOL *bRootExtension;
Dump ("TCCreateRootDeviceObject BEGIN\n");
ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL);
RtlStringCbCopyW (dosname, sizeof(dosname),(LPWSTR) DOS_ROOT_PREFIX);
RtlStringCbCopyW (ntname, sizeof(ntname),(LPWSTR) NT_ROOT_PREFIX);
RtlInitUnicodeString (&ntUnicodeString, ntname);
RtlInitUnicodeString (&Win32NameString, dosname);
Dump ("Creating root device nt=%ls dos=%ls\n", ntname, dosname);
ntStatus = IoCreateDevice (
DriverObject,
sizeof (BOOL),
&ntUnicodeString,
FILE_DEVICE_UNKNOWN,
FILE_DEVICE_SECURE_OPEN,
FALSE,
&DeviceObject);
if (!NT_SUCCESS (ntStatus))
{
Dump ("TCCreateRootDeviceObject NTSTATUS = 0x%08x END\n", ntStatus);
return ntStatus;/* Failed to create DeviceObject */
}
DeviceObject->Flags |= DO_DIRECT_IO;
DeviceObject->AlignmentRequirement = FILE_WORD_ALIGNMENT;
/* Setup the device extension */
bRootExtension = (BOOL *) DeviceObject->DeviceExtension;
*bRootExtension = TRUE;
KeInitializeMutex (&RootDeviceControlMutex, 0);
ntStatus = IoCreateSymbolicLink (&Win32NameString, &ntUnicodeString);
if (!NT_SUCCESS (ntStatus))
{
Dump ("TCCreateRootDeviceObject NTSTATUS = 0x%08x END\n", ntStatus);
IoDeleteDevice (DeviceObject);
return ntStatus;
}
IoRegisterShutdownNotification (DeviceObject);
RootDeviceObject = DeviceObject;
Dump ("TCCreateRootDeviceObject STATUS_SUCCESS END\n");
return STATUS_SUCCESS;
}
NTSTATUS TCCreateDeviceObject (PDRIVER_OBJECT DriverObject,
PDEVICE_OBJECT * ppDeviceObject,
MOUNT_STRUCT * mount)
{
UNICODE_STRING ntUnicodeString;
WCHAR ntname[32];
PEXTENSION Extension;
NTSTATUS ntStatus;
ULONG devChars = 0;
#if defined (DEBUG) || defined (DEBUG_TRACE)
WCHAR dosname[32];
#endif
Dump ("TCCreateDeviceObject BEGIN\n");
ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL);
TCGetNTNameFromNumber (ntname, sizeof(ntname),mount->nDosDriveNo);
RtlInitUnicodeString (&ntUnicodeString, ntname);
#if defined (DEBUG) || defined (DEBUG_TRACE)
TCGetDosNameFromNumber (dosname, sizeof(dosname),mount->nDosDriveNo, DeviceNamespaceDefault);
#endif
devChars = FILE_DEVICE_SECURE_OPEN;
devChars |= mount->bMountReadOnly ? FILE_READ_ONLY_DEVICE : 0;
devChars |= mount->bMountRemovable ? FILE_REMOVABLE_MEDIA : 0;
#if defined (DEBUG) || defined (DEBUG_TRACE)
Dump ("Creating device nt=%ls dos=%ls\n", ntname, dosname);
#endif
ntStatus = IoCreateDevice (
DriverObject, /* Our Driver Object */
sizeof (EXTENSION), /* Size of state information */
&ntUnicodeString, /* Device name "\Device\Name" */
FILE_DEVICE_DISK, /* Device type */
devChars, /* Device characteristics */
FALSE, /* Exclusive device */
ppDeviceObject); /* Returned ptr to Device Object */
if (!NT_SUCCESS (ntStatus))
{
Dump ("TCCreateDeviceObject NTSTATUS = 0x%08x END\n", ntStatus);
return ntStatus;/* Failed to create DeviceObject */
}
/* Initialize device object and extension. */
(*ppDeviceObject)->Flags |= DO_DIRECT_IO;
(*ppDeviceObject)->StackSize += 6; // Reduce occurrence of NO_MORE_IRP_STACK_LOCATIONS bug check caused by buggy drivers
/* Setup the device extension */
Extension = (PEXTENSION) (*ppDeviceObject)->DeviceExtension;
memset (Extension, 0, sizeof (EXTENSION));
Extension->IsVolumeDevice = TRUE;
Extension->nDosDriveNo = mount->nDosDriveNo;
Extension->bRemovable = mount->bMountRemovable;
Extension->PartitionInInactiveSysEncScope = mount->bPartitionInInactiveSysEncScope;
Extension->SystemFavorite = mount->SystemFavorite;
KeInitializeEvent (&Extension->keCreateEvent, SynchronizationEvent, FALSE);
KeInitializeSemaphore (&Extension->RequestSemaphore, 0L, MAXLONG);
KeInitializeSpinLock (&Extension->ListSpinLock);
InitializeListHead (&Extension->ListEntry);
IoInitializeRemoveLock (&Extension->Queue.RemoveLock, 'LRCV', 0, 0);
VirtualVolumeDeviceObjects[mount->nDosDriveNo] = *ppDeviceObject;
Dump ("TCCreateDeviceObject STATUS_SUCCESS END\n");
return STATUS_SUCCESS;
}
BOOL RootDeviceControlMutexAcquireNoWait ()
{
NTSTATUS status;
LARGE_INTEGER timeout;
timeout.QuadPart = 0;
status = KeWaitForMutexObject (&RootDeviceControlMutex, Executive, KernelMode, FALSE, &timeout);
return NT_SUCCESS (status) && status != STATUS_TIMEOUT;
}
void RootDeviceControlMutexRelease ()
{
KeReleaseMutex (&RootDeviceControlMutex, FALSE);
}
/*
IOCTL_STORAGE_GET_DEVICE_NUMBER 0x002D1080
IOCTL_STORAGE_GET_HOTPLUG_INFO 0x002D0C14
IOCTL_STORAGE_QUERY_PROPERTY 0x002D1400
*/
NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp)
{
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp);
switch (irpSp->Parameters.DeviceIoControl.IoControlCode)
{
case IOCTL_MOUNTDEV_QUERY_DEVICE_NAME:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_MOUNTDEV_QUERY_DEVICE_NAME)\n");
if (!ValidateIOBufferSize (Irp, sizeof (MOUNTDEV_NAME), ValidateOutput))
{
Irp->IoStatus.Information = sizeof (MOUNTDEV_NAME);
Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW;
}
else
{
ULONG outLength;
UNICODE_STRING ntUnicodeString;
WCHAR ntName[256];
PMOUNTDEV_NAME outputBuffer = (PMOUNTDEV_NAME) Irp->AssociatedIrp.SystemBuffer;
TCGetNTNameFromNumber (ntName, sizeof(ntName),Extension->nDosDriveNo);
RtlInitUnicodeString (&ntUnicodeString, ntName);
outputBuffer->NameLength = ntUnicodeString.Length;
outLength = ntUnicodeString.Length + sizeof(USHORT);
if (irpSp->Parameters.DeviceIoControl.OutputBufferLength < outLength)
{
Irp->IoStatus.Information = sizeof (MOUNTDEV_NAME);
Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW;
break;
}
RtlCopyMemory ((PCHAR)outputBuffer->Name,ntUnicodeString.Buffer, ntUnicodeString.Length);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = outLength;
Dump ("name = %ls\n",ntName);
}
break;
case IOCTL_MOUNTDEV_QUERY_UNIQUE_ID:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_MOUNTDEV_QUERY_UNIQUE_ID)\n");
if (!ValidateIOBufferSize (Irp, sizeof (MOUNTDEV_UNIQUE_ID), ValidateOutput))
{
Irp->IoStatus.Information = sizeof (MOUNTDEV_UNIQUE_ID);
Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW;
}
else
{
ULONG outLength;
UCHAR volId[128], tmp[] = { 0,0 };
PMOUNTDEV_UNIQUE_ID outputBuffer = (PMOUNTDEV_UNIQUE_ID) Irp->AssociatedIrp.SystemBuffer;
RtlStringCbCopyA (volId, sizeof(volId),TC_UNIQUE_ID_PREFIX);
tmp[0] = 'A' + (UCHAR) Extension->nDosDriveNo;
RtlStringCbCatA (volId, sizeof(volId),tmp);
outputBuffer->UniqueIdLength = (USHORT) strlen (volId);
outLength = (ULONG) (strlen (volId) + sizeof (USHORT));
if (irpSp->Parameters.DeviceIoControl.OutputBufferLength < outLength)
{
Irp->IoStatus.Information = sizeof (MOUNTDEV_UNIQUE_ID);
Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW;
break;
}
RtlCopyMemory ((PCHAR)outputBuffer->UniqueId, volId, strlen (volId));
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = outLength;
Dump ("id = %s\n",volId);
}
break;
case IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME)\n");
{
ULONG outLength;
UNICODE_STRING ntUnicodeString;
WCHAR ntName[256];
PMOUNTDEV_SUGGESTED_LINK_NAME outputBuffer = (PMOUNTDEV_SUGGESTED_LINK_NAME) Irp->AssociatedIrp.SystemBuffer;
if (!ValidateIOBufferSize (Irp, sizeof (MOUNTDEV_SUGGESTED_LINK_NAME), ValidateOutput))
{
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
Irp->IoStatus.Information = 0;
break;
}
TCGetDosNameFromNumber (ntName, sizeof(ntName),Extension->nDosDriveNo, DeviceNamespaceDefault);
RtlInitUnicodeString (&ntUnicodeString, ntName);
outLength = FIELD_OFFSET(MOUNTDEV_SUGGESTED_LINK_NAME,Name) + ntUnicodeString.Length;
outputBuffer->UseOnlyIfThereAreNoOtherLinks = FALSE;
outputBuffer->NameLength = ntUnicodeString.Length;
if(irpSp->Parameters.DeviceIoControl.OutputBufferLength < outLength)
{
Irp->IoStatus.Information = sizeof (MOUNTDEV_SUGGESTED_LINK_NAME);
Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW;
break;
}
RtlCopyMemory ((PCHAR)outputBuffer->Name,ntUnicodeString.Buffer, ntUnicodeString.Length);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = outLength;
Dump ("link = %ls\n",ntName);
}
break;
case IOCTL_DISK_GET_MEDIA_TYPES:
case IOCTL_DISK_GET_DRIVE_GEOMETRY:
case IOCTL_STORAGE_GET_MEDIA_TYPES:
case IOCTL_DISK_UPDATE_DRIVE_SIZE:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_GET_DRIVE_GEOMETRY)\n");
/* Return the drive geometry for the disk. Note that we
return values which were made up to suit the disk size. */
if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY), ValidateOutput))
{
PDISK_GEOMETRY outputBuffer = (PDISK_GEOMETRY)
Irp->AssociatedIrp.SystemBuffer;
outputBuffer->MediaType = Extension->bRemovable ? RemovableMedia : FixedMedia;
outputBuffer->Cylinders.QuadPart = Extension->NumberOfCylinders;
outputBuffer->TracksPerCylinder = Extension->TracksPerCylinder;
outputBuffer->SectorsPerTrack = Extension->SectorsPerTrack;
outputBuffer->BytesPerSector = Extension->BytesPerSector;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (DISK_GEOMETRY);
}
break;
case IOCTL_DISK_GET_DRIVE_GEOMETRY_EX:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_GET_DRIVE_GEOMETRY_EX)\n");
{
ULONG minOutputSize = IsOSAtLeast (WIN_SERVER_2003)? sizeof (DISK_GEOMETRY_EX) : sizeof (DISK_GEOMETRY) + sizeof (LARGE_INTEGER);
ULONG fullOutputSize = sizeof (DISK_GEOMETRY) + sizeof (LARGE_INTEGER) + sizeof (DISK_PARTITION_INFO) + sizeof (DISK_DETECTION_INFO);
if (ValidateIOBufferSize (Irp, minOutputSize, ValidateOutput))
{
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp);
BOOL bFullBuffer = (irpSp->Parameters.DeviceIoControl.OutputBufferLength >= fullOutputSize)? TRUE : FALSE;
PDISK_GEOMETRY_EX outputBuffer = (PDISK_GEOMETRY_EX) Irp->AssociatedIrp.SystemBuffer;
outputBuffer->Geometry.MediaType = Extension->bRemovable ? RemovableMedia : FixedMedia;
outputBuffer->Geometry.Cylinders.QuadPart = Extension->NumberOfCylinders;
outputBuffer->Geometry.TracksPerCylinder = Extension->TracksPerCylinder;
outputBuffer->Geometry.SectorsPerTrack = Extension->SectorsPerTrack;
outputBuffer->Geometry.BytesPerSector = Extension->BytesPerSector;
/* add one sector to DiskLength since our partition size is DiskLength and its offset if BytesPerSector */
outputBuffer->DiskSize.QuadPart = Extension->DiskLength + Extension->BytesPerSector;
if (bFullBuffer)
{
PDISK_PARTITION_INFO pPartInfo = (PDISK_PARTITION_INFO)(((ULONG_PTR) outputBuffer) + sizeof (DISK_GEOMETRY) + sizeof (LARGE_INTEGER));
PDISK_DETECTION_INFO pDetectInfo = ((PDISK_DETECTION_INFO)((((ULONG_PTR) pPartInfo) + sizeof (DISK_PARTITION_INFO))));
pPartInfo->SizeOfPartitionInfo = sizeof (DISK_PARTITION_INFO);
pPartInfo->PartitionStyle = PARTITION_STYLE_MBR;
pPartInfo->Mbr.Signature = GetCrc32((unsigned char*) &(Extension->UniqueVolumeId), 4);
pDetectInfo->SizeOfDetectInfo = sizeof (DISK_DETECTION_INFO);
Irp->IoStatus.Information = fullOutputSize;
}
else
{
if (irpSp->Parameters.DeviceIoControl.OutputBufferLength >= sizeof (DISK_GEOMETRY_EX))
Irp->IoStatus.Information = sizeof (DISK_GEOMETRY_EX);
else
Irp->IoStatus.Information = minOutputSize;
}
Irp->IoStatus.Status = STATUS_SUCCESS;
}
}
break;
case IOCTL_STORAGE_GET_MEDIA_TYPES_EX:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_STORAGE_GET_MEDIA_TYPES_EX)\n");
if (ValidateIOBufferSize (Irp, sizeof (GET_MEDIA_TYPES), ValidateOutput))
{
PGET_MEDIA_TYPES outputBuffer = (PGET_MEDIA_TYPES)
Irp->AssociatedIrp.SystemBuffer;
PDEVICE_MEDIA_INFO mediaInfo = &outputBuffer->MediaInfo[0];
outputBuffer->DeviceType = FILE_DEVICE_DISK;
outputBuffer->MediaInfoCount = 1;
if (Extension->bRemovable)
{
mediaInfo->DeviceSpecific.RemovableDiskInfo.NumberMediaSides = 1;
if (Extension->bReadOnly)
mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaCharacteristics = (MEDIA_CURRENTLY_MOUNTED | MEDIA_READ_ONLY | MEDIA_WRITE_PROTECTED);
else
mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaCharacteristics = (MEDIA_CURRENTLY_MOUNTED | MEDIA_READ_WRITE);
mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaType = (STORAGE_MEDIA_TYPE) RemovableMedia;
mediaInfo->DeviceSpecific.RemovableDiskInfo.Cylinders.QuadPart = Extension->NumberOfCylinders;
mediaInfo->DeviceSpecific.RemovableDiskInfo.TracksPerCylinder = Extension->TracksPerCylinder;
mediaInfo->DeviceSpecific.RemovableDiskInfo.SectorsPerTrack = Extension->SectorsPerTrack;
mediaInfo->DeviceSpecific.RemovableDiskInfo.BytesPerSector = Extension->BytesPerSector;
}
else
{
mediaInfo->DeviceSpecific.DiskInfo.NumberMediaSides = 1;
if (Extension->bReadOnly)
mediaInfo->DeviceSpecific.DiskInfo.MediaCharacteristics = (MEDIA_CURRENTLY_MOUNTED | MEDIA_READ_ONLY | MEDIA_WRITE_PROTECTED);
else
mediaInfo->DeviceSpecific.DiskInfo.MediaCharacteristics = (MEDIA_CURRENTLY_MOUNTED | MEDIA_READ_WRITE);
mediaInfo->DeviceSpecific.DiskInfo.MediaType = (STORAGE_MEDIA_TYPE) FixedMedia;
mediaInfo->DeviceSpecific.DiskInfo.Cylinders.QuadPart = Extension->NumberOfCylinders;
mediaInfo->DeviceSpecific.DiskInfo.TracksPerCylinder = Extension->TracksPerCylinder;
mediaInfo->DeviceSpecific.DiskInfo.SectorsPerTrack = Extension->SectorsPerTrack;
mediaInfo->DeviceSpecific.DiskInfo.BytesPerSector = Extension->BytesPerSector;
}
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (GET_MEDIA_TYPES);
}
break;
case IOCTL_STORAGE_QUERY_PROPERTY:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_STORAGE_QUERY_PROPERTY)\n");
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
if (EnableExtendedIoctlSupport || Extension->TrimEnabled)
{
if (ValidateIOBufferSize (Irp, sizeof (STORAGE_PROPERTY_QUERY), ValidateInput))
{
PSTORAGE_PROPERTY_QUERY pStoragePropQuery = (PSTORAGE_PROPERTY_QUERY) Irp->AssociatedIrp.SystemBuffer;
STORAGE_QUERY_TYPE type = pStoragePropQuery->QueryType;
Dump ("IOCTL_STORAGE_QUERY_PROPERTY - PropertyId = %d, type = %d, InputBufferLength = %d, OutputBufferLength = %d\n", pStoragePropQuery->PropertyId, type, (int) irpSp->Parameters.DeviceIoControl.InputBufferLength, (int) irpSp->Parameters.DeviceIoControl.OutputBufferLength);
if (Extension->bRawDevice &&
(pStoragePropQuery->PropertyId == (STORAGE_PROPERTY_ID) StorageDeviceLBProvisioningProperty)
)
{
IO_STATUS_BLOCK IoStatus;
Dump ("ProcessVolumeDeviceControlIrp: sending IOCTL_STORAGE_QUERY_PROPERTY (%d) to device\n", (int) pStoragePropQuery->PropertyId);
Irp->IoStatus.Status = ZwDeviceIoControlFile (
Extension->hDeviceFile,
NULL,
NULL,
NULL,
&IoStatus,
IOCTL_STORAGE_QUERY_PROPERTY,
Irp->AssociatedIrp.SystemBuffer,
irpSp->Parameters.DeviceIoControl.InputBufferLength,
Irp->AssociatedIrp.SystemBuffer,
irpSp->Parameters.DeviceIoControl.OutputBufferLength);
Dump ("ProcessVolumeDeviceControlIrp: ZwDeviceIoControlFile returned 0x%.8X\n", (DWORD) Irp->IoStatus.Status);
if (Irp->IoStatus.Status == STATUS_SUCCESS)
{
Irp->IoStatus.Status = IoStatus.Status;
Irp->IoStatus.Information = IoStatus.Information;
}
}
else if ( (pStoragePropQuery->PropertyId == StorageAccessAlignmentProperty)
|| (pStoragePropQuery->PropertyId == StorageDeviceProperty)
|| (pStoragePropQuery->PropertyId == StorageAdapterProperty)
|| (pStoragePropQuery->PropertyId == StorageDeviceSeekPenaltyProperty)
|| (pStoragePropQuery->PropertyId == StorageDeviceTrimProperty)
)
{
if (type == PropertyExistsQuery)
{
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
}
else if (type == PropertyStandardQuery)
{
ULONG descriptorSize;
switch (pStoragePropQuery->PropertyId)
{
case StorageDeviceProperty:
{
Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageDeviceProperty\n");
/* Add 0x00 for NULL terminating string used as ProductId, ProductRevision, SerialNumber, VendorId */
descriptorSize = sizeof (STORAGE_DEVICE_DESCRIPTOR) + 1;
if (ValidateIOBufferSize (Irp, descriptorSize, ValidateOutput))
{
PSTORAGE_DEVICE_DESCRIPTOR outputBuffer = (PSTORAGE_DEVICE_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer;
outputBuffer->Version = sizeof(STORAGE_DEVICE_DESCRIPTOR);
outputBuffer->Size = descriptorSize;
outputBuffer->DeviceType = FILE_DEVICE_DISK;
outputBuffer->RemovableMedia = Extension->bRemovable? TRUE : FALSE;
outputBuffer->ProductIdOffset = sizeof (STORAGE_DEVICE_DESCRIPTOR);
outputBuffer->SerialNumberOffset = sizeof (STORAGE_DEVICE_DESCRIPTOR);
outputBuffer->ProductRevisionOffset = sizeof (STORAGE_DEVICE_DESCRIPTOR);
outputBuffer->VendorIdOffset = sizeof (STORAGE_DEVICE_DESCRIPTOR);
outputBuffer->BusType = BusTypeVirtual;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = descriptorSize;
}
else if (irpSp->Parameters.DeviceIoControl.OutputBufferLength == sizeof (STORAGE_DESCRIPTOR_HEADER))
{
PSTORAGE_DESCRIPTOR_HEADER outputBuffer = (PSTORAGE_DESCRIPTOR_HEADER) Irp->AssociatedIrp.SystemBuffer;
outputBuffer->Version = sizeof(STORAGE_DEVICE_DESCRIPTOR);
outputBuffer->Size = descriptorSize;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (STORAGE_DESCRIPTOR_HEADER);
}
}
break;
case StorageAdapterProperty:
{
Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageAdapterProperty\n");
descriptorSize = sizeof (STORAGE_ADAPTER_DESCRIPTOR);
if (ValidateIOBufferSize (Irp, descriptorSize, ValidateOutput))
{
PSTORAGE_ADAPTER_DESCRIPTOR outputBuffer = (PSTORAGE_ADAPTER_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer;
outputBuffer->Version = sizeof(STORAGE_ADAPTER_DESCRIPTOR);
outputBuffer->Size = descriptorSize;
outputBuffer->MaximumTransferLength = Extension->HostMaximumTransferLength;
outputBuffer->MaximumPhysicalPages = Extension->HostMaximumPhysicalPages;
outputBuffer->AlignmentMask = Extension->HostAlignmentMask;
outputBuffer->BusType = BusTypeVirtual;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = descriptorSize;
}
else if (irpSp->Parameters.DeviceIoControl.OutputBufferLength == sizeof (STORAGE_DESCRIPTOR_HEADER))
{
PSTORAGE_DESCRIPTOR_HEADER outputBuffer = (PSTORAGE_DESCRIPTOR_HEADER) Irp->AssociatedIrp.SystemBuffer;
outputBuffer->Version = sizeof(STORAGE_ADAPTER_DESCRIPTOR);
outputBuffer->Size = descriptorSize;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (STORAGE_DESCRIPTOR_HEADER);
}
}
break;
case StorageAccessAlignmentProperty:
{
Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageAccessAlignmentProperty\n");
if (ValidateIOBufferSize (Irp, sizeof (STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR), ValidateOutput))
{
PSTORAGE_ACCESS_ALIGNMENT_DESCRIPTOR outputBuffer = (PSTORAGE_ACCESS_ALIGNMENT_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer;
outputBuffer->Version = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR);
outputBuffer->Size = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR);
outputBuffer->BytesPerLogicalSector = Extension->BytesPerSector;
outputBuffer->BytesPerPhysicalSector = Extension->HostBytesPerPhysicalSector;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR);
}
else if (irpSp->Parameters.DeviceIoControl.OutputBufferLength == sizeof (STORAGE_DESCRIPTOR_HEADER))
{
PSTORAGE_DESCRIPTOR_HEADER outputBuffer = (PSTORAGE_DESCRIPTOR_HEADER) Irp->AssociatedIrp.SystemBuffer;
outputBuffer->Version = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR);
outputBuffer->Size = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (STORAGE_DESCRIPTOR_HEADER);
}
}
break;
case StorageDeviceSeekPenaltyProperty:
{
Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageDeviceSeekPenaltyProperty\n");
if (ValidateIOBufferSize (Irp, sizeof (DEVICE_SEEK_PENALTY_DESCRIPTOR), ValidateOutput))
{
PDEVICE_SEEK_PENALTY_DESCRIPTOR outputBuffer = (PDEVICE_SEEK_PENALTY_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer;
Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageDeviceSeekPenaltyProperty: set IncursSeekPenalty to %s\n", Extension->IncursSeekPenalty? "TRUE" : "FALSE");
outputBuffer->Version = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR);
outputBuffer->Size = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR);
outputBuffer->IncursSeekPenalty = (BOOLEAN) Extension->IncursSeekPenalty;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (DEVICE_SEEK_PENALTY_DESCRIPTOR);
}
else if (irpSp->Parameters.DeviceIoControl.OutputBufferLength == sizeof (STORAGE_DESCRIPTOR_HEADER))
{
PSTORAGE_DESCRIPTOR_HEADER outputBuffer = (PSTORAGE_DESCRIPTOR_HEADER) Irp->AssociatedIrp.SystemBuffer;
outputBuffer->Version = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR);
outputBuffer->Size = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (STORAGE_DESCRIPTOR_HEADER);
}
}
break;
case StorageDeviceTrimProperty:
{
Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageDeviceTrimProperty\n");
if (ValidateIOBufferSize (Irp, sizeof (DEVICE_TRIM_DESCRIPTOR), ValidateOutput))
{
PDEVICE_TRIM_DESCRIPTOR outputBuffer = (PDEVICE_TRIM_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer;
Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageDeviceTrimProperty: set TrimEnabled to %s\n", Extension->TrimEnabled? "TRUE" : "FALSE");
outputBuffer->Version = sizeof(DEVICE_TRIM_DESCRIPTOR);
outputBuffer->Size = sizeof(DEVICE_TRIM_DESCRIPTOR);
outputBuffer->TrimEnabled = (BOOLEAN) Extension->TrimEnabled;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (DEVICE_TRIM_DESCRIPTOR);
}
else if (irpSp->Parameters.DeviceIoControl.OutputBufferLength == sizeof (STORAGE_DESCRIPTOR_HEADER))
{
PSTORAGE_DESCRIPTOR_HEADER outputBuffer = (PSTORAGE_DESCRIPTOR_HEADER) Irp->AssociatedIrp.SystemBuffer;
outputBuffer->Version = sizeof(DEVICE_TRIM_DESCRIPTOR);
outputBuffer->Size = sizeof(DEVICE_TRIM_DESCRIPTOR);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (STORAGE_DESCRIPTOR_HEADER);
}
}
break;
}
}
}
}
}
break;
case IOCTL_DISK_GET_PARTITION_INFO:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_GET_PARTITION_INFO)\n");
if (ValidateIOBufferSize (Irp, sizeof (PARTITION_INFORMATION), ValidateOutput))
{
PPARTITION_INFORMATION outputBuffer = (PPARTITION_INFORMATION)
Irp->AssociatedIrp.SystemBuffer;
outputBuffer->PartitionType = Extension->PartitionType;
outputBuffer->BootIndicator = FALSE;
outputBuffer->RecognizedPartition = TRUE;
outputBuffer->RewritePartition = FALSE;
outputBuffer->StartingOffset.QuadPart = Extension->BytesPerSector;
outputBuffer->PartitionLength.QuadPart= Extension->DiskLength;
outputBuffer->PartitionNumber = 1;
outputBuffer->HiddenSectors = 0;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (PARTITION_INFORMATION);
}
break;
case IOCTL_DISK_GET_PARTITION_INFO_EX:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_GET_PARTITION_INFO_EX)\n");
if (ValidateIOBufferSize (Irp, sizeof (PARTITION_INFORMATION_EX), ValidateOutput))
{
PPARTITION_INFORMATION_EX outputBuffer = (PPARTITION_INFORMATION_EX) Irp->AssociatedIrp.SystemBuffer;
outputBuffer->PartitionStyle = PARTITION_STYLE_MBR;
outputBuffer->RewritePartition = FALSE;
outputBuffer->StartingOffset.QuadPart = Extension->BytesPerSector;
outputBuffer->PartitionLength.QuadPart= Extension->DiskLength;
outputBuffer->PartitionNumber = 1;
outputBuffer->Mbr.PartitionType = Extension->PartitionType;
outputBuffer->Mbr.BootIndicator = FALSE;
outputBuffer->Mbr.RecognizedPartition = TRUE;
outputBuffer->Mbr.HiddenSectors = 0;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (PARTITION_INFORMATION_EX);
}
break;
case IOCTL_DISK_GET_DRIVE_LAYOUT:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_GET_DRIVE_LAYOUT)\n");
if (ValidateIOBufferSize (Irp, sizeof (DRIVE_LAYOUT_INFORMATION), ValidateOutput))
{
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp);
BOOL bFullBuffer = (irpSp->Parameters.DeviceIoControl.OutputBufferLength >= (sizeof (DRIVE_LAYOUT_INFORMATION) + 3*sizeof(PARTITION_INFORMATION)))? TRUE : FALSE;
PDRIVE_LAYOUT_INFORMATION outputBuffer = (PDRIVE_LAYOUT_INFORMATION)
Irp->AssociatedIrp.SystemBuffer;
outputBuffer->PartitionCount = bFullBuffer? 4 : 1;
outputBuffer->Signature = GetCrc32((unsigned char*) &(Extension->UniqueVolumeId), 4);
outputBuffer->PartitionEntry->PartitionType = Extension->PartitionType;
outputBuffer->PartitionEntry->BootIndicator = FALSE;
outputBuffer->PartitionEntry->RecognizedPartition = TRUE;
outputBuffer->PartitionEntry->RewritePartition = FALSE;
outputBuffer->PartitionEntry->StartingOffset.QuadPart = Extension->BytesPerSector;
outputBuffer->PartitionEntry->PartitionLength.QuadPart = Extension->DiskLength;
outputBuffer->PartitionEntry->PartitionNumber = 1;
outputBuffer->PartitionEntry->HiddenSectors = 0;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (DRIVE_LAYOUT_INFORMATION);
if (bFullBuffer)
{
Irp->IoStatus.Information += 3*sizeof(PARTITION_INFORMATION);
memset (((BYTE*) Irp->AssociatedIrp.SystemBuffer) + sizeof (DRIVE_LAYOUT_INFORMATION), 0, 3*sizeof(PARTITION_INFORMATION));
}
}
break;
case IOCTL_DISK_GET_DRIVE_LAYOUT_EX:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_GET_DRIVE_LAYOUT_EX)\n");
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
if (EnableExtendedIoctlSupport)
{
if (ValidateIOBufferSize (Irp, sizeof (DRIVE_LAYOUT_INFORMATION_EX), ValidateOutput))
{
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp);
BOOL bFullBuffer = (irpSp->Parameters.DeviceIoControl.OutputBufferLength >= (sizeof (DRIVE_LAYOUT_INFORMATION_EX) + 3*sizeof(PARTITION_INFORMATION_EX)))? TRUE : FALSE;
PDRIVE_LAYOUT_INFORMATION_EX outputBuffer = (PDRIVE_LAYOUT_INFORMATION_EX)
Irp->AssociatedIrp.SystemBuffer;
outputBuffer->PartitionCount = bFullBuffer? 4 : 1;
outputBuffer->PartitionStyle = PARTITION_STYLE_MBR;
outputBuffer->Mbr.Signature = GetCrc32((unsigned char*) &(Extension->UniqueVolumeId), 4);
outputBuffer->PartitionEntry->PartitionStyle = PARTITION_STYLE_MBR;
outputBuffer->PartitionEntry->Mbr.BootIndicator = FALSE;
outputBuffer->PartitionEntry->Mbr.RecognizedPartition = TRUE;
outputBuffer->PartitionEntry->RewritePartition = FALSE;
outputBuffer->PartitionEntry->StartingOffset.QuadPart = Extension->BytesPerSector;
outputBuffer->PartitionEntry->PartitionLength.QuadPart = Extension->DiskLength;
outputBuffer->PartitionEntry->PartitionNumber = 1;
outputBuffer->PartitionEntry->Mbr.HiddenSectors = 0;
outputBuffer->PartitionEntry->Mbr.PartitionType = Extension->PartitionType;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (DRIVE_LAYOUT_INFORMATION_EX);
if (bFullBuffer)
{
Irp->IoStatus.Information += 3*sizeof(PARTITION_INFORMATION_EX);
}
}
}
break;
case IOCTL_DISK_GET_LENGTH_INFO:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_GET_LENGTH_INFO)\n");
if (!ValidateIOBufferSize (Irp, sizeof (GET_LENGTH_INFORMATION), ValidateOutput))
{
Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW;
Irp->IoStatus.Information = sizeof (GET_LENGTH_INFORMATION);
}
else
{
PGET_LENGTH_INFORMATION outputBuffer = (PGET_LENGTH_INFORMATION) Irp->AssociatedIrp.SystemBuffer;
outputBuffer->Length.QuadPart = Extension->DiskLength;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (GET_LENGTH_INFORMATION);
}
break;
case IOCTL_DISK_VERIFY:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_VERIFY)\n");
if (ValidateIOBufferSize (Irp, sizeof (VERIFY_INFORMATION), ValidateInput))
{
HRESULT hResult;
ULONGLONG ullStartingOffset, ullNewOffset, ullEndOffset;
PVERIFY_INFORMATION pVerifyInformation;
pVerifyInformation = (PVERIFY_INFORMATION) Irp->AssociatedIrp.SystemBuffer;
ullStartingOffset = (ULONGLONG) pVerifyInformation->StartingOffset.QuadPart;
hResult = ULongLongAdd(ullStartingOffset,
(ULONGLONG) Extension->cryptoInfo->hiddenVolume ? Extension->cryptoInfo->hiddenVolumeOffset : Extension->cryptoInfo->volDataAreaOffset,
&ullNewOffset);
if (hResult != S_OK)
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
else if (S_OK != ULongLongAdd(ullStartingOffset, (ULONGLONG) pVerifyInformation->Length, &ullEndOffset))
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
else if (ullEndOffset > (ULONGLONG) Extension->DiskLength)
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
else
{
IO_STATUS_BLOCK ioStatus;
PVOID buffer = TCalloc (max (pVerifyInformation->Length, PAGE_SIZE));
if (!buffer)
{
Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
}
else
{
LARGE_INTEGER offset = pVerifyInformation->StartingOffset;
offset.QuadPart = ullNewOffset;
Irp->IoStatus.Status = ZwReadFile (Extension->hDeviceFile, NULL, NULL, NULL, &ioStatus, buffer, pVerifyInformation->Length, &offset, NULL);
TCfree (buffer);
if (NT_SUCCESS (Irp->IoStatus.Status) && ioStatus.Information != pVerifyInformation->Length)
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
}
}
Irp->IoStatus.Information = 0;
}
break;
case IOCTL_DISK_CHECK_VERIFY:
case IOCTL_STORAGE_CHECK_VERIFY:
case IOCTL_STORAGE_CHECK_VERIFY2:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_STORAGE_CHECK_VERIFY)\n");
{
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
if (irpSp->Parameters.DeviceIoControl.OutputBufferLength >= sizeof (ULONG))
{
*((ULONG *) Irp->AssociatedIrp.SystemBuffer) = 0;
Irp->IoStatus.Information = sizeof (ULONG);
}
}
break;
case IOCTL_DISK_IS_WRITABLE:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_IS_WRITABLE)\n");
{
if (Extension->bReadOnly)
Irp->IoStatus.Status = STATUS_MEDIA_WRITE_PROTECTED;
else
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
}
break;
case IOCTL_VOLUME_ONLINE:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_VOLUME_ONLINE)\n");
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
break;
case IOCTL_VOLUME_POST_ONLINE:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_VOLUME_POST_ONLINE)\n");
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
if (EnableExtendedIoctlSupport)
{
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
}
break;
case IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS)\n");
// Vista's, Windows 8.1 and later filesystem defragmenter fails if IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS does not succeed.
if (!(OsMajorVersion == 6 && OsMinorVersion == 0)
&& !(IsOSAtLeast (WIN_8_1) && AllowWindowsDefrag && Extension->bRawDevice)
)
{
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
}
else if (ValidateIOBufferSize (Irp, sizeof (VOLUME_DISK_EXTENTS), ValidateOutput))
{
VOLUME_DISK_EXTENTS *extents = (VOLUME_DISK_EXTENTS *) Irp->AssociatedIrp.SystemBuffer;
if (IsOSAtLeast (WIN_8_1))
{
// Windows 10 filesystem defragmenter works only if we report an extent with a real disk number
// So in the case of a VeraCrypt disk based volume, we use the disk number
// of the underlaying physical disk and we report a single extent
extents->NumberOfDiskExtents = 1;
extents->Extents[0].DiskNumber = Extension->DeviceNumber;
extents->Extents[0].StartingOffset.QuadPart = Extension->BytesPerSector;
extents->Extents[0].ExtentLength.QuadPart = Extension->DiskLength;
}
else
{
// Vista: No extent data can be returned as this is not a physical drive.
memset (extents, 0, sizeof (*extents));
extents->NumberOfDiskExtents = 0;
}
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (*extents);
}
break;
case IOCTL_STORAGE_READ_CAPACITY:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_STORAGE_READ_CAPACITY)\n");
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
if (EnableExtendedIoctlSupport)
{
if (ValidateIOBufferSize (Irp, sizeof (STORAGE_READ_CAPACITY), ValidateOutput))
{
STORAGE_READ_CAPACITY *capacity = (STORAGE_READ_CAPACITY *) Irp->AssociatedIrp.SystemBuffer;
capacity->Version = sizeof (STORAGE_READ_CAPACITY);
capacity->Size = sizeof (STORAGE_READ_CAPACITY);
capacity->BlockLength = Extension->BytesPerSector;
capacity->NumberOfBlocks.QuadPart = (Extension->DiskLength / Extension->BytesPerSector) + 1;
capacity->DiskLength.QuadPart = Extension->DiskLength + Extension->BytesPerSector;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (STORAGE_READ_CAPACITY);
}
}
break;
/*case IOCTL_STORAGE_GET_DEVICE_NUMBER:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_STORAGE_GET_DEVICE_NUMBER)\n");
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
if (EnableExtendedIoctlSupport)
{
if (ValidateIOBufferSize (Irp, sizeof (STORAGE_DEVICE_NUMBER), ValidateOutput))
{
STORAGE_DEVICE_NUMBER *storage = (STORAGE_DEVICE_NUMBER *) Irp->AssociatedIrp.SystemBuffer;
storage->DeviceType = FILE_DEVICE_DISK;
storage->DeviceNumber = (ULONG) -1;
storage->PartitionNumber = 1;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (STORAGE_DEVICE_NUMBER);
}
}
break;*/
case IOCTL_STORAGE_GET_HOTPLUG_INFO:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_STORAGE_GET_HOTPLUG_INFO)\n");
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
if (EnableExtendedIoctlSupport)
{
if (ValidateIOBufferSize (Irp, sizeof (STORAGE_HOTPLUG_INFO), ValidateOutput))
{
STORAGE_HOTPLUG_INFO *info = (STORAGE_HOTPLUG_INFO *) Irp->AssociatedIrp.SystemBuffer;
info->Size = sizeof (STORAGE_HOTPLUG_INFO);
info->MediaRemovable = Extension->bRemovable? TRUE : FALSE;
info->MediaHotplug = FALSE;
info->DeviceHotplug = FALSE;
info->WriteCacheEnableOverride = FALSE;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (STORAGE_HOTPLUG_INFO);
}
}
break;
case IOCTL_VOLUME_IS_DYNAMIC:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_VOLUME_IS_DYNAMIC)\n");
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
if (EnableExtendedIoctlSupport)
{
if (ValidateIOBufferSize (Irp, sizeof (BOOLEAN), ValidateOutput))
{
BOOLEAN *pbDynamic = (BOOLEAN*) Irp->AssociatedIrp.SystemBuffer;
*pbDynamic = FALSE;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (BOOLEAN);
}
}
break;
case IOCTL_DISK_IS_CLUSTERED:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_IS_CLUSTERED)\n");
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
if (EnableExtendedIoctlSupport)
{
if (ValidateIOBufferSize (Irp, sizeof (BOOLEAN), ValidateOutput))
{
BOOLEAN *pbIsClustered = (BOOLEAN*) Irp->AssociatedIrp.SystemBuffer;
*pbIsClustered = FALSE;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (BOOLEAN);
}
}
break;
case IOCTL_VOLUME_GET_GPT_ATTRIBUTES:
Dump ("ProcessVolumeDeviceControlIrp (IOCTL_VOLUME_GET_GPT_ATTRIBUTES)\n");
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
if (EnableExtendedIoctlSupport)
{
if (ValidateIOBufferSize (Irp, sizeof (VOLUME_GET_GPT_ATTRIBUTES_INFORMATION), ValidateOutput))
{
VOLUME_GET_GPT_ATTRIBUTES_INFORMATION *pGptAttr = (VOLUME_GET_GPT_ATTRIBUTES_INFORMATION*) Irp->AssociatedIrp.SystemBuffer;
pGptAttr->GptAttributes = 0; // we are MBR not GPT
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (VOLUME_GET_GPT_ATTRIBUTES_INFORMATION);
}
}
break;
case IOCTL_UNKNOWN_WINDOWS10_EFS_ACCESS:
// This undocumented IOCTL is sent when handling EFS data
// We must return success otherwise EFS operations fail
Dump ("ProcessVolumeDeviceControlIrp (unknown IOCTL 0x%.8X, OutputBufferLength = %d). Returning fake success\n", irpSp->Parameters.DeviceIoControl.IoControlCode, (int) irpSp->Parameters.DeviceIoControl.OutputBufferLength);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
break;
case IOCTL_DISK_UPDATE_PROPERTIES:
Dump ("ProcessVolumeDeviceControlIrp: returning STATUS_SUCCESS for IOCTL_DISK_UPDATE_PROPERTIES\n");
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
break;
case IOCTL_DISK_MEDIA_REMOVAL:
case IOCTL_STORAGE_MEDIA_REMOVAL:
Dump ("ProcessVolumeDeviceControlIrp: returning STATUS_SUCCESS for %ls\n", TCTranslateCode (irpSp->Parameters.DeviceIoControl.IoControlCode));
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
break;
case IOCTL_DISK_GET_CLUSTER_INFO:
Dump ("ProcessVolumeDeviceControlIrp: returning STATUS_NOT_SUPPORTED for %ls\n", TCTranslateCode (irpSp->Parameters.DeviceIoControl.IoControlCode));
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
if (EnableExtendedIoctlSupport)
{
Irp->IoStatus.Status = STATUS_NOT_SUPPORTED;
Irp->IoStatus.Information = 0;
}
break;
case IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES:
Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES\n");
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
if (Extension->bRawDevice && Extension->TrimEnabled)
{
if (ValidateIOBufferSize (Irp, sizeof (DEVICE_MANAGE_DATA_SET_ATTRIBUTES), ValidateInput))
{
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp);
DWORD inputLength = irpSp->Parameters.DeviceIoControl.InputBufferLength;
PDEVICE_MANAGE_DATA_SET_ATTRIBUTES pInputAttrs = (PDEVICE_MANAGE_DATA_SET_ATTRIBUTES) Irp->AssociatedIrp.SystemBuffer;
DEVICE_DATA_MANAGEMENT_SET_ACTION action = pInputAttrs->Action;
BOOL bEntireSet = pInputAttrs->Flags & DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE? TRUE : FALSE;
ULONGLONG minSizedataSet = (ULONGLONG) pInputAttrs->DataSetRangesOffset + (ULONGLONG) pInputAttrs->DataSetRangesLength;
ULONGLONG minSizeParameter = (ULONGLONG) pInputAttrs->ParameterBlockOffset + (ULONGLONG) pInputAttrs->ParameterBlockLength;
ULONGLONG minSizeGeneric = sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES) + (ULONGLONG) pInputAttrs->ParameterBlockLength + (ULONGLONG) pInputAttrs->DataSetRangesLength;
PDEVICE_MANAGE_DATA_SET_ATTRIBUTES pNewSetAttrs = NULL;
ULONG ulNewInputLength = 0;
BOOL bForwardIoctl = FALSE;
if (inputLength >= minSizeGeneric && inputLength >= minSizedataSet && inputLength >= minSizeParameter)
{
if (bEntireSet)
{
if (minSizedataSet)
{
Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE set but data set range specified=> Error.\n");
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
Irp->IoStatus.Information = 0;
}
else
{
DWORD dwDataSetOffset = ALIGN_VALUE (inputLength, sizeof(DEVICE_DATA_SET_RANGE));
DWORD dwDataSetLength = sizeof(DEVICE_DATA_SET_RANGE);
Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE set. Setting data range to all volume.\n");
ulNewInputLength = dwDataSetOffset + dwDataSetLength;
pNewSetAttrs = (PDEVICE_MANAGE_DATA_SET_ATTRIBUTES) TCalloc (ulNewInputLength);
if (pNewSetAttrs)
{
PDEVICE_DATA_SET_RANGE pRange = (PDEVICE_DATA_SET_RANGE) (((unsigned char*) pNewSetAttrs) + dwDataSetOffset);
memcpy (pNewSetAttrs, pInputAttrs, inputLength);
pRange->StartingOffset = (ULONGLONG) Extension->cryptoInfo->hiddenVolume ? Extension->cryptoInfo->hiddenVolumeOffset : Extension->cryptoInfo->volDataAreaOffset;
pRange->LengthInBytes = Extension->DiskLength;
pNewSetAttrs->Size = sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES);
pNewSetAttrs->Action = action;
pNewSetAttrs->Flags = pInputAttrs->Flags & (~DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE);
pNewSetAttrs->ParameterBlockOffset = pInputAttrs->ParameterBlockOffset;
pNewSetAttrs->ParameterBlockLength = pInputAttrs->ParameterBlockLength;
pNewSetAttrs->DataSetRangesOffset = dwDataSetOffset;
pNewSetAttrs->DataSetRangesLength = dwDataSetLength;
bForwardIoctl = TRUE;
}
else
{
Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - Failed to allocate memory.\n");
Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
Irp->IoStatus.Information = 0;
}
}
}
else
{
Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - creating new data set range from input range.\n");
ulNewInputLength = inputLength;
pNewSetAttrs = (PDEVICE_MANAGE_DATA_SET_ATTRIBUTES) TCalloc (inputLength);
if (pNewSetAttrs)
{
PDEVICE_DATA_SET_RANGE pNewRanges = (PDEVICE_DATA_SET_RANGE) (((unsigned char*) pNewSetAttrs) + pInputAttrs->DataSetRangesOffset);
PDEVICE_DATA_SET_RANGE pInputRanges = (PDEVICE_DATA_SET_RANGE) (((unsigned char*) pInputAttrs) + pInputAttrs->DataSetRangesOffset);
DWORD dwInputRangesCount = 0, dwNewRangesCount = 0, i;
ULONGLONG ullStartingOffset, ullNewOffset, ullEndOffset;
HRESULT hResult;
memcpy (pNewSetAttrs, pInputAttrs, inputLength);
dwInputRangesCount = pInputAttrs->DataSetRangesLength / sizeof(DEVICE_DATA_SET_RANGE);
for (i = 0; i < dwInputRangesCount; i++)
{
ullStartingOffset = (ULONGLONG) pInputRanges[i].StartingOffset;
hResult = ULongLongAdd(ullStartingOffset,
(ULONGLONG) Extension->cryptoInfo->hiddenVolume ? Extension->cryptoInfo->hiddenVolumeOffset : Extension->cryptoInfo->volDataAreaOffset,
&ullNewOffset);
if (hResult != S_OK)
continue;
else if (S_OK != ULongLongAdd(ullStartingOffset, (ULONGLONG) pInputRanges[i].LengthInBytes, &ullEndOffset))
continue;
else if (ullEndOffset > (ULONGLONG) Extension->DiskLength)
continue;
else if (ullNewOffset > 0)
{
pNewRanges[dwNewRangesCount].StartingOffset = (LONGLONG) ullNewOffset;
pNewRanges[dwNewRangesCount].LengthInBytes = pInputRanges[i].LengthInBytes;
dwNewRangesCount++;
}
}
Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - %d valid range processed from %d range in input.\n", (int) dwNewRangesCount, (int) dwInputRangesCount);
pNewSetAttrs->DataSetRangesLength = dwNewRangesCount * sizeof (DEVICE_DATA_SET_RANGE);
bForwardIoctl = TRUE;
}
else
{
Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - Failed to allocate memory.\n");
Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
Irp->IoStatus.Information = 0;
}
}
}
else
{
Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - buffer containing DEVICE_MANAGE_DATA_SET_ATTRIBUTES has invalid length.\n");
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
Irp->IoStatus.Information = 0;
}
if (bForwardIoctl)
{
if (action == DeviceDsmAction_Trim)
{
Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_Trim.\n");
if (Extension->cryptoInfo->hiddenVolume || !AllowTrimCommand)
{
Dump ("ProcessVolumeDeviceControlIrp: TRIM command filtered\n");
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
}
else
{
IO_STATUS_BLOCK IoStatus;
Dump ("ProcessVolumeDeviceControlIrp: sending TRIM to device\n");
Irp->IoStatus.Status = ZwDeviceIoControlFile (
Extension->hDeviceFile,
NULL,
NULL,
NULL,
&IoStatus,
IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES,
(PVOID) pNewSetAttrs,
ulNewInputLength,
NULL,
0);
Dump ("ProcessVolumeDeviceControlIrp: ZwDeviceIoControlFile returned 0x%.8X\n", (DWORD) Irp->IoStatus.Status);
if (Irp->IoStatus.Status == STATUS_SUCCESS)
{
Irp->IoStatus.Status = IoStatus.Status;
Irp->IoStatus.Information = IoStatus.Information;
}
else
Irp->IoStatus.Information = 0;
}
}
else
{
switch (action)
{
case DeviceDsmAction_Notification: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_Notification\n"); break;
case DeviceDsmAction_OffloadRead: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_OffloadRead\n"); break;
case DeviceDsmAction_OffloadWrite: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_OffloadWrite\n"); break;
case DeviceDsmAction_Allocation: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_Allocation\n"); break;
case DeviceDsmAction_Scrub: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_Scrub\n"); break;
case DeviceDsmAction_DrtQuery: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_DrtQuery\n"); break;
case DeviceDsmAction_DrtClear: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_DrtClear\n"); break;
case DeviceDsmAction_DrtDisable: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_DrtDisable\n"); break;
default: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - unknown action %d\n", (int) action); break;
}
}
}
if (pNewSetAttrs)
TCfree (pNewSetAttrs);
}
}
#if defined (DEBUG) || defined (DEBUG_TRACE)
else
Dump ("ProcessVolumeDeviceControlIrp: returning STATUS_INVALID_DEVICE_REQUEST for IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES\n");
#endif
break;
case IOCTL_STORAGE_CHECK_PRIORITY_HINT_SUPPORT:
case IOCTL_VOLUME_QUERY_ALLOCATION_HINT:
case FT_BALANCED_READ_MODE:
case IOCTL_STORAGE_GET_DEVICE_NUMBER:
case IOCTL_MOUNTDEV_LINK_CREATED:
Dump ("ProcessVolumeDeviceControlIrp: returning STATUS_INVALID_DEVICE_REQUEST for %ls\n", TCTranslateCode (irpSp->Parameters.DeviceIoControl.IoControlCode));
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
break;
default:
Dump ("ProcessVolumeDeviceControlIrp (unknown code 0x%.8X)\n", irpSp->Parameters.DeviceIoControl.IoControlCode);
return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0);
}
#if defined(DEBUG) || defined (DEBG_TRACE)
if (!NT_SUCCESS (Irp->IoStatus.Status))
{
Dump ("IOCTL error 0x%08x (0x%x %d)\n",
Irp->IoStatus.Status,
(int) (irpSp->Parameters.DeviceIoControl.IoControlCode >> 16),
(int) ((irpSp->Parameters.DeviceIoControl.IoControlCode & 0x1FFF) >> 2));
}
#endif
return TCCompleteDiskIrp (Irp, Irp->IoStatus.Status, Irp->IoStatus.Information);
}
NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp)
{
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp);
NTSTATUS ntStatus;
switch (irpSp->Parameters.DeviceIoControl.IoControlCode)
{
case TC_IOCTL_GET_DRIVER_VERSION:
case TC_IOCTL_LEGACY_GET_DRIVER_VERSION:
if (ValidateIOBufferSize (Irp, sizeof (LONG), ValidateOutput))
{
LONG tmp = VERSION_NUM;
memcpy (Irp->AssociatedIrp.SystemBuffer, &tmp, 4);
Irp->IoStatus.Information = sizeof (LONG);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_GET_DEVICE_REFCOUNT:
if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput))
{
*(int *) Irp->AssociatedIrp.SystemBuffer = DeviceObject->ReferenceCount;
Irp->IoStatus.Information = sizeof (int);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED:
if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput))
{
LONG deviceObjectCount = 0;
*(int *) Irp->AssociatedIrp.SystemBuffer = DriverUnloadDisabled;
if (IoEnumerateDeviceObjectList (TCDriverObject, NULL, 0, &deviceObjectCount) == STATUS_BUFFER_TOO_SMALL && deviceObjectCount > 1)
*(int *) Irp->AssociatedIrp.SystemBuffer = TRUE;
Irp->IoStatus.Information = sizeof (int);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_IS_ANY_VOLUME_MOUNTED:
if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput))
{
int drive;
*(int *) Irp->AssociatedIrp.SystemBuffer = 0;
for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive)
{
if (GetVirtualVolumeDeviceObject (drive))
{
*(int *) Irp->AssociatedIrp.SystemBuffer = 1;
break;
}
}
if (IsBootDriveMounted())
*(int *) Irp->AssociatedIrp.SystemBuffer = 1;
Irp->IoStatus.Information = sizeof (int);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_OPEN_TEST:
{
OPEN_TEST_STRUCT *opentest = (OPEN_TEST_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
OBJECT_ATTRIBUTES ObjectAttributes;
HANDLE NtFileHandle;
UNICODE_STRING FullFileName;
IO_STATUS_BLOCK IoStatus;
LARGE_INTEGER offset;
ACCESS_MASK access = FILE_READ_ATTRIBUTES;
if (!ValidateIOBufferSize (Irp, sizeof (OPEN_TEST_STRUCT), ValidateInputOutput))
break;
EnsureNullTerminatedString (opentest->wszFileName, sizeof (opentest->wszFileName));
RtlInitUnicodeString (&FullFileName, opentest->wszFileName);
InitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);
if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bComputeVolumeIDs)
access |= FILE_READ_DATA;
ntStatus = ZwCreateFile (&NtFileHandle,
SYNCHRONIZE | access, &ObjectAttributes, &IoStatus, NULL,
0, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0);
if (NT_SUCCESS (ntStatus))
{
opentest->TCBootLoaderDetected = FALSE;
opentest->FilesystemDetected = FALSE;
memset (opentest->VolumeIDComputed, 0, sizeof (opentest->VolumeIDComputed));
memset (opentest->volumeIDs, 0, sizeof (opentest->volumeIDs));
if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bComputeVolumeIDs)
{
byte *readBuffer = TCalloc (TC_MAX_VOLUME_SECTOR_SIZE);
if (!readBuffer)
{
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
}
else
{
if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem)
{
// Determine if the first sector contains a portion of the VeraCrypt Boot Loader
offset.QuadPart = 0;
ntStatus = ZwReadFile (NtFileHandle,
NULL,
NULL,
NULL,
&IoStatus,
readBuffer,
TC_MAX_VOLUME_SECTOR_SIZE,
&offset,
NULL);
if (NT_SUCCESS (ntStatus))
{
size_t i;
if (opentest->bDetectTCBootLoader && IoStatus.Information >= TC_SECTOR_SIZE_BIOS)
{
// Search for the string "VeraCrypt"
for (i = 0; i < TC_SECTOR_SIZE_BIOS - strlen (TC_APP_NAME); ++i)
{
if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0)
{
opentest->TCBootLoaderDetected = TRUE;
break;
}
}
}
if (opentest->DetectFilesystem && IoStatus.Information >= sizeof (int64))
{
switch (BE64 (*(uint64 *) readBuffer))
{
case 0xEB52904E54465320ULL: // NTFS
case 0xEB3C904D53444F53ULL: // FAT16/FAT32
case 0xEB58904D53444F53ULL: // FAT32
case 0xEB76904558464154ULL: // exFAT
case 0x0000005265465300ULL: // ReFS
case 0xEB58906D6B66732EULL: // FAT32 mkfs.fat
case 0xEB58906D6B646F73ULL: // FAT32 mkfs.vfat/mkdosfs
case 0xEB3C906D6B66732EULL: // FAT16/FAT12 mkfs.fat
case 0xEB3C906D6B646F73ULL: // FAT16/FAT12 mkfs.vfat/mkdosfs
opentest->FilesystemDetected = TRUE;
break;
case 0x0000000000000000ULL:
// all 512 bytes are zeroes => unencrypted filesystem like Microsoft reserved partition
if (IsAllZeroes (readBuffer + 8, TC_VOLUME_HEADER_EFFECTIVE_SIZE - 8))
opentest->FilesystemDetected = TRUE;
break;
}
}
}
}
if (opentest->bComputeVolumeIDs && (!opentest->DetectFilesystem || !opentest->FilesystemDetected))
{
int volumeType;
// Go through all volume types (e.g., normal, hidden)
for (volumeType = TC_VOLUME_TYPE_NORMAL;
volumeType < TC_VOLUME_TYPE_COUNT;
volumeType++)
{
/* Read the volume header */
switch (volumeType)
{
case TC_VOLUME_TYPE_NORMAL:
offset.QuadPart = TC_VOLUME_HEADER_OFFSET;
break;
case TC_VOLUME_TYPE_HIDDEN:
offset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET;
break;
}
ntStatus = ZwReadFile (NtFileHandle,
NULL,
NULL,
NULL,
&IoStatus,
readBuffer,
TC_MAX_VOLUME_SECTOR_SIZE,
&offset,
NULL);
if (NT_SUCCESS (ntStatus))
{
/* compute the ID of this volume: SHA-256 of the effective header */
sha256 (opentest->volumeIDs[volumeType], readBuffer, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
opentest->VolumeIDComputed[volumeType] = TRUE;
}
}
}
TCfree (readBuffer);
}
}
ZwClose (NtFileHandle);
Dump ("Open test on file %ls success.\n", opentest->wszFileName);
}
else
{
#if 0
Dump ("Open test on file %ls failed NTSTATUS 0x%08x\n", opentest->wszFileName, ntStatus);
#endif
}
Irp->IoStatus.Information = NT_SUCCESS (ntStatus) ? sizeof (OPEN_TEST_STRUCT) : 0;
Irp->IoStatus.Status = ntStatus;
}
break;
case TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG:
{
GetSystemDriveConfigurationRequest *request = (GetSystemDriveConfigurationRequest *) Irp->AssociatedIrp.SystemBuffer;
OBJECT_ATTRIBUTES ObjectAttributes;
HANDLE NtFileHandle;
UNICODE_STRING FullFileName;
IO_STATUS_BLOCK IoStatus;
LARGE_INTEGER offset;
size_t devicePathLen = 0;
if (!ValidateIOBufferSize (Irp, sizeof (GetSystemDriveConfigurationRequest), ValidateInputOutput))
break;
// check that request->DevicePath has the expected format "\\Device\\HarddiskXXX\\Partition0"
if ( !NT_SUCCESS (RtlUnalignedStringCchLengthW (request->DevicePath, TC_MAX_PATH, &devicePathLen))
|| (devicePathLen < 28) // 28 is the length of "\\Device\\Harddisk0\\Partition0" which is the minimum
|| (devicePathLen > 30) // 30 is the length of "\\Device\\Harddisk255\\Partition0" which is the maximum
|| (memcmp (request->DevicePath, L"\\Device\\Harddisk", 16 * sizeof (WCHAR)))
|| (memcmp (&request->DevicePath[devicePathLen - 11], L"\\Partition0", 11 * sizeof (WCHAR)))
)
{
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
Irp->IoStatus.Information = 0;
break;
}
EnsureNullTerminatedString (request->DevicePath, sizeof (request->DevicePath));
RtlInitUnicodeString (&FullFileName, request->DevicePath);
InitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);
ntStatus = ZwCreateFile (&NtFileHandle,
SYNCHRONIZE | GENERIC_READ, &ObjectAttributes, &IoStatus, NULL,
FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT | FILE_RANDOM_ACCESS, NULL, 0);
if (NT_SUCCESS (ntStatus))
{
byte *readBuffer = TCalloc (TC_MAX_VOLUME_SECTOR_SIZE);
if (!readBuffer)
{
Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
Irp->IoStatus.Information = 0;
}
else
{
// Determine if the first sector contains a portion of the VeraCrypt Boot Loader
offset.QuadPart = 0; // MBR
ntStatus = ZwReadFile (NtFileHandle,
NULL,
NULL,
NULL,
&IoStatus,
readBuffer,
TC_MAX_VOLUME_SECTOR_SIZE,
&offset,
NULL);
if (NT_SUCCESS (ntStatus))
{
// check that we could read all needed data
if (IoStatus.Information >= TC_SECTOR_SIZE_BIOS)
{
size_t i;
// Check for dynamic drive
request->DriveIsDynamic = FALSE;
if (readBuffer[510] == 0x55 && readBuffer[511] == 0xaa)
{
int i;
for (i = 0; i < 4; ++i)
{
if (readBuffer[446 + i * 16 + 4] == PARTITION_LDM)
{
request->DriveIsDynamic = TRUE;
break;
}
}
}
request->BootLoaderVersion = 0;
request->Configuration = 0;
request->UserConfiguration = 0;
request->CustomUserMessage[0] = 0;
// Search for the string "VeraCrypt"
for (i = 0; i < sizeof (readBuffer) - strlen (TC_APP_NAME); ++i)
{
if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0)
{
request->BootLoaderVersion = BE16 (*(uint16 *) (readBuffer + TC_BOOT_SECTOR_VERSION_OFFSET));
request->Configuration = readBuffer[TC_BOOT_SECTOR_CONFIG_OFFSET];
if (request->BootLoaderVersion != 0 && request->BootLoaderVersion <= VERSION_NUM)
{
request->UserConfiguration = readBuffer[TC_BOOT_SECTOR_USER_CONFIG_OFFSET];
memcpy (request->CustomUserMessage, readBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH);
}
break;
}
}
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (*request);
}
else
{
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
Irp->IoStatus.Information = 0;
}
}
else
{
Irp->IoStatus.Status = ntStatus;
Irp->IoStatus.Information = 0;
}
TCfree (readBuffer);
}
ZwClose (NtFileHandle);
}
else
{
Irp->IoStatus.Status = ntStatus;
Irp->IoStatus.Information = 0;
}
}
break;
case TC_IOCTL_WIPE_PASSWORD_CACHE:
WipeCache ();
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_GET_PASSWORD_CACHE_STATUS:
Irp->IoStatus.Status = cacheEmpty ? STATUS_PIPE_EMPTY : STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_SET_PORTABLE_MODE_STATUS:
if (!UserCanAccessDriveDevice())
{
Irp->IoStatus.Status = STATUS_ACCESS_DENIED;
Irp->IoStatus.Information = 0;
}
else
{
PortableMode = TRUE;
Dump ("Setting portable mode\n");
}
break;
case TC_IOCTL_GET_PORTABLE_MODE_STATUS:
Irp->IoStatus.Status = PortableMode ? STATUS_SUCCESS : STATUS_PIPE_EMPTY;
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_GET_MOUNTED_VOLUMES:
if (ValidateIOBufferSize (Irp, sizeof (MOUNT_LIST_STRUCT), ValidateOutput))
{
MOUNT_LIST_STRUCT *list = (MOUNT_LIST_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
PDEVICE_OBJECT ListDevice;
int drive;
list->ulMountedDrives = 0;
for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive)
{
PEXTENSION ListExtension;
ListDevice = GetVirtualVolumeDeviceObject (drive);
if (!ListDevice)
continue;
ListExtension = (PEXTENSION) ListDevice->DeviceExtension;
if (IsVolumeAccessibleByCurrentUser (ListExtension))
{
list->ulMountedDrives |= (1 << ListExtension->nDosDriveNo);
RtlStringCbCopyW (list->wszVolume[ListExtension->nDosDriveNo], sizeof(list->wszVolume[ListExtension->nDosDriveNo]),ListExtension->wszVolume);
RtlStringCbCopyW (list->wszLabel[ListExtension->nDosDriveNo], sizeof(list->wszLabel[ListExtension->nDosDriveNo]),ListExtension->wszLabel);
memcpy (list->volumeID[ListExtension->nDosDriveNo], ListExtension->volumeID, VOLUME_ID_SIZE);
list->diskLength[ListExtension->nDosDriveNo] = ListExtension->DiskLength;
list->ea[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->ea;
if (ListExtension->cryptoInfo->hiddenVolume)
list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_HIDDEN; // Hidden volume
else if (ListExtension->cryptoInfo->bHiddenVolProtectionAction)
list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED; // Normal/outer volume (hidden volume protected AND write already prevented)
else if (ListExtension->cryptoInfo->bProtectHiddenVolume)
list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER; // Normal/outer volume (hidden volume protected)
else
list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_NORMAL; // Normal volume
list->truecryptMode[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->bTrueCryptMode;
}
}
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (MOUNT_LIST_STRUCT);
}
break;
case TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES:
if (ValidateIOBufferSize (Irp, sizeof (uint32), ValidateOutput))
{
// Prevent the user from downgrading to versions lower than 5.0 by faking mounted volumes.
// The user could render the system unbootable by downgrading when boot encryption
// is active or being set up.
memset (Irp->AssociatedIrp.SystemBuffer, 0, irpSp->Parameters.DeviceIoControl.OutputBufferLength);
*(uint32 *) Irp->AssociatedIrp.SystemBuffer = 0xffffFFFF;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = irpSp->Parameters.DeviceIoControl.OutputBufferLength;
}
break;
case TC_IOCTL_GET_VOLUME_PROPERTIES:
if (ValidateIOBufferSize (Irp, sizeof (VOLUME_PROPERTIES_STRUCT), ValidateInputOutput))
{
VOLUME_PROPERTIES_STRUCT *prop = (VOLUME_PROPERTIES_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
PDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (prop->driveNo);
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
Irp->IoStatus.Information = 0;
if (ListDevice)
{
PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension;
if (IsVolumeAccessibleByCurrentUser (ListExtension))
{
prop->uniqueId = ListExtension->UniqueVolumeId;
RtlStringCbCopyW (prop->wszVolume, sizeof(prop->wszVolume),ListExtension->wszVolume);
RtlStringCbCopyW (prop->wszLabel, sizeof(prop->wszLabel),ListExtension->wszLabel);
memcpy (prop->volumeID, ListExtension->volumeID, VOLUME_ID_SIZE);
prop->bDriverSetLabel = ListExtension->bDriverSetLabel;
prop->diskLength = ListExtension->DiskLength;
prop->ea = ListExtension->cryptoInfo->ea;
prop->mode = ListExtension->cryptoInfo->mode;
prop->pkcs5 = ListExtension->cryptoInfo->pkcs5;
prop->pkcs5Iterations = ListExtension->cryptoInfo->noIterations;
prop->volumePim = ListExtension->cryptoInfo->volumePim;
#if 0
prop->volumeCreationTime = ListExtension->cryptoInfo->volume_creation_time;
prop->headerCreationTime = ListExtension->cryptoInfo->header_creation_time;
#endif
prop->volumeHeaderFlags = ListExtension->cryptoInfo->HeaderFlags;
prop->readOnly = ListExtension->bReadOnly;
prop->removable = ListExtension->bRemovable;
prop->partitionInInactiveSysEncScope = ListExtension->PartitionInInactiveSysEncScope;
prop->hiddenVolume = ListExtension->cryptoInfo->hiddenVolume;
if (ListExtension->cryptoInfo->bProtectHiddenVolume)
prop->hiddenVolProtection = ListExtension->cryptoInfo->bHiddenVolProtectionAction ? HIDVOL_PROT_STATUS_ACTION_TAKEN : HIDVOL_PROT_STATUS_ACTIVE;
else
prop->hiddenVolProtection = HIDVOL_PROT_STATUS_NONE;
prop->totalBytesRead = ListExtension->Queue.TotalBytesRead;
prop->totalBytesWritten = ListExtension->Queue.TotalBytesWritten;
prop->volFormatVersion = ListExtension->cryptoInfo->LegacyVolume ? TC_VOLUME_FORMAT_VERSION_PRE_6_0 : TC_VOLUME_FORMAT_VERSION;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (VOLUME_PROPERTIES_STRUCT);
}
}
}
break;
case TC_IOCTL_GET_RESOLVED_SYMLINK:
if (ValidateIOBufferSize (Irp, sizeof (RESOLVE_SYMLINK_STRUCT), ValidateInputOutput))
{
RESOLVE_SYMLINK_STRUCT *resolve = (RESOLVE_SYMLINK_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
{
NTSTATUS ntStatus;
EnsureNullTerminatedString (resolve->symLinkName, sizeof (resolve->symLinkName));
ntStatus = SymbolicLinkToTarget (resolve->symLinkName,
resolve->targetName,
sizeof (resolve->targetName));
Irp->IoStatus.Information = sizeof (RESOLVE_SYMLINK_STRUCT);
Irp->IoStatus.Status = ntStatus;
}
}
break;
case TC_IOCTL_GET_DRIVE_PARTITION_INFO:
if (ValidateIOBufferSize (Irp, sizeof (DISK_PARTITION_INFO_STRUCT), ValidateInputOutput))
{
DISK_PARTITION_INFO_STRUCT *info = (DISK_PARTITION_INFO_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
{
PARTITION_INFORMATION_EX pi;
NTSTATUS ntStatus;
EnsureNullTerminatedString (info->deviceName, sizeof (info->deviceName));
ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO_EX, NULL, 0, &pi, sizeof (pi));
if (NT_SUCCESS(ntStatus))
{
memset (&info->partInfo, 0, sizeof (info->partInfo));
info->partInfo.PartitionLength = pi.PartitionLength;
info->partInfo.PartitionNumber = pi.PartitionNumber;
info->partInfo.StartingOffset = pi.StartingOffset;
if (pi.PartitionStyle == PARTITION_STYLE_MBR)
{
info->partInfo.PartitionType = pi.Mbr.PartitionType;
info->partInfo.BootIndicator = pi.Mbr.BootIndicator;
}
info->IsGPT = pi.PartitionStyle == PARTITION_STYLE_GPT;
}
else
{
// Windows 2000 does not support IOCTL_DISK_GET_PARTITION_INFO_EX
ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO, NULL, 0, &info->partInfo, sizeof (info->partInfo));
info->IsGPT = FALSE;
}
if (!NT_SUCCESS (ntStatus))
{
GET_LENGTH_INFORMATION lengthInfo;
ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &lengthInfo, sizeof (lengthInfo));
if (NT_SUCCESS (ntStatus))
{
memset (&info->partInfo, 0, sizeof (info->partInfo));
info->partInfo.PartitionLength = lengthInfo.Length;
}
}
info->IsDynamic = FALSE;
if (NT_SUCCESS (ntStatus) && OsMajorVersion >= 6)
{
# define IOCTL_VOLUME_IS_DYNAMIC CTL_CODE(IOCTL_VOLUME_BASE, 18, METHOD_BUFFERED, FILE_ANY_ACCESS)
if (!NT_SUCCESS (TCDeviceIoControl (info->deviceName, IOCTL_VOLUME_IS_DYNAMIC, NULL, 0, &info->IsDynamic, sizeof (info->IsDynamic))))
info->IsDynamic = FALSE;
}
Irp->IoStatus.Information = sizeof (DISK_PARTITION_INFO_STRUCT);
Irp->IoStatus.Status = ntStatus;
}
}
break;
case TC_IOCTL_GET_DRIVE_GEOMETRY:
if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY_STRUCT), ValidateInputOutput))
{
DISK_GEOMETRY_STRUCT *g = (DISK_GEOMETRY_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
{
NTSTATUS ntStatus;
EnsureNullTerminatedString (g->deviceName, sizeof (g->deviceName));
Dump ("Calling IOCTL_DISK_GET_DRIVE_GEOMETRY on %ls\n", g->deviceName);
ntStatus = TCDeviceIoControl (g->deviceName,
IOCTL_DISK_GET_DRIVE_GEOMETRY,
NULL, 0, &g->diskGeometry, sizeof (g->diskGeometry));
Irp->IoStatus.Information = sizeof (DISK_GEOMETRY_STRUCT);
Irp->IoStatus.Status = ntStatus;
}
}
break;
case VC_IOCTL_GET_DRIVE_GEOMETRY_EX:
if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY_EX_STRUCT), ValidateInputOutput))
{
DISK_GEOMETRY_EX_STRUCT *g = (DISK_GEOMETRY_EX_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
{
NTSTATUS ntStatus;
PVOID buffer = TCalloc (256); // enough for DISK_GEOMETRY_EX and padded data
if (buffer)
{
EnsureNullTerminatedString (g->deviceName, sizeof (g->deviceName));
Dump ("Calling IOCTL_DISK_GET_DRIVE_GEOMETRY_EX on %ls\n", g->deviceName);
ntStatus = TCDeviceIoControl (g->deviceName,
IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
NULL, 0, buffer, 256);
if (NT_SUCCESS(ntStatus))
{
PDISK_GEOMETRY_EX pGeo = (PDISK_GEOMETRY_EX) buffer;
memcpy (&g->diskGeometry, &pGeo->Geometry, sizeof (DISK_GEOMETRY));
g->DiskSize.QuadPart = pGeo->DiskSize.QuadPart;
}
else
{
DISK_GEOMETRY dg = {0};
Dump ("Failed. Calling IOCTL_DISK_GET_DRIVE_GEOMETRY on %ls\n", g->deviceName);
ntStatus = TCDeviceIoControl (g->deviceName,
IOCTL_DISK_GET_DRIVE_GEOMETRY,
NULL, 0, &dg, sizeof (dg));
if (NT_SUCCESS(ntStatus))
{
memcpy (&g->diskGeometry, &dg, sizeof (DISK_GEOMETRY));
g->DiskSize.QuadPart = dg.Cylinders.QuadPart * dg.SectorsPerTrack * dg.TracksPerCylinder * dg.BytesPerSector;
if (OsMajorVersion >= 6)
{
STORAGE_READ_CAPACITY storage = {0};
NTSTATUS lStatus;
storage.Version = sizeof (STORAGE_READ_CAPACITY);
Dump ("Calling IOCTL_STORAGE_READ_CAPACITY on %ls\n", g->deviceName);
lStatus = TCDeviceIoControl (g->deviceName,
IOCTL_STORAGE_READ_CAPACITY,
NULL, 0, &storage, sizeof (STORAGE_READ_CAPACITY));
if ( NT_SUCCESS(lStatus)
&& (storage.Size == sizeof (STORAGE_READ_CAPACITY))
)
{
g->DiskSize.QuadPart = storage.DiskLength.QuadPart;
}
}
}
}
TCfree (buffer);
Irp->IoStatus.Information = sizeof (DISK_GEOMETRY_EX_STRUCT);
Irp->IoStatus.Status = ntStatus;
}
else
{
Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
Irp->IoStatus.Information = 0;
}
}
}
break;
case TC_IOCTL_PROBE_REAL_DRIVE_SIZE:
if (ValidateIOBufferSize (Irp, sizeof (ProbeRealDriveSizeRequest), ValidateInputOutput))
{
ProbeRealDriveSizeRequest *request = (ProbeRealDriveSizeRequest *) Irp->AssociatedIrp.SystemBuffer;
NTSTATUS status;
UNICODE_STRING name;
PFILE_OBJECT fileObject;
PDEVICE_OBJECT deviceObject;
EnsureNullTerminatedString (request->DeviceName, sizeof (request->DeviceName));
RtlInitUnicodeString (&name, request->DeviceName);
status = IoGetDeviceObjectPointer (&name, FILE_READ_ATTRIBUTES, &fileObject, &deviceObject);
if (!NT_SUCCESS (status))
{
Irp->IoStatus.Information = 0;
Irp->IoStatus.Status = status;
break;
}
status = ProbeRealDriveSize (deviceObject, &request->RealDriveSize);
ObDereferenceObject (fileObject);
if (status == STATUS_TIMEOUT)
{
request->TimeOut = TRUE;
Irp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
else if (!NT_SUCCESS (status))
{
Irp->IoStatus.Information = 0;
Irp->IoStatus.Status = status;
}
else
{
request->TimeOut = FALSE;
Irp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest);
Irp->IoStatus.Status = status;
}
}
break;
case TC_IOCTL_MOUNT_VOLUME:
if (ValidateIOBufferSize (Irp, sizeof (MOUNT_STRUCT), ValidateInputOutput))
{
MOUNT_STRUCT *mount = (MOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
if (mount->VolumePassword.Length > MAX_PASSWORD || mount->ProtectedHidVolPassword.Length > MAX_PASSWORD
|| mount->pkcs5_prf < 0 || mount->pkcs5_prf > LAST_PRF_ID
|| mount->VolumePim < -1 || mount->VolumePim == INT_MAX
|| mount->ProtectedHidVolPkcs5Prf < 0 || mount->ProtectedHidVolPkcs5Prf > LAST_PRF_ID
|| (mount->bTrueCryptMode != FALSE && mount->bTrueCryptMode != TRUE)
)
{
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
Irp->IoStatus.Information = 0;
break;
}
EnsureNullTerminatedString (mount->wszVolume, sizeof (mount->wszVolume));
EnsureNullTerminatedString (mount->wszLabel, sizeof (mount->wszLabel));
Irp->IoStatus.Information = sizeof (MOUNT_STRUCT);
Irp->IoStatus.Status = MountDevice (DeviceObject, mount);
burn (&mount->VolumePassword, sizeof (mount->VolumePassword));
burn (&mount->ProtectedHidVolPassword, sizeof (mount->ProtectedHidVolPassword));
burn (&mount->pkcs5_prf, sizeof (mount->pkcs5_prf));
burn (&mount->VolumePim, sizeof (mount->VolumePim));
burn (&mount->bTrueCryptMode, sizeof (mount->bTrueCryptMode));
burn (&mount->ProtectedHidVolPkcs5Prf, sizeof (mount->ProtectedHidVolPkcs5Prf));
burn (&mount->ProtectedHidVolPim, sizeof (mount->ProtectedHidVolPim));
}
break;
case TC_IOCTL_DISMOUNT_VOLUME:
if (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput))
{
UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
PDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (unmount->nDosDriveNo);
unmount->nReturnCode = ERR_DRIVE_NOT_FOUND;
if (ListDevice)
{
PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension;
if (IsVolumeAccessibleByCurrentUser (ListExtension))
unmount->nReturnCode = UnmountDevice (unmount, ListDevice, unmount->ignoreOpenFiles);
}
Irp->IoStatus.Information = sizeof (UNMOUNT_STRUCT);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_DISMOUNT_ALL_VOLUMES:
if (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput))
{
UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer;
unmount->nReturnCode = UnmountAllDevices (unmount, unmount->ignoreOpenFiles);
Irp->IoStatus.Information = sizeof (UNMOUNT_STRUCT);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_BOOT_ENCRYPTION_SETUP:
Irp->IoStatus.Status = StartBootEncryptionSetup (DeviceObject, Irp, irpSp);
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP:
Irp->IoStatus.Status = AbortBootEncryptionSetup();
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS:
GetBootEncryptionStatus (Irp, irpSp);
break;
case TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT:
Irp->IoStatus.Information = 0;
Irp->IoStatus.Status = GetSetupResult();
break;
case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES:
GetBootDriveVolumeProperties (Irp, irpSp);
break;
case TC_IOCTL_GET_BOOT_LOADER_VERSION:
GetBootLoaderVersion (Irp, irpSp);
break;
case TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER:
ReopenBootVolumeHeader (Irp, irpSp);
break;
case VC_IOCTL_GET_BOOT_LOADER_FINGERPRINT:
GetBootLoaderFingerprint (Irp, irpSp);
break;
case TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME:
GetBootEncryptionAlgorithmName (Irp, irpSp);
break;
case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING:
if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput))
{
*(int *) Irp->AssociatedIrp.SystemBuffer = IsHiddenSystemRunning() ? 1 : 0;
Irp->IoStatus.Information = sizeof (int);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_START_DECOY_SYSTEM_WIPE:
Irp->IoStatus.Status = StartDecoySystemWipe (DeviceObject, Irp, irpSp);
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE:
Irp->IoStatus.Status = AbortDecoySystemWipe();
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT:
Irp->IoStatus.Status = GetDecoySystemWipeResult();
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS:
GetDecoySystemWipeStatus (Irp, irpSp);
break;
case TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR:
Irp->IoStatus.Status = WriteBootDriveSector (Irp, irpSp);
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_GET_WARNING_FLAGS:
if (ValidateIOBufferSize (Irp, sizeof (GetWarningFlagsRequest), ValidateOutput))
{
GetWarningFlagsRequest *flags = (GetWarningFlagsRequest *) Irp->AssociatedIrp.SystemBuffer;
flags->PagingFileCreationPrevented = PagingFileCreationPrevented;
PagingFileCreationPrevented = FALSE;
flags->SystemFavoriteVolumeDirty = SystemFavoriteVolumeDirty;
SystemFavoriteVolumeDirty = FALSE;
Irp->IoStatus.Information = sizeof (GetWarningFlagsRequest);
Irp->IoStatus.Status = STATUS_SUCCESS;
}
break;
case TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY:
if (UserCanAccessDriveDevice())
{
SystemFavoriteVolumeDirty = TRUE;
Irp->IoStatus.Status = STATUS_SUCCESS;
}
else
Irp->IoStatus.Status = STATUS_ACCESS_DENIED;
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_REREAD_DRIVER_CONFIG:
Irp->IoStatus.Status = ReadRegistryConfigFlags (FALSE);
Irp->IoStatus.Information = 0;
break;
case TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG:
if ( (ValidateIOBufferSize (Irp, sizeof (GetSystemDriveDumpConfigRequest), ValidateOutput))
&& (Irp->RequestorMode == KernelMode)
)
{
GetSystemDriveDumpConfigRequest *request = (GetSystemDriveDumpConfigRequest *) Irp->AssociatedIrp.SystemBuffer;
request->BootDriveFilterExtension = GetBootDriveFilterExtension();
if (IsBootDriveMounted() && request->BootDriveFilterExtension)
{
request->HwEncryptionEnabled = IsHwEncryptionEnabled();
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof (*request);
}
else
{
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;
Irp->IoStatus.Information = 0;
}
}
break;
default:
return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0);
}
#if defined(DEBUG) || defined(DEBUG_TRACE)
if (!NT_SUCCESS (Irp->IoStatus.Status))
{
switch (irpSp->Parameters.DeviceIoControl.IoControlCode)
{
case TC_IOCTL_GET_MOUNTED_VOLUMES:
case TC_IOCTL_GET_PASSWORD_CACHE_STATUS:
case TC_IOCTL_GET_PORTABLE_MODE_STATUS:
case TC_IOCTL_SET_PORTABLE_MODE_STATUS:
case TC_IOCTL_OPEN_TEST:
case TC_IOCTL_GET_RESOLVED_SYMLINK:
case TC_IOCTL_GET_DRIVE_PARTITION_INFO:
case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES:
case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS:
case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING:
break;
default:
Dump ("IOCTL error 0x%08x\n", Irp->IoStatus.Status);
}
}
#endif
return TCCompleteIrp (Irp, Irp->IoStatus.Status, Irp->IoStatus.Information);
}
NTSTATUS TCStartThread (PKSTART_ROUTINE threadProc, PVOID threadArg, PKTHREAD *kThread)
{
return TCStartThreadInProcess (threadProc, threadArg, kThread, NULL);
}
NTSTATUS TCStartThreadInProcess (PKSTART_ROUTINE threadProc, PVOID threadArg, PKTHREAD *kThread, PEPROCESS process)
{
NTSTATUS status;
HANDLE threadHandle;
HANDLE processHandle = NULL;
OBJECT_ATTRIBUTES threadObjAttributes;
if (process)
{
status = ObOpenObjectByPointer (process, OBJ_KERNEL_HANDLE, NULL, 0, NULL, KernelMode, &processHandle);
if (!NT_SUCCESS (status))
return status;
}
InitializeObjectAttributes (&threadObjAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);
status = PsCreateSystemThread (&threadHandle, THREAD_ALL_ACCESS, &threadObjAttributes, processHandle, NULL, threadProc, threadArg);
if (!NT_SUCCESS (status))
return status;
status = ObReferenceObjectByHandle (threadHandle, THREAD_ALL_ACCESS, NULL, KernelMode, (PVOID *) kThread, NULL);
if (!NT_SUCCESS (status))
{
ZwClose (threadHandle);
*kThread = NULL;
return status;
}
if (processHandle)
ZwClose (processHandle);
ZwClose (threadHandle);
return STATUS_SUCCESS;
}
void TCStopThread (PKTHREAD kThread, PKEVENT wakeUpEvent)
{
if (wakeUpEvent)
KeSetEvent (wakeUpEvent, 0, FALSE);
KeWaitForSingleObject (kThread, Executive, KernelMode, FALSE, NULL);
ObDereferenceObject (kThread);
}
NTSTATUS TCStartVolumeThread (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, MOUNT_STRUCT * mount)
{
PTHREAD_BLOCK pThreadBlock = TCalloc (sizeof (THREAD_BLOCK));
HANDLE hThread;
NTSTATUS ntStatus;
OBJECT_ATTRIBUTES threadObjAttributes;
SECURITY_QUALITY_OF_SERVICE qos;
Dump ("Starting thread...\n");
if (pThreadBlock == NULL)
{
return STATUS_INSUFFICIENT_RESOURCES;
}
else
{
pThreadBlock->DeviceObject = DeviceObject;
pThreadBlock->mount = mount;
}
qos.Length = sizeof (qos);
qos.ContextTrackingMode = SECURITY_STATIC_TRACKING;
qos.EffectiveOnly = TRUE;
qos.ImpersonationLevel = SecurityImpersonation;
ntStatus = SeCreateClientSecurity (PsGetCurrentThread(), &qos, FALSE, &Extension->SecurityClientContext);
if (!NT_SUCCESS (ntStatus))
goto ret;
Extension->SecurityClientContextValid = TRUE;
Extension->bThreadShouldQuit = FALSE;
InitializeObjectAttributes (&threadObjAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);
ntStatus = PsCreateSystemThread (&hThread,
THREAD_ALL_ACCESS,
&threadObjAttributes,
NULL,
NULL,
VolumeThreadProc,
pThreadBlock);
if (!NT_SUCCESS (ntStatus))
{
Dump ("PsCreateSystemThread Failed END\n");
goto ret;
}
ntStatus = ObReferenceObjectByHandle (hThread,
THREAD_ALL_ACCESS,
NULL,
KernelMode,
&Extension->peThread,
NULL);
ZwClose (hThread);
if (!NT_SUCCESS (ntStatus))
goto ret;
Dump ("Waiting for thread to initialize...\n");
KeWaitForSingleObject (&Extension->keCreateEvent,
Executive,
KernelMode,
FALSE,
NULL);
Dump ("Waiting completed! Thread returns 0x%08x\n", pThreadBlock->ntCreateStatus);
ntStatus = pThreadBlock->ntCreateStatus;
ret:
TCfree (pThreadBlock);
return ntStatus;
}
void TCStopVolumeThread (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension)
{
NTSTATUS ntStatus;
UNREFERENCED_PARAMETER (DeviceObject); /* Remove compiler warning */
Dump ("Signalling thread to quit...\n");
Extension->bThreadShouldQuit = TRUE;
KeReleaseSemaphore (&Extension->RequestSemaphore,
0,
1,
TRUE);
ntStatus = KeWaitForSingleObject (Extension->peThread,
Executive,
KernelMode,
FALSE,
NULL);
ASSERT (NT_SUCCESS (ntStatus));
ObDereferenceObject (Extension->peThread);
Extension->peThread = NULL;
Dump ("Thread exited\n");
}
// Suspend current thread for a number of milliseconds
void TCSleep (int milliSeconds)
{
PKTIMER timer = (PKTIMER) TCalloc (sizeof (KTIMER));
LARGE_INTEGER duetime;
if (!timer)
return;
duetime.QuadPart = (__int64) milliSeconds * -10000;
KeInitializeTimerEx(timer, NotificationTimer);
KeSetTimerEx(timer, duetime, 0, NULL);
KeWaitForSingleObject (timer, Executive, KernelMode, FALSE, NULL);
TCfree (timer);
}
BOOL IsDeviceName(wchar_t wszVolume[TC_MAX_PATH])
{
if ( (wszVolume[0] == '\\')
&& (wszVolume[1] == 'D' || wszVolume[1] == 'd')
&& (wszVolume[2] == 'E' || wszVolume[2] == 'e')
&& (wszVolume[3] == 'V' || wszVolume[3] == 'v')
&& (wszVolume[4] == 'I' || wszVolume[4] == 'i')
&& (wszVolume[5] == 'C' || wszVolume[5] == 'c')
&& (wszVolume[6] == 'E' || wszVolume[6] == 'e')
)
{
return TRUE;
}
else
return FALSE;
}
/* VolumeThreadProc does all the work of processing IRP's, and dispatching them
to either the ReadWrite function or the DeviceControl function */
VOID VolumeThreadProc (PVOID Context)
{
PTHREAD_BLOCK pThreadBlock = (PTHREAD_BLOCK) Context;
PDEVICE_OBJECT DeviceObject = pThreadBlock->DeviceObject;
PEXTENSION Extension = (PEXTENSION) DeviceObject->DeviceExtension;
BOOL bDevice;
/* Set thread priority to lowest realtime level. */
KeSetPriorityThread (KeGetCurrentThread (), LOW_REALTIME_PRIORITY);
Dump ("Mount THREAD OPENING VOLUME BEGIN\n");
if ( !IsDeviceName (pThreadBlock->mount->wszVolume))
{
RtlStringCbCopyW (pThreadBlock->wszMountVolume, sizeof(pThreadBlock->wszMountVolume),WIDE ("\\??\\"));
RtlStringCbCatW (pThreadBlock->wszMountVolume, sizeof(pThreadBlock->wszMountVolume),pThreadBlock->mount->wszVolume);
bDevice = FALSE;
}
else
{
pThreadBlock->wszMountVolume[0] = 0;
RtlStringCbCatW (pThreadBlock->wszMountVolume, sizeof(pThreadBlock->wszMountVolume),pThreadBlock->mount->wszVolume);
bDevice = TRUE;
}
Dump ("Mount THREAD request for File %ls DriveNumber %d Device = %d\n",
pThreadBlock->wszMountVolume, pThreadBlock->mount->nDosDriveNo, bDevice);
pThreadBlock->ntCreateStatus = TCOpenVolume (DeviceObject,
Extension,
pThreadBlock->mount,
pThreadBlock->wszMountVolume,
bDevice);
if (!NT_SUCCESS (pThreadBlock->ntCreateStatus) || pThreadBlock->mount->nReturnCode != 0)
{
KeSetEvent (&Extension->keCreateEvent, 0, FALSE);
PsTerminateSystemThread (STATUS_SUCCESS);
}
// Start IO queue
Extension->Queue.IsFilterDevice = FALSE;
Extension->Queue.DeviceObject = DeviceObject;
Extension->Queue.CryptoInfo = Extension->cryptoInfo;
Extension->Queue.HostFileHandle = Extension->hDeviceFile;
Extension->Queue.VirtualDeviceLength = Extension->DiskLength;
Extension->Queue.MaxReadAheadOffset.QuadPart = Extension->HostLength;
if (Extension->SecurityClientContextValid)
Extension->Queue.SecurityClientContext = &Extension->SecurityClientContext;
else
Extension->Queue.SecurityClientContext = NULL;
pThreadBlock->ntCreateStatus = EncryptedIoQueueStart (&Extension->Queue);
if (!NT_SUCCESS (pThreadBlock->ntCreateStatus))
{
TCCloseVolume (DeviceObject, Extension);
pThreadBlock->mount->nReturnCode = ERR_OS_ERROR;
KeSetEvent (&Extension->keCreateEvent, 0, FALSE);
PsTerminateSystemThread (STATUS_SUCCESS);
}
KeSetEvent (&Extension->keCreateEvent, 0, FALSE);
/* From this point on pThreadBlock cannot be used as it will have been released! */
pThreadBlock = NULL;
for (;;)
{
/* Wait for a request from the dispatch routines. */
KeWaitForSingleObject ((PVOID) & Extension->RequestSemaphore, Executive, KernelMode, FALSE, NULL);
for (;;)
{
PIO_STACK_LOCATION irpSp;
PLIST_ENTRY request;
PIRP irp;
request = ExInterlockedRemoveHeadList (&Extension->ListEntry, &Extension->ListSpinLock);
if (request == NULL)
break;
irp = CONTAINING_RECORD (request, IRP, Tail.Overlay.ListEntry);
irpSp = IoGetCurrentIrpStackLocation (irp);
ASSERT (irpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL);
ProcessVolumeDeviceControlIrp (DeviceObject, Extension, irp);
IoReleaseRemoveLock (&Extension->Queue.RemoveLock, irp);
}
if (Extension->bThreadShouldQuit)
{
Dump ("Closing volume\n");
EncryptedIoQueueStop (&Extension->Queue);
TCCloseVolume (DeviceObject, Extension);
PsTerminateSystemThread (STATUS_SUCCESS);
}
}
}
void TCGetNTNameFromNumber (LPWSTR ntname, int cbNtName, int nDriveNo)
{
WCHAR tmp[2] =
{0, 0};
int j = nDriveNo + (WCHAR) 'A';
tmp[0] = (short) j;
RtlStringCbCopyW (ntname, cbNtName,(LPWSTR) NT_MOUNT_PREFIX);
RtlStringCbCatW (ntname, cbNtName, tmp);
}
void TCGetDosNameFromNumber (LPWSTR dosname,int cbDosName, int nDriveNo, DeviceNamespaceType namespaceType)
{
WCHAR tmp[3] =
{0, ':', 0};
int j = nDriveNo + (WCHAR) 'A';
tmp[0] = (short) j;
if (DeviceNamespaceGlobal == namespaceType)
{
RtlStringCbCopyW (dosname, cbDosName, (LPWSTR) DOS_MOUNT_PREFIX_GLOBAL);
}
else
{
RtlStringCbCopyW (dosname, cbDosName, (LPWSTR) DOS_MOUNT_PREFIX_DEFAULT);
}
RtlStringCbCatW (dosname, cbDosName, tmp);
}
#if defined(_DEBUG) || defined (_DEBUG_TRACE)
LPWSTR TCTranslateCode (ULONG ulCode)
{
switch (ulCode)
{
#define TC_CASE_RET_NAME(CODE) case CODE : return L###CODE
TC_CASE_RET_NAME (TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP);
TC_CASE_RET_NAME (TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE);
TC_CASE_RET_NAME (TC_IOCTL_BOOT_ENCRYPTION_SETUP);
TC_CASE_RET_NAME (TC_IOCTL_DISMOUNT_ALL_VOLUMES);
TC_CASE_RET_NAME (TC_IOCTL_DISMOUNT_VOLUME);
TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES);
TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME);
TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT);
TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS);
TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_LOADER_VERSION);
TC_CASE_RET_NAME (TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT);
TC_CASE_RET_NAME (TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS);
TC_CASE_RET_NAME (TC_IOCTL_GET_DEVICE_REFCOUNT);
TC_CASE_RET_NAME (TC_IOCTL_GET_DRIVE_GEOMETRY);
TC_CASE_RET_NAME (TC_IOCTL_GET_DRIVE_PARTITION_INFO);
TC_CASE_RET_NAME (TC_IOCTL_GET_DRIVER_VERSION);
TC_CASE_RET_NAME (TC_IOCTL_GET_MOUNTED_VOLUMES);
TC_CASE_RET_NAME (TC_IOCTL_GET_PASSWORD_CACHE_STATUS);
TC_CASE_RET_NAME (TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG);
TC_CASE_RET_NAME (TC_IOCTL_GET_PORTABLE_MODE_STATUS);
TC_CASE_RET_NAME (TC_IOCTL_SET_PORTABLE_MODE_STATUS);
TC_CASE_RET_NAME (TC_IOCTL_GET_RESOLVED_SYMLINK);
TC_CASE_RET_NAME (TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG);
TC_CASE_RET_NAME (TC_IOCTL_GET_VOLUME_PROPERTIES);
TC_CASE_RET_NAME (TC_IOCTL_GET_WARNING_FLAGS);
TC_CASE_RET_NAME (TC_IOCTL_DISK_IS_WRITABLE);
TC_CASE_RET_NAME (TC_IOCTL_IS_ANY_VOLUME_MOUNTED);
TC_CASE_RET_NAME (TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED);
TC_CASE_RET_NAME (TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING);
TC_CASE_RET_NAME (TC_IOCTL_MOUNT_VOLUME);
TC_CASE_RET_NAME (TC_IOCTL_OPEN_TEST);
TC_CASE_RET_NAME (TC_IOCTL_PROBE_REAL_DRIVE_SIZE);
TC_CASE_RET_NAME (TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER);
TC_CASE_RET_NAME (TC_IOCTL_REREAD_DRIVER_CONFIG);
TC_CASE_RET_NAME (TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY);
TC_CASE_RET_NAME (TC_IOCTL_START_DECOY_SYSTEM_WIPE);
TC_CASE_RET_NAME (TC_IOCTL_WIPE_PASSWORD_CACHE);
TC_CASE_RET_NAME (TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR);
TC_CASE_RET_NAME (VC_IOCTL_GET_DRIVE_GEOMETRY_EX);
TC_CASE_RET_NAME (IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS);
#undef TC_CASE_RET_NAME
}
if (ulCode == IOCTL_DISK_GET_DRIVE_GEOMETRY)
return (LPWSTR) _T ("IOCTL_DISK_GET_DRIVE_GEOMETRY");
else if (ulCode == IOCTL_DISK_GET_DRIVE_GEOMETRY_EX)
return (LPWSTR) _T ("IOCTL_DISK_GET_DRIVE_GEOMETRY_EX");
else if (ulCode == IOCTL_MOUNTDEV_QUERY_DEVICE_NAME)
return (LPWSTR) _T ("IOCTL_MOUNTDEV_QUERY_DEVICE_NAME");
else if (ulCode == IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME)
return (LPWSTR) _T ("IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME");
else if (ulCode == IOCTL_MOUNTDEV_QUERY_UNIQUE_ID)
return (LPWSTR) _T ("IOCTL_MOUNTDEV_QUERY_UNIQUE_ID");
else if (ulCode == IOCTL_VOLUME_ONLINE)
return (LPWSTR) _T ("IOCTL_VOLUME_ONLINE");
else if (ulCode == IOCTL_MOUNTDEV_LINK_CREATED)
return (LPWSTR) _T ("IOCTL_MOUNTDEV_LINK_CREATED");
else if (ulCode == IOCTL_MOUNTDEV_LINK_DELETED)
return (LPWSTR) _T ("IOCTL_MOUNTDEV_LINK_DELETED");
else if (ulCode == IOCTL_MOUNTMGR_QUERY_POINTS)
return (LPWSTR) _T ("IOCTL_MOUNTMGR_QUERY_POINTS");
else if (ulCode == IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_CREATED)
return (LPWSTR) _T ("IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_CREATED");
else if (ulCode == IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_DELETED)
return (LPWSTR) _T ("IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_DELETED");
else if (ulCode == IOCTL_DISK_GET_LENGTH_INFO)
return (LPWSTR) _T ("IOCTL_DISK_GET_LENGTH_INFO");
else if (ulCode == IOCTL_STORAGE_GET_DEVICE_NUMBER)
return (LPWSTR) _T ("IOCTL_STORAGE_GET_DEVICE_NUMBER");
else if (ulCode == IOCTL_DISK_GET_PARTITION_INFO)
return (LPWSTR) _T ("IOCTL_DISK_GET_PARTITION_INFO");
else if (ulCode == IOCTL_DISK_GET_PARTITION_INFO_EX)
return (LPWSTR) _T ("IOCTL_DISK_GET_PARTITION_INFO_EX");
else if (ulCode == IOCTL_DISK_SET_PARTITION_INFO)
return (LPWSTR) _T ("IOCTL_DISK_SET_PARTITION_INFO");
else if (ulCode == IOCTL_DISK_GET_DRIVE_LAYOUT)
return (LPWSTR) _T ("IOCTL_DISK_GET_DRIVE_LAYOUT");
else if (ulCode == IOCTL_DISK_GET_DRIVE_LAYOUT_EX)
return (LPWSTR) _T ("IOCTL_DISK_GET_DRIVE_LAYOUT_EX");
else if (ulCode == IOCTL_DISK_SET_DRIVE_LAYOUT_EX)
return (LPWSTR) _T ("IOCTL_DISK_SET_DRIVE_LAYOUT_EX");
else if (ulCode == IOCTL_DISK_VERIFY)
return (LPWSTR) _T ("IOCTL_DISK_VERIFY");
else if (ulCode == IOCTL_DISK_FORMAT_TRACKS)
return (LPWSTR) _T ("IOCTL_DISK_FORMAT_TRACKS");
else if (ulCode == IOCTL_DISK_REASSIGN_BLOCKS)
return (LPWSTR) _T ("IOCTL_DISK_REASSIGN_BLOCKS");
else if (ulCode == IOCTL_DISK_PERFORMANCE)
return (LPWSTR) _T ("IOCTL_DISK_PERFORMANCE");
else if (ulCode == IOCTL_DISK_IS_WRITABLE)
return (LPWSTR) _T ("IOCTL_DISK_IS_WRITABLE");
else if (ulCode == IOCTL_DISK_LOGGING)
return (LPWSTR) _T ("IOCTL_DISK_LOGGING");
else if (ulCode == IOCTL_DISK_FORMAT_TRACKS_EX)
return (LPWSTR) _T ("IOCTL_DISK_FORMAT_TRACKS_EX");
else if (ulCode == IOCTL_DISK_HISTOGRAM_STRUCTURE)
return (LPWSTR) _T ("IOCTL_DISK_HISTOGRAM_STRUCTURE");
else if (ulCode == IOCTL_DISK_HISTOGRAM_DATA)
return (LPWSTR) _T ("IOCTL_DISK_HISTOGRAM_DATA");
else if (ulCode == IOCTL_DISK_HISTOGRAM_RESET)
return (LPWSTR) _T ("IOCTL_DISK_HISTOGRAM_RESET");
else if (ulCode == IOCTL_DISK_REQUEST_STRUCTURE)
return (LPWSTR) _T ("IOCTL_DISK_REQUEST_STRUCTURE");
else if (ulCode == IOCTL_DISK_REQUEST_DATA)
return (LPWSTR) _T ("IOCTL_DISK_REQUEST_DATA");
else if (ulCode == IOCTL_DISK_CONTROLLER_NUMBER)
return (LPWSTR) _T ("IOCTL_DISK_CONTROLLER_NUMBER");
else if (ulCode == SMART_GET_VERSION)
return (LPWSTR) _T ("SMART_GET_VERSION");
else if (ulCode == SMART_SEND_DRIVE_COMMAND)
return (LPWSTR) _T ("SMART_SEND_DRIVE_COMMAND");
else if (ulCode == SMART_RCV_DRIVE_DATA)
return (LPWSTR) _T ("SMART_RCV_DRIVE_DATA");
else if (ulCode == IOCTL_DISK_INTERNAL_SET_VERIFY)
return (LPWSTR) _T ("IOCTL_DISK_INTERNAL_SET_VERIFY");
else if (ulCode == IOCTL_DISK_INTERNAL_CLEAR_VERIFY)
return (LPWSTR) _T ("IOCTL_DISK_INTERNAL_CLEAR_VERIFY");
else if (ulCode == IOCTL_DISK_CHECK_VERIFY)
return (LPWSTR) _T ("IOCTL_DISK_CHECK_VERIFY");
else if (ulCode == IOCTL_DISK_MEDIA_REMOVAL)
return (LPWSTR) _T ("IOCTL_DISK_MEDIA_REMOVAL");
else if (ulCode == IOCTL_DISK_EJECT_MEDIA)
return (LPWSTR) _T ("IOCTL_DISK_EJECT_MEDIA");
else if (ulCode == IOCTL_DISK_LOAD_MEDIA)
return (LPWSTR) _T ("IOCTL_DISK_LOAD_MEDIA");
else if (ulCode == IOCTL_DISK_RESERVE)
return (LPWSTR) _T ("IOCTL_DISK_RESERVE");
else if (ulCode == IOCTL_DISK_RELEASE)
return (LPWSTR) _T ("IOCTL_DISK_RELEASE");
else if (ulCode == IOCTL_DISK_FIND_NEW_DEVICES)
return (LPWSTR) _T ("IOCTL_DISK_FIND_NEW_DEVICES");
else if (ulCode == IOCTL_DISK_GET_MEDIA_TYPES)
return (LPWSTR) _T ("IOCTL_DISK_GET_MEDIA_TYPES");
else if (ulCode == IOCTL_DISK_IS_CLUSTERED)
return (LPWSTR) _T ("IOCTL_DISK_IS_CLUSTERED");
else if (ulCode == IOCTL_DISK_UPDATE_DRIVE_SIZE)
return (LPWSTR) _T ("IOCTL_DISK_UPDATE_DRIVE_SIZE");
else if (ulCode == IOCTL_STORAGE_GET_MEDIA_TYPES)
return (LPWSTR) _T ("IOCTL_STORAGE_GET_MEDIA_TYPES");
else if (ulCode == IOCTL_STORAGE_GET_HOTPLUG_INFO)
return (LPWSTR) _T ("IOCTL_STORAGE_GET_HOTPLUG_INFO");
else if (ulCode == IOCTL_STORAGE_SET_HOTPLUG_INFO)
return (LPWSTR) _T ("IOCTL_STORAGE_SET_HOTPLUG_INFO");
else if (ulCode == IOCTL_STORAGE_QUERY_PROPERTY)
return (LPWSTR) _T ("IOCTL_STORAGE_QUERY_PROPERTY");
else if (ulCode == IOCTL_VOLUME_GET_GPT_ATTRIBUTES)
return (LPWSTR) _T ("IOCTL_VOLUME_GET_GPT_ATTRIBUTES");
else if (ulCode == FT_BALANCED_READ_MODE)
return (LPWSTR) _T ("FT_BALANCED_READ_MODE");
else if (ulCode == IOCTL_VOLUME_QUERY_ALLOCATION_HINT)
return (LPWSTR) _T ("IOCTL_VOLUME_QUERY_ALLOCATION_HINT");
else if (ulCode == IOCTL_DISK_GET_CLUSTER_INFO)
return (LPWSTR) _T ("IOCTL_DISK_GET_CLUSTER_INFO");
else if (ulCode == IOCTL_DISK_ARE_VOLUMES_READY)
return (LPWSTR) _T ("IOCTL_DISK_ARE_VOLUMES_READY");
else if (ulCode == IOCTL_VOLUME_IS_DYNAMIC)
return (LPWSTR) _T ("IOCTL_VOLUME_IS_DYNAMIC");
else if (ulCode == IOCTL_MOUNTDEV_QUERY_STABLE_GUID)
return (LPWSTR) _T ("IOCTL_MOUNTDEV_QUERY_STABLE_GUID");
else if (ulCode == IOCTL_VOLUME_POST_ONLINE)
return (LPWSTR) _T ("IOCTL_VOLUME_POST_ONLINE");
else if (ulCode == IOCTL_STORAGE_CHECK_PRIORITY_HINT_SUPPORT)
return (LPWSTR) _T ("IOCTL_STORAGE_CHECK_PRIORITY_HINT_SUPPORT");
else if (ulCode == IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES)
return (LPWSTR) _T ("IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES");
else if (ulCode == IRP_MJ_READ)
return (LPWSTR) _T ("IRP_MJ_READ");
else if (ulCode == IRP_MJ_WRITE)
return (LPWSTR) _T ("IRP_MJ_WRITE");
else if (ulCode == IRP_MJ_CREATE)
return (LPWSTR) _T ("IRP_MJ_CREATE");
else if (ulCode == IRP_MJ_CLOSE)
return (LPWSTR) _T ("IRP_MJ_CLOSE");
else if (ulCode == IRP_MJ_CLEANUP)
return (LPWSTR) _T ("IRP_MJ_CLEANUP");
else if (ulCode == IRP_MJ_FLUSH_BUFFERS)
return (LPWSTR) _T ("IRP_MJ_FLUSH_BUFFERS");
else if (ulCode == IRP_MJ_SHUTDOWN)
return (LPWSTR) _T ("IRP_MJ_SHUTDOWN");
else if (ulCode == IRP_MJ_DEVICE_CONTROL)
return (LPWSTR) _T ("IRP_MJ_DEVICE_CONTROL");
else
{
return (LPWSTR) _T ("IOCTL");
}
}
#endif
void TCDeleteDeviceObject (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension)
{
UNICODE_STRING Win32NameString;
NTSTATUS ntStatus;
Dump ("TCDeleteDeviceObject BEGIN\n");
if (Extension->bRootDevice)
{
RtlInitUnicodeString (&Win32NameString, (LPWSTR) DOS_ROOT_PREFIX);
ntStatus = IoDeleteSymbolicLink (&Win32NameString);
if (!NT_SUCCESS (ntStatus))
Dump ("IoDeleteSymbolicLink failed ntStatus = 0x%08x\n", ntStatus);
RootDeviceObject = NULL;
}
else
{
if (Extension->peThread != NULL)
TCStopVolumeThread (DeviceObject, Extension);
if (Extension->UserSid)
TCfree (Extension->UserSid);
if (Extension->SecurityClientContextValid)
{
if (OsMajorVersion == 5 && OsMinorVersion == 0)
{
ObDereferenceObject (Extension->SecurityClientContext.ClientToken);
}
else
{
// Windows 2000 does not support PsDereferenceImpersonationToken() used by SeDeleteClientSecurity().
// TODO: Use only SeDeleteClientSecurity() once support for Windows 2000 is dropped.
VOID (*PsDereferenceImpersonationTokenD) (PACCESS_TOKEN ImpersonationToken);
UNICODE_STRING name;
RtlInitUnicodeString (&name, L"PsDereferenceImpersonationToken");
PsDereferenceImpersonationTokenD = MmGetSystemRoutineAddress (&name);
if (!PsDereferenceImpersonationTokenD)
TC_BUG_CHECK (STATUS_NOT_IMPLEMENTED);
# define PsDereferencePrimaryToken
# define PsDereferenceImpersonationToken PsDereferenceImpersonationTokenD
SeDeleteClientSecurity (&Extension->SecurityClientContext);
# undef PsDereferencePrimaryToken
# undef PsDereferenceImpersonationToken
}
}
VirtualVolumeDeviceObjects[Extension->nDosDriveNo] = NULL;
}
IoDeleteDevice (DeviceObject);
Dump ("TCDeleteDeviceObject END\n");
}
VOID TCUnloadDriver (PDRIVER_OBJECT DriverObject)
{
Dump ("TCUnloadDriver BEGIN\n");
OnShutdownPending();
if (IsBootDriveMounted())
TC_BUG_CHECK (STATUS_INVALID_DEVICE_STATE);
EncryptionThreadPoolStop();
TCDeleteDeviceObject (RootDeviceObject, (PEXTENSION) RootDeviceObject->DeviceExtension);
Dump ("TCUnloadDriver END\n");
}
void OnShutdownPending ()
{
UNMOUNT_STRUCT unmount;
memset (&unmount, 0, sizeof (unmount));
unmount.ignoreOpenFiles = TRUE;
while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_DISMOUNT_ALL_VOLUMES, &unmount, sizeof (unmount), &unmount, sizeof (unmount)) == STATUS_INSUFFICIENT_RESOURCES || unmount.HiddenVolumeProtectionTriggered)
unmount.HiddenVolumeProtectionTriggered = FALSE;
while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0) == STATUS_INSUFFICIENT_RESOURCES);
}
NTSTATUS TCDeviceIoControl (PWSTR deviceName, ULONG IoControlCode, void *InputBuffer, ULONG InputBufferSize, void *OutputBuffer, ULONG OutputBufferSize)
{
IO_STATUS_BLOCK ioStatusBlock;
NTSTATUS ntStatus;
PIRP irp;
PFILE_OBJECT fileObject;
PDEVICE_OBJECT deviceObject;
KEVENT event;
UNICODE_STRING name;
RtlInitUnicodeString(&name, deviceName);
ntStatus = IoGetDeviceObjectPointer (&name, FILE_READ_ATTRIBUTES, &fileObject, &deviceObject);
if (!NT_SUCCESS (ntStatus))
return ntStatus;
KeInitializeEvent(&event, NotificationEvent, FALSE);
irp = IoBuildDeviceIoControlRequest (IoControlCode,
deviceObject,
InputBuffer, InputBufferSize,
OutputBuffer, OutputBufferSize,
FALSE,
&event,
&ioStatusBlock);
if (irp == NULL)
{
Dump ("IRP allocation failed\n");
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
goto ret;
}
IoGetNextIrpStackLocation (irp)->FileObject = fileObject;
ntStatus = IoCallDriver (deviceObject, irp);
if (ntStatus == STATUS_PENDING)
{
KeWaitForSingleObject (&event, Executive, KernelMode, FALSE, NULL);
ntStatus = ioStatusBlock.Status;
}
ret:
ObDereferenceObject (fileObject);
return ntStatus;
}
typedef struct
{
PDEVICE_OBJECT deviceObject; ULONG ioControlCode; void *inputBuffer; int inputBufferSize; void *outputBuffer; int outputBufferSize;
NTSTATUS Status;
KEVENT WorkItemCompletedEvent;
} SendDeviceIoControlRequestWorkItemArgs;
static VOID SendDeviceIoControlRequestWorkItemRoutine (PDEVICE_OBJECT rootDeviceObject, SendDeviceIoControlRequestWorkItemArgs *arg)
{
arg->Status = SendDeviceIoControlRequest (arg->deviceObject, arg->ioControlCode, arg->inputBuffer, arg->inputBufferSize, arg->outputBuffer, arg->outputBufferSize);
KeSetEvent (&arg->WorkItemCompletedEvent, IO_NO_INCREMENT, FALSE);
}
NTSTATUS SendDeviceIoControlRequest (PDEVICE_OBJECT deviceObject, ULONG ioControlCode, void *inputBuffer, int inputBufferSize, void *outputBuffer, int outputBufferSize)
{
IO_STATUS_BLOCK ioStatusBlock;
NTSTATUS status;
PIRP irp;
KEVENT event;
if (KeGetCurrentIrql() > APC_LEVEL)
{
SendDeviceIoControlRequestWorkItemArgs args;
PIO_WORKITEM workItem = IoAllocateWorkItem (RootDeviceObject);
if (!workItem)
return STATUS_INSUFFICIENT_RESOURCES;
args.deviceObject = deviceObject;
args.ioControlCode = ioControlCode;
args.inputBuffer = inputBuffer;
args.inputBufferSize = inputBufferSize;
args.outputBuffer = outputBuffer;
args.outputBufferSize = outputBufferSize;
KeInitializeEvent (&args.WorkItemCompletedEvent, SynchronizationEvent, FALSE);
IoQueueWorkItem (workItem, SendDeviceIoControlRequestWorkItemRoutine, DelayedWorkQueue, &args);
KeWaitForSingleObject (&args.WorkItemCompletedEvent, Executive, KernelMode, FALSE, NULL);
IoFreeWorkItem (workItem);
return args.Status;
}
KeInitializeEvent (&event, NotificationEvent, FALSE);
irp = IoBuildDeviceIoControlRequest (ioControlCode, deviceObject, inputBuffer, inputBufferSize,
outputBuffer, outputBufferSize, FALSE, &event, &ioStatusBlock);
if (!irp)
return STATUS_INSUFFICIENT_RESOURCES;
ObReferenceObject (deviceObject);
status = IoCallDriver (deviceObject, irp);
if (status == STATUS_PENDING)
{
KeWaitForSingleObject (&event, Executive, KernelMode, FALSE, NULL);
status = ioStatusBlock.Status;
}
ObDereferenceObject (deviceObject);
return status;
}
NTSTATUS ProbeRealDriveSize (PDEVICE_OBJECT driveDeviceObject, LARGE_INTEGER *driveSize)
{
NTSTATUS status;
LARGE_INTEGER sysLength;
LARGE_INTEGER offset;
byte *sectorBuffer;
ULONGLONG startTime;
if (!UserCanAccessDriveDevice())
return STATUS_ACCESS_DENIED;
sectorBuffer = TCalloc (TC_SECTOR_SIZE_BIOS);
if (!sectorBuffer)
return STATUS_INSUFFICIENT_RESOURCES;
status = SendDeviceIoControlRequest (driveDeviceObject, IOCTL_DISK_GET_LENGTH_INFO,
NULL, 0, &sysLength, sizeof (sysLength));
if (!NT_SUCCESS (status))
{
Dump ("Failed to get drive size - error %x\n", status);
TCfree (sectorBuffer);
return status;
}
startTime = KeQueryInterruptTime ();
for (offset.QuadPart = sysLength.QuadPart; ; offset.QuadPart += TC_SECTOR_SIZE_BIOS)
{
status = TCReadDevice (driveDeviceObject, sectorBuffer, offset, TC_SECTOR_SIZE_BIOS);
if (NT_SUCCESS (status))
status = TCWriteDevice (driveDeviceObject, sectorBuffer, offset, TC_SECTOR_SIZE_BIOS);
if (!NT_SUCCESS (status))
{
driveSize->QuadPart = offset.QuadPart;
Dump ("Real drive size = %I64d bytes (%I64d hidden)\n", driveSize->QuadPart, driveSize->QuadPart - sysLength.QuadPart);
TCfree (sectorBuffer);
return STATUS_SUCCESS;
}
if (KeQueryInterruptTime() - startTime > 3ULL * 60 * 1000 * 1000 * 10)
{
// Abort if probing for more than 3 minutes
driveSize->QuadPart = sysLength.QuadPart;
TCfree (sectorBuffer);
return STATUS_TIMEOUT;
}
}
}
NTSTATUS TCOpenFsVolume (PEXTENSION Extension, PHANDLE volumeHandle, PFILE_OBJECT * fileObject)
{
NTSTATUS ntStatus;
OBJECT_ATTRIBUTES objectAttributes;
UNICODE_STRING fullFileName;
IO_STATUS_BLOCK ioStatus;
WCHAR volumeName[TC_MAX_PATH];
TCGetNTNameFromNumber (volumeName, sizeof(volumeName),Extension->nDosDriveNo);
RtlInitUnicodeString (&fullFileName, volumeName);
InitializeObjectAttributes (&objectAttributes, &fullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);
ntStatus = ZwCreateFile (volumeHandle,
SYNCHRONIZE | GENERIC_READ,
&objectAttributes,
&ioStatus,
NULL,
FILE_ATTRIBUTE_NORMAL,
FILE_SHARE_READ | FILE_SHARE_WRITE,
FILE_OPEN,
FILE_SYNCHRONOUS_IO_NONALERT,
NULL,
0);
Dump ("Volume %ls open NTSTATUS 0x%08x\n", volumeName, ntStatus);
if (!NT_SUCCESS (ntStatus))
return ntStatus;
ntStatus = ObReferenceObjectByHandle (*volumeHandle,
FILE_READ_DATA,
NULL,
KernelMode,
fileObject,
NULL);
if (!NT_SUCCESS (ntStatus))
ZwClose (*volumeHandle);
return ntStatus;
}
void TCCloseFsVolume (HANDLE volumeHandle, PFILE_OBJECT fileObject)
{
ObDereferenceObject (fileObject);
ZwClose (volumeHandle);
}
static NTSTATUS TCReadWriteDevice (BOOL write, PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length)
{
NTSTATUS status;
IO_STATUS_BLOCK ioStatusBlock;
PIRP irp;
KEVENT completionEvent;
ASSERT (KeGetCurrentIrql() <= APC_LEVEL);
KeInitializeEvent (&completionEvent, NotificationEvent, FALSE);
irp = IoBuildSynchronousFsdRequest (write ? IRP_MJ_WRITE : IRP_MJ_READ, deviceObject, buffer, length, &offset, &completionEvent, &ioStatusBlock);
if (!irp)
return STATUS_INSUFFICIENT_RESOURCES;
ObReferenceObject (deviceObject);
status = IoCallDriver (deviceObject, irp);
if (status == STATUS_PENDING)
{
status = KeWaitForSingleObject (&completionEvent, Executive, KernelMode, FALSE, NULL);
if (NT_SUCCESS (status))
status = ioStatusBlock.Status;
}
ObDereferenceObject (deviceObject);
return status;
}
NTSTATUS TCReadDevice (PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length)
{
return TCReadWriteDevice (FALSE, deviceObject, buffer, offset, length);
}
NTSTATUS TCWriteDevice (PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length)
{
return TCReadWriteDevice (TRUE, deviceObject, buffer, offset, length);
}
NTSTATUS TCFsctlCall (PFILE_OBJECT fileObject, LONG IoControlCode,
void *InputBuffer, int InputBufferSize, void *OutputBuffer, int OutputBufferSize)
{
IO_STATUS_BLOCK ioStatusBlock;
NTSTATUS ntStatus;
PIRP irp;
KEVENT event;
PIO_STACK_LOCATION stack;
PDEVICE_OBJECT deviceObject = IoGetRelatedDeviceObject (fileObject);
KeInitializeEvent(&event, NotificationEvent, FALSE);
irp = IoBuildDeviceIoControlRequest (IoControlCode,
deviceObject,
InputBuffer, InputBufferSize,
OutputBuffer, OutputBufferSize,
FALSE,
&event,
&ioStatusBlock);
if (irp == NULL)
return STATUS_INSUFFICIENT_RESOURCES;
stack = IoGetNextIrpStackLocation(irp);
stack->MajorFunction = IRP_MJ_FILE_SYSTEM_CONTROL;
stack->MinorFunction = IRP_MN_USER_FS_REQUEST;
stack->FileObject = fileObject;
ntStatus = IoCallDriver (deviceObject, irp);
if (ntStatus == STATUS_PENDING)
{
KeWaitForSingleObject (&event, Executive, KernelMode, FALSE, NULL);
ntStatus = ioStatusBlock.Status;
}
return ntStatus;
}
NTSTATUS CreateDriveLink (int nDosDriveNo)
{
WCHAR dev[128], link[128];
UNICODE_STRING deviceName, symLink;
NTSTATUS ntStatus;
TCGetNTNameFromNumber (dev, sizeof(dev),nDosDriveNo);
TCGetDosNameFromNumber (link, sizeof(link),nDosDriveNo, DeviceNamespaceDefault);
RtlInitUnicodeString (&deviceName, dev);
RtlInitUnicodeString (&symLink, link);
ntStatus = IoCreateSymbolicLink (&symLink, &deviceName);
Dump ("IoCreateSymbolicLink returned %X\n", ntStatus);
return ntStatus;
}
NTSTATUS RemoveDriveLink (int nDosDriveNo)
{
WCHAR link[256];
UNICODE_STRING symLink;
NTSTATUS ntStatus;
TCGetDosNameFromNumber (link, sizeof(link),nDosDriveNo, DeviceNamespaceDefault);
RtlInitUnicodeString (&symLink, link);
ntStatus = IoDeleteSymbolicLink (&symLink);
Dump ("IoDeleteSymbolicLink returned %X\n", ntStatus);
return ntStatus;
}
NTSTATUS MountManagerMount (MOUNT_STRUCT *mount)
{
NTSTATUS ntStatus;
WCHAR arrVolume[256];
char buf[200];
PMOUNTMGR_TARGET_NAME in = (PMOUNTMGR_TARGET_NAME) buf;
PMOUNTMGR_CREATE_POINT_INPUT point = (PMOUNTMGR_CREATE_POINT_INPUT) buf;
TCGetNTNameFromNumber (arrVolume, sizeof(arrVolume),mount->nDosDriveNo);
in->DeviceNameLength = (USHORT) wcslen (arrVolume) * 2;
RtlStringCbCopyW(in->DeviceName, sizeof(buf) - sizeof(in->DeviceNameLength),arrVolume);
ntStatus = TCDeviceIoControl (MOUNTMGR_DEVICE_NAME, IOCTL_MOUNTMGR_VOLUME_ARRIVAL_NOTIFICATION,
in, (ULONG) (sizeof (in->DeviceNameLength) + wcslen (arrVolume) * 2), 0, 0);
memset (buf, 0, sizeof buf);
TCGetDosNameFromNumber ((PWSTR) &point[1], sizeof(buf) - sizeof(MOUNTMGR_CREATE_POINT_INPUT),mount->nDosDriveNo, DeviceNamespaceDefault);
point->SymbolicLinkNameOffset = sizeof (MOUNTMGR_CREATE_POINT_INPUT);
point->SymbolicLinkNameLength = (USHORT) wcslen ((PWSTR) &point[1]) * 2;
point->DeviceNameOffset = point->SymbolicLinkNameOffset + point->SymbolicLinkNameLength;
TCGetNTNameFromNumber ((PWSTR) (buf + point->DeviceNameOffset), sizeof(buf) - point->DeviceNameOffset,mount->nDosDriveNo);
point->DeviceNameLength = (USHORT) wcslen ((PWSTR) (buf + point->DeviceNameOffset)) * 2;
ntStatus = TCDeviceIoControl (MOUNTMGR_DEVICE_NAME, IOCTL_MOUNTMGR_CREATE_POINT, point,
point->DeviceNameOffset + point->DeviceNameLength, 0, 0);
return ntStatus;
}
NTSTATUS MountManagerUnmount (int nDosDriveNo)
{
NTSTATUS ntStatus;
char buf[256], out[300];
PMOUNTMGR_MOUNT_POINT in = (PMOUNTMGR_MOUNT_POINT) buf;
memset (buf, 0, sizeof buf);
TCGetDosNameFromNumber ((PWSTR) &in[1], sizeof(buf) - sizeof(MOUNTMGR_MOUNT_POINT),nDosDriveNo, DeviceNamespaceDefault);
// Only symbolic link can be deleted with IOCTL_MOUNTMGR_DELETE_POINTS. If any other entry is specified, the mount manager will ignore subsequent IOCTL_MOUNTMGR_VOLUME_ARRIVAL_NOTIFICATION for the same volume ID.
in->SymbolicLinkNameOffset = sizeof (MOUNTMGR_MOUNT_POINT);
in->SymbolicLinkNameLength = (USHORT) wcslen ((PWCHAR) &in[1]) * 2;
ntStatus = TCDeviceIoControl (MOUNTMGR_DEVICE_NAME, IOCTL_MOUNTMGR_DELETE_POINTS,
in, sizeof(MOUNTMGR_MOUNT_POINT) + in->SymbolicLinkNameLength, out, sizeof out);
Dump ("IOCTL_MOUNTMGR_DELETE_POINTS returned 0x%08x\n", ntStatus);
return ntStatus;
}
NTSTATUS MountDevice (PDEVICE_OBJECT DeviceObject, MOUNT_STRUCT *mount)
{
PDEVICE_OBJECT NewDeviceObject;
NTSTATUS ntStatus;
// Make sure the user is asking for a reasonable nDosDriveNo
if (mount->nDosDriveNo >= 0 && mount->nDosDriveNo <= 25
&& IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceDefault) // drive letter must not exist both locally and globally
&& IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceGlobal)
)
{
Dump ("Mount request looks valid\n");
}
else
{
Dump ("WARNING: MOUNT DRIVE LETTER INVALID\n");
mount->nReturnCode = ERR_DRIVE_NOT_FOUND;
return ERR_DRIVE_NOT_FOUND;
}
if (!SelfTestsPassed)
{
Dump ("Failure of built-in automatic self-tests! Mounting not allowed.\n");
mount->nReturnCode = ERR_SELF_TESTS_FAILED;
return ERR_SELF_TESTS_FAILED;
}
ntStatus = TCCreateDeviceObject (DeviceObject->DriverObject, &NewDeviceObject, mount);
if (!NT_SUCCESS (ntStatus))
{
Dump ("Mount CREATE DEVICE ERROR, ntStatus = 0x%08x\n", ntStatus);
return ntStatus;
}
else
{
PEXTENSION NewExtension = (PEXTENSION) NewDeviceObject->DeviceExtension;
SECURITY_SUBJECT_CONTEXT subContext;
PACCESS_TOKEN accessToken;
SeCaptureSubjectContext (&subContext);
SeLockSubjectContext(&subContext);
if (subContext.ClientToken && subContext.ImpersonationLevel >= SecurityImpersonation)
accessToken = subContext.ClientToken;
else
accessToken = subContext.PrimaryToken;
if (!accessToken)
{
ntStatus = STATUS_INVALID_PARAMETER;
}
else
{
PTOKEN_USER tokenUser;
ntStatus = SeQueryInformationToken (accessToken, TokenUser, &tokenUser);
if (NT_SUCCESS (ntStatus))
{
ULONG sidLength = RtlLengthSid (tokenUser->User.Sid);
NewExtension->UserSid = TCalloc (sidLength);
if (!NewExtension->UserSid)
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
else
ntStatus = RtlCopySid (sidLength, NewExtension->UserSid, tokenUser->User.Sid);
ExFreePool (tokenUser); // Documented in newer versions of WDK
}
}
SeUnlockSubjectContext(&subContext);
SeReleaseSubjectContext (&subContext);
if (NT_SUCCESS (ntStatus))
ntStatus = TCStartVolumeThread (NewDeviceObject, NewExtension, mount);
if (!NT_SUCCESS (ntStatus))
{
Dump ("Mount FAILURE NT ERROR, ntStatus = 0x%08x\n", ntStatus);
TCDeleteDeviceObject (NewDeviceObject, NewExtension);
return ntStatus;
}
else
{
if (mount->nReturnCode == 0)
{
HANDLE volumeHandle;
PFILE_OBJECT volumeFileObject;
ULONG labelLen = (ULONG) wcslen (mount->wszLabel);
BOOL bIsNTFS = FALSE;
ULONG labelMaxLen, labelEffectiveLen;
Dump ("Mount SUCCESS TC code = 0x%08x READ-ONLY = %d\n", mount->nReturnCode, NewExtension->bReadOnly);
if (NewExtension->bReadOnly)
NewDeviceObject->Characteristics |= FILE_READ_ONLY_DEVICE;
NewDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
NewExtension->UniqueVolumeId = LastUniqueVolumeId++;
// check again that the drive letter is available globally and locally
if ( !IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceDefault)
|| !IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceGlobal)
)
{
TCDeleteDeviceObject (NewDeviceObject, NewExtension);
mount->nReturnCode = ERR_DRIVE_NOT_FOUND;
return ERR_DRIVE_NOT_FOUND;
}
if (mount->bMountManager)
MountManagerMount (mount);
NewExtension->bMountManager = mount->bMountManager;
// We create symbolic link even if mount manager is notified of
// arriving volume as it apparently sometimes fails to create the link
CreateDriveLink (mount->nDosDriveNo);
mount->FilesystemDirty = FALSE;
if (NT_SUCCESS (TCOpenFsVolume (NewExtension, &volumeHandle, &volumeFileObject)))
{
__try
{
ULONG fsStatus;
if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_IS_VOLUME_DIRTY, NULL, 0, &fsStatus, sizeof (fsStatus)))
&& (fsStatus & VOLUME_IS_DIRTY))
{
mount->FilesystemDirty = TRUE;
}
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
mount->FilesystemDirty = TRUE;
}
// detect if the filesystem is NTFS or FAT
__try
{
NTFS_VOLUME_DATA_BUFFER ntfsData;
if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_GET_NTFS_VOLUME_DATA, NULL, 0, &ntfsData, sizeof (ntfsData))))
{
bIsNTFS = TRUE;
}
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
bIsNTFS = FALSE;
}
NewExtension->bIsNTFS = bIsNTFS;
mount->bIsNTFS = bIsNTFS;
if (labelLen > 0)
{
if (bIsNTFS)
labelMaxLen = 32; // NTFS maximum label length
else
labelMaxLen = 11; // FAT maximum label length
// calculate label effective length
labelEffectiveLen = labelLen > labelMaxLen? labelMaxLen : labelLen;
// correct the label in the device
memset (&NewExtension->wszLabel[labelEffectiveLen], 0, 33 - labelEffectiveLen);
memcpy (mount->wszLabel, NewExtension->wszLabel, 33);
// set the volume label
__try
{
IO_STATUS_BLOCK ioblock;
ULONG labelInfoSize = sizeof(FILE_FS_LABEL_INFORMATION) + (labelEffectiveLen * sizeof(WCHAR));
FILE_FS_LABEL_INFORMATION* labelInfo = (FILE_FS_LABEL_INFORMATION*) TCalloc (labelInfoSize);
if (labelInfo)
{
labelInfo->VolumeLabelLength = labelEffectiveLen * sizeof(WCHAR);
memcpy (labelInfo->VolumeLabel, mount->wszLabel, labelInfo->VolumeLabelLength);
if (STATUS_SUCCESS == ZwSetVolumeInformationFile (volumeHandle, &ioblock, labelInfo, labelInfoSize, FileFsLabelInformation))
{
mount->bDriverSetLabel = TRUE;
NewExtension->bDriverSetLabel = TRUE;
}
TCfree(labelInfo);
}
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
}
}
TCCloseFsVolume (volumeHandle, volumeFileObject);
}
}
else
{
Dump ("Mount FAILURE TC code = 0x%08x\n", mount->nReturnCode);
TCDeleteDeviceObject (NewDeviceObject, NewExtension);
}
return STATUS_SUCCESS;
}
}
}
NTSTATUS UnmountDevice (UNMOUNT_STRUCT *unmountRequest, PDEVICE_OBJECT deviceObject, BOOL ignoreOpenFiles)
{
PEXTENSION extension = deviceObject->DeviceExtension;
NTSTATUS ntStatus;
HANDLE volumeHandle;
PFILE_OBJECT volumeFileObject;
Dump ("UnmountDevice %d\n", extension->nDosDriveNo);
ntStatus = TCOpenFsVolume (extension, &volumeHandle, &volumeFileObject);
if (NT_SUCCESS (ntStatus))
{
int dismountRetry;
// Dismounting a writable NTFS filesystem prevents the driver from being unloaded on Windows 7
if (IsOSAtLeast (WIN_7) && !extension->bReadOnly)
{
NTFS_VOLUME_DATA_BUFFER ntfsData;
if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_GET_NTFS_VOLUME_DATA, NULL, 0, &ntfsData, sizeof (ntfsData))))
DriverUnloadDisabled = TRUE;
}
// Lock volume
ntStatus = TCFsctlCall (volumeFileObject, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0);
Dump ("FSCTL_LOCK_VOLUME returned %X\n", ntStatus);
if (!NT_SUCCESS (ntStatus) && !ignoreOpenFiles)
{
TCCloseFsVolume (volumeHandle, volumeFileObject);
return ERR_FILES_OPEN;
}
// Dismount volume
for (dismountRetry = 0; dismountRetry < 200; ++dismountRetry)
{
ntStatus = TCFsctlCall (volumeFileObject, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0);
Dump ("FSCTL_DISMOUNT_VOLUME returned %X\n", ntStatus);
if (NT_SUCCESS (ntStatus) || ntStatus == STATUS_VOLUME_DISMOUNTED)
break;
if (!ignoreOpenFiles)
{
TCCloseFsVolume (volumeHandle, volumeFileObject);
return ERR_FILES_OPEN;
}
TCSleep (100);
}
}
else
{
// Volume cannot be opened => force dismount if allowed
if (!ignoreOpenFiles)
return ERR_FILES_OPEN;
else
volumeHandle = NULL;
}
if (extension->bMountManager)
MountManagerUnmount (extension->nDosDriveNo);
// We always remove symbolic link as mount manager might fail to do so
RemoveDriveLink (extension->nDosDriveNo);
extension->bShuttingDown = TRUE;
ntStatus = IoAcquireRemoveLock (&extension->Queue.RemoveLock, NULL);
ASSERT (NT_SUCCESS (ntStatus));
IoReleaseRemoveLockAndWait (&extension->Queue.RemoveLock, NULL);
if (volumeHandle != NULL)
TCCloseFsVolume (volumeHandle, volumeFileObject);
if (unmountRequest)
{
PCRYPTO_INFO cryptoInfo = ((PEXTENSION) deviceObject->DeviceExtension)->cryptoInfo;
unmountRequest->HiddenVolumeProtectionTriggered = (cryptoInfo->bProtectHiddenVolume && cryptoInfo->bHiddenVolProtectionAction);
}
TCDeleteDeviceObject (deviceObject, (PEXTENSION) deviceObject->DeviceExtension);
return 0;
}
static PDEVICE_OBJECT FindVolumeWithHighestUniqueId (int maxUniqueId)
{
PDEVICE_OBJECT highestIdDevice = NULL;
int highestId = -1;
int drive;
for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive)
{
PDEVICE_OBJECT device = GetVirtualVolumeDeviceObject (drive);
if (device)
{
PEXTENSION extension = (PEXTENSION) device->DeviceExtension;
if (extension->UniqueVolumeId > highestId && extension->UniqueVolumeId <= maxUniqueId)
{
highestId = extension->UniqueVolumeId;
highestIdDevice = device;
}
}
}
return highestIdDevice;
}
NTSTATUS UnmountAllDevices (UNMOUNT_STRUCT *unmountRequest, BOOL ignoreOpenFiles)
{
NTSTATUS status = 0;
PDEVICE_OBJECT ListDevice;
int maxUniqueId = LastUniqueVolumeId;
Dump ("Unmounting all volumes\n");
if (unmountRequest)
unmountRequest->HiddenVolumeProtectionTriggered = FALSE;
// Dismount volumes in the reverse order they were mounted to properly dismount nested volumes
while ((ListDevice = FindVolumeWithHighestUniqueId (maxUniqueId)) != NULL)
{
PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension;
maxUniqueId = ListExtension->UniqueVolumeId - 1;
if (IsVolumeAccessibleByCurrentUser (ListExtension))
{
NTSTATUS ntStatus;
if (unmountRequest)
unmountRequest->nDosDriveNo = ListExtension->nDosDriveNo;
ntStatus = UnmountDevice (unmountRequest, ListDevice, ignoreOpenFiles);
status = ntStatus == 0 ? status : ntStatus;
if (unmountRequest && unmountRequest->HiddenVolumeProtectionTriggered)
break;
}
}
return status;
}
// Resolves symbolic link name to its target name
NTSTATUS SymbolicLinkToTarget (PWSTR symlinkName, PWSTR targetName, USHORT maxTargetNameLength)
{
NTSTATUS ntStatus;
OBJECT_ATTRIBUTES objectAttributes;
UNICODE_STRING fullFileName;
HANDLE handle;
RtlInitUnicodeString (&fullFileName, symlinkName);
InitializeObjectAttributes (&objectAttributes, &fullFileName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL);
ntStatus = ZwOpenSymbolicLinkObject (&handle, GENERIC_READ, &objectAttributes);
if (NT_SUCCESS (ntStatus))
{
UNICODE_STRING target;
target.Buffer = targetName;
target.Length = 0;
target.MaximumLength = maxTargetNameLength;
memset (targetName, 0, maxTargetNameLength);
ntStatus = ZwQuerySymbolicLinkObject (handle, &target, NULL);
ZwClose (handle);
}
return ntStatus;
}
// Checks if two regions overlap (borders are parts of regions)
BOOL RegionsOverlap (unsigned __int64 start1, unsigned __int64 end1, unsigned __int64 start2, unsigned __int64 end2)
{
return (start1 < start2) ? (end1 >= start2) : (start1 <= end2);
}
void GetIntersection (uint64 start1, uint32 length1, uint64 start2, uint64 end2, uint64 *intersectStart, uint32 *intersectLength)
{
uint64 end1 = start1 + length1 - 1;
uint64 intersectEnd = (end1 <= end2) ? end1 : end2;
*intersectStart = (start1 >= start2) ? start1 : start2;
*intersectLength = (uint32) ((*intersectStart > intersectEnd) ? 0 : intersectEnd + 1 - *intersectStart);
if (*intersectLength == 0)
*intersectStart = start1;
}
BOOL IsAccessibleByUser (PUNICODE_STRING objectFileName, BOOL readOnly)
{
OBJECT_ATTRIBUTES fileObjAttributes;
IO_STATUS_BLOCK ioStatusBlock;
HANDLE fileHandle;
NTSTATUS status;
ASSERT (!IoIsSystemThread (PsGetCurrentThread()));
InitializeObjectAttributes (&fileObjAttributes, objectFileName, OBJ_CASE_INSENSITIVE | OBJ_FORCE_ACCESS_CHECK | OBJ_KERNEL_HANDLE, NULL, NULL);
status = ZwCreateFile (&fileHandle,
readOnly ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE,
&fileObjAttributes,
&ioStatusBlock,
NULL,
FILE_ATTRIBUTE_NORMAL,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
FILE_OPEN,
FILE_SYNCHRONOUS_IO_NONALERT,
NULL,
0);
if (NT_SUCCESS (status))
{
ZwClose (fileHandle);
return TRUE;
}
return FALSE;
}
BOOL UserCanAccessDriveDevice ()
{
UNICODE_STRING name;
RtlInitUnicodeString (&name, L"\\Device\\MountPointManager");
return IsAccessibleByUser (&name, FALSE);
}
BOOL IsDriveLetterAvailable (int nDosDriveNo, DeviceNamespaceType namespaceType)
{
OBJECT_ATTRIBUTES objectAttributes;
UNICODE_STRING objectName;
WCHAR link[128];
HANDLE handle;
NTSTATUS ntStatus;
TCGetDosNameFromNumber (link, sizeof(link),nDosDriveNo, namespaceType);
RtlInitUnicodeString (&objectName, link);
InitializeObjectAttributes (&objectAttributes, &objectName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL);
if (NT_SUCCESS (ntStatus = ZwOpenSymbolicLinkObject (&handle, GENERIC_READ, &objectAttributes)))
{
ZwClose (handle);
return FALSE;
}
return (ntStatus == STATUS_OBJECT_NAME_NOT_FOUND)? TRUE : FALSE;
}
NTSTATUS TCCompleteIrp (PIRP irp, NTSTATUS status, ULONG_PTR information)
{
irp->IoStatus.Status = status;
irp->IoStatus.Information = information;
IoCompleteRequest (irp, IO_NO_INCREMENT);
return status;
}
NTSTATUS TCCompleteDiskIrp (PIRP irp, NTSTATUS status, ULONG_PTR information)
{
irp->IoStatus.Status = status;
irp->IoStatus.Information = information;
IoCompleteRequest (irp, NT_SUCCESS (status) ? IO_DISK_INCREMENT : IO_NO_INCREMENT);
return status;
}
size_t GetCpuCount ()
{
KAFFINITY activeCpuMap = KeQueryActiveProcessors();
size_t mapSize = sizeof (activeCpuMap) * 8;
size_t cpuCount = 0;
while (mapSize--)
{
if (activeCpuMap & 1)
++cpuCount;
activeCpuMap >>= 1;
}
if (cpuCount == 0)
return 1;
return cpuCount;
}
void EnsureNullTerminatedString (wchar_t *str, size_t maxSizeInBytes)
{
ASSERT ((maxSizeInBytes & 1) == 0);
str[maxSizeInBytes / sizeof (wchar_t) - 1] = 0;
}
void *AllocateMemoryWithTimeout (size_t size, int retryDelay, int timeout)
{
LARGE_INTEGER waitInterval;
waitInterval.QuadPart = retryDelay * -10000;
ASSERT (KeGetCurrentIrql() <= APC_LEVEL);
ASSERT (retryDelay > 0 && retryDelay <= timeout);
while (TRUE)
{
void *memory = TCalloc (size);
if (memory)
return memory;
timeout -= retryDelay;
if (timeout <= 0)
break;
KeDelayExecutionThread (KernelMode, FALSE, &waitInterval);
}
return NULL;
}
NTSTATUS TCReadRegistryKey (PUNICODE_STRING keyPath, wchar_t *keyValueName, PKEY_VALUE_PARTIAL_INFORMATION *keyData)
{
OBJECT_ATTRIBUTES regObjAttribs;
HANDLE regKeyHandle;
NTSTATUS status;
UNICODE_STRING valName;
ULONG size = 0;
ULONG resultSize;
InitializeObjectAttributes (®ObjAttribs, keyPath, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL);
status = ZwOpenKey (®KeyHandle, KEY_READ, ®ObjAttribs);
if (!NT_SUCCESS (status))
return status;
RtlInitUnicodeString (&valName, keyValueName);
status = ZwQueryValueKey (regKeyHandle, &valName, KeyValuePartialInformation, NULL, 0, &size);
if (!NT_SUCCESS (status) && status != STATUS_BUFFER_OVERFLOW && status != STATUS_BUFFER_TOO_SMALL)
{
ZwClose (regKeyHandle);
return status;
}
if (size == 0)
{
ZwClose (regKeyHandle);
return STATUS_NO_DATA_DETECTED;
}
*keyData = (PKEY_VALUE_PARTIAL_INFORMATION) TCalloc (size);
if (!*keyData)
{
ZwClose (regKeyHandle);
return STATUS_INSUFFICIENT_RESOURCES;
}
status = ZwQueryValueKey (regKeyHandle, &valName, KeyValuePartialInformation, *keyData, size, &resultSize);
ZwClose (regKeyHandle);
return status;
}
NTSTATUS TCWriteRegistryKey (PUNICODE_STRING keyPath, wchar_t *keyValueName, ULONG keyValueType, void *valueData, ULONG valueSize)
{
OBJECT_ATTRIBUTES regObjAttribs;
HANDLE regKeyHandle;
NTSTATUS status;
UNICODE_STRING valName;
InitializeObjectAttributes (®ObjAttribs, keyPath, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL);
status = ZwOpenKey (®KeyHandle, KEY_READ | KEY_WRITE, ®ObjAttribs);
if (!NT_SUCCESS (status))
return status;
RtlInitUnicodeString (&valName, keyValueName);
status = ZwSetValueKey (regKeyHandle, &valName, 0, keyValueType, valueData, valueSize);
ZwClose (regKeyHandle);
return status;
}
BOOL IsVolumeClassFilterRegistered ()
{
UNICODE_STRING name;
NTSTATUS status;
BOOL registered = FALSE;
PKEY_VALUE_PARTIAL_INFORMATION data;
RtlInitUnicodeString (&name, L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{71A27CDD-812A-11D0-BEC7-08002BE2092F}");
status = TCReadRegistryKey (&name, L"UpperFilters", &data);
if (NT_SUCCESS (status))
{
if (data->Type == REG_MULTI_SZ && data->DataLength >= 9 * sizeof (wchar_t))
{
// Search for the string "veracrypt"
ULONG i;
for (i = 0; i <= data->DataLength - 9 * sizeof (wchar_t); ++i)
{
if (memcmp (data->Data + i, L"veracrypt", 9 * sizeof (wchar_t)) == 0)
{
Dump ("Volume class filter active\n");
registered = TRUE;
break;
}
}
}
TCfree (data);
}
return registered;
}
NTSTATUS ReadRegistryConfigFlags (BOOL driverEntry)
{
PKEY_VALUE_PARTIAL_INFORMATION data;
UNICODE_STRING name;
NTSTATUS status;
uint32 flags = 0;
RtlInitUnicodeString (&name, L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Services\\veracrypt");
status = TCReadRegistryKey (&name, TC_DRIVER_CONFIG_REG_VALUE_NAME, &data);
if (NT_SUCCESS (status))
{
if (data->Type == REG_DWORD)
{
flags = *(uint32 *) data->Data;
Dump ("Configuration flags = 0x%x\n", flags);
if (driverEntry)
{
if (flags & (TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD | TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES))
CacheBootPassword = TRUE;
if (flags & TC_DRIVER_CONFIG_DISABLE_NONADMIN_SYS_FAVORITES_ACCESS)
NonAdminSystemFavoritesAccessDisabled = TRUE;
if (flags & TC_DRIVER_CONFIG_CACHE_BOOT_PIM)
CacheBootPim = TRUE;
if (flags & VC_DRIVER_CONFIG_BLOCK_SYS_TRIM)
BlockSystemTrimCommand = TRUE;
}
EnableHwEncryption ((flags & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? FALSE : TRUE);
EnableExtendedIoctlSupport = (flags & TC_DRIVER_CONFIG_ENABLE_EXTENDED_IOCTL)? TRUE : FALSE;
AllowTrimCommand = (flags & VC_DRIVER_CONFIG_ALLOW_NONSYS_TRIM)? TRUE : FALSE;
AllowWindowsDefrag = (flags & VC_DRIVER_CONFIG_ALLOW_WINDOWS_DEFRAG)? TRUE : FALSE;
}
else
status = STATUS_INVALID_PARAMETER;
TCfree (data);
}
if (driverEntry && NT_SUCCESS (TCReadRegistryKey (&name, TC_ENCRYPTION_FREE_CPU_COUNT_REG_VALUE_NAME, &data)))
{
if (data->Type == REG_DWORD)
EncryptionThreadPoolFreeCpuCountLimit = *(uint32 *) data->Data;
TCfree (data);
}
return status;
}
NTSTATUS WriteRegistryConfigFlags (uint32 flags)
{
UNICODE_STRING name;
RtlInitUnicodeString (&name, L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Services\\veracrypt");
return TCWriteRegistryKey (&name, TC_DRIVER_CONFIG_REG_VALUE_NAME, REG_DWORD, &flags, sizeof (flags));
}
NTSTATUS GetDeviceSectorSize (PDEVICE_OBJECT deviceObject, ULONG *bytesPerSector)
{
NTSTATUS status;
DISK_GEOMETRY geometry;
status = SendDeviceIoControlRequest (deviceObject, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &geometry, sizeof (geometry));
if (!NT_SUCCESS (status))
return status;
*bytesPerSector = geometry.BytesPerSector;
return STATUS_SUCCESS;
}
NTSTATUS ZeroUnreadableSectors (PDEVICE_OBJECT deviceObject, LARGE_INTEGER startOffset, ULONG size, uint64 *zeroedSectorCount)
{
NTSTATUS status;
ULONG sectorSize;
ULONG sectorCount;
byte *sectorBuffer = NULL;
*zeroedSectorCount = 0;
status = GetDeviceSectorSize (deviceObject, §orSize);
if (!NT_SUCCESS (status))
return status;
sectorBuffer = TCalloc (sectorSize);
if (!sectorBuffer)
return STATUS_INSUFFICIENT_RESOURCES;
for (sectorCount = size / sectorSize; sectorCount > 0; --sectorCount, startOffset.QuadPart += sectorSize)
{
status = TCReadDevice (deviceObject, sectorBuffer, startOffset, sectorSize);
if (!NT_SUCCESS (status))
{
Dump ("Zeroing sector at %I64d\n", startOffset.QuadPart);
memset (sectorBuffer, 0, sectorSize);
status = TCWriteDevice (deviceObject, sectorBuffer, startOffset, sectorSize);
if (!NT_SUCCESS (status))
goto err;
++(*zeroedSectorCount);
}
}
status = STATUS_SUCCESS;
err:
if (sectorBuffer)
TCfree (sectorBuffer);
return status;
}
NTSTATUS ReadDeviceSkipUnreadableSectors (PDEVICE_OBJECT deviceObject, byte *buffer, LARGE_INTEGER startOffset, ULONG size, uint64 *badSectorCount)
{
NTSTATUS status;
ULONG sectorSize;
ULONG sectorCount;
*badSectorCount = 0;
status = GetDeviceSectorSize (deviceObject, §orSize);
if (!NT_SUCCESS (status))
return status;
for (sectorCount = size / sectorSize; sectorCount > 0; --sectorCount, startOffset.QuadPart += sectorSize, buffer += sectorSize)
{
status = TCReadDevice (deviceObject, buffer, startOffset, sectorSize);
if (!NT_SUCCESS (status))
{
Dump ("Skipping bad sector at %I64d\n", startOffset.QuadPart);
memset (buffer, 0, sectorSize);
++(*badSectorCount);
}
}
return STATUS_SUCCESS;
}
BOOL IsVolumeAccessibleByCurrentUser (PEXTENSION volumeDeviceExtension)
{
SECURITY_SUBJECT_CONTEXT subContext;
PACCESS_TOKEN accessToken;
PTOKEN_USER tokenUser;
BOOL result = FALSE;
if (IoIsSystemThread (PsGetCurrentThread())
|| UserCanAccessDriveDevice()
|| !volumeDeviceExtension->UserSid
|| (volumeDeviceExtension->SystemFavorite && !NonAdminSystemFavoritesAccessDisabled))
{
return TRUE;
}
SeCaptureSubjectContext (&subContext);
SeLockSubjectContext(&subContext);
if (subContext.ClientToken && subContext.ImpersonationLevel >= SecurityImpersonation)
accessToken = subContext.ClientToken;
else
accessToken = subContext.PrimaryToken;
if (!accessToken)
goto ret;
if (SeTokenIsAdmin (accessToken))
{
result = TRUE;
goto ret;
}
if (!NT_SUCCESS (SeQueryInformationToken (accessToken, TokenUser, &tokenUser)))
goto ret;
result = RtlEqualSid (volumeDeviceExtension->UserSid, tokenUser->User.Sid);
ExFreePool (tokenUser); // Documented in newer versions of WDK
ret:
SeUnlockSubjectContext(&subContext);
SeReleaseSubjectContext (&subContext);
return result;
}
void GetElapsedTimeInit (LARGE_INTEGER *lastPerfCounter)
{
*lastPerfCounter = KeQueryPerformanceCounter (NULL);
}
// Returns elapsed time in microseconds since last call
int64 GetElapsedTime (LARGE_INTEGER *lastPerfCounter)
{
LARGE_INTEGER freq;
LARGE_INTEGER counter = KeQueryPerformanceCounter (&freq);
int64 elapsed = (counter.QuadPart - lastPerfCounter->QuadPart) * 1000000LL / freq.QuadPart;
*lastPerfCounter = counter;
return elapsed;
}
BOOL IsOSAtLeast (OSVersionEnum reqMinOS)
{
/* When updating this function, update IsOSVersionAtLeast() in Dlgcode.c too. */
ULONG major = 0, minor = 0;
ASSERT (OsMajorVersion != 0);
switch (reqMinOS)
{
case WIN_2000: major = 5; minor = 0; break;
case WIN_XP: major = 5; minor = 1; break;
case WIN_SERVER_2003: major = 5; minor = 2; break;
case WIN_VISTA: major = 6; minor = 0; break;
case WIN_7: major = 6; minor = 1; break;
case WIN_8: major = 6; minor = 2; break;
case WIN_8_1: major = 6; minor = 3; break;
case WIN_10: major = 10; minor = 0; break;
default:
TC_THROW_FATAL_EXCEPTION;
break;
}
return ((OsMajorVersion << 16 | OsMinorVersion << 8)
>= (major << 16 | minor << 8));
}
NTSTATUS NTAPI KeSaveExtendedProcessorState (
__in ULONG64 Mask,
PXSTATE_SAVE XStateSave
)
{
if (KeSaveExtendedProcessorStatePtr)
{
return (KeSaveExtendedProcessorStatePtr) (Mask, XStateSave);
}
else
{
return STATUS_SUCCESS;
}
}
VOID NTAPI KeRestoreExtendedProcessorState (
PXSTATE_SAVE XStateSave
)
{
if (KeRestoreExtendedProcessorStatePtr)
{
(KeRestoreExtendedProcessorStatePtr) (XStateSave);
}
} | ./CrossVul/dataset_final_sorted/CWE-119/c/good_715_0 |
crossvul-cpp_data_good_4907_2 | /*
* kernel/sched/core.c
*
* Kernel scheduler and related syscalls
*
* Copyright (C) 1991-2002 Linus Torvalds
*
* 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
* make semaphores SMP safe
* 1998-11-19 Implemented schedule_timeout() and related stuff
* by Andrea Arcangeli
* 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
* hybrid priority-list and round-robin design with
* an array-switch method of distributing timeslices
* and per-CPU runqueues. Cleanups and useful suggestions
* by Davide Libenzi, preemptible kernel bits by Robert Love.
* 2003-09-03 Interactivity tuning by Con Kolivas.
* 2004-04-02 Scheduler domains code by Nick Piggin
* 2007-04-15 Work begun on replacing all interactivity tuning with a
* fair scheduling design by Con Kolivas.
* 2007-05-05 Load balancing (smp-nice) and other improvements
* by Peter Williams
* 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
* 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
* 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
* Thomas Gleixner, Mike Kravetz
*/
#include <linux/kasan.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/nmi.h>
#include <linux/init.h>
#include <linux/uaccess.h>
#include <linux/highmem.h>
#include <linux/mmu_context.h>
#include <linux/interrupt.h>
#include <linux/capability.h>
#include <linux/completion.h>
#include <linux/kernel_stat.h>
#include <linux/debug_locks.h>
#include <linux/perf_event.h>
#include <linux/security.h>
#include <linux/notifier.h>
#include <linux/profile.h>
#include <linux/freezer.h>
#include <linux/vmalloc.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/pid_namespace.h>
#include <linux/smp.h>
#include <linux/threads.h>
#include <linux/timer.h>
#include <linux/rcupdate.h>
#include <linux/cpu.h>
#include <linux/cpuset.h>
#include <linux/percpu.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/sysctl.h>
#include <linux/syscalls.h>
#include <linux/times.h>
#include <linux/tsacct_kern.h>
#include <linux/kprobes.h>
#include <linux/delayacct.h>
#include <linux/unistd.h>
#include <linux/pagemap.h>
#include <linux/hrtimer.h>
#include <linux/tick.h>
#include <linux/ctype.h>
#include <linux/ftrace.h>
#include <linux/slab.h>
#include <linux/init_task.h>
#include <linux/context_tracking.h>
#include <linux/compiler.h>
#include <linux/frame.h>
#include <asm/switch_to.h>
#include <asm/tlb.h>
#include <asm/irq_regs.h>
#include <asm/mutex.h>
#ifdef CONFIG_PARAVIRT
#include <asm/paravirt.h>
#endif
#include "sched.h"
#include "../workqueue_internal.h"
#include "../smpboot.h"
#define CREATE_TRACE_POINTS
#include <trace/events/sched.h>
DEFINE_MUTEX(sched_domains_mutex);
DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
static void update_rq_clock_task(struct rq *rq, s64 delta);
void update_rq_clock(struct rq *rq)
{
s64 delta;
lockdep_assert_held(&rq->lock);
if (rq->clock_skip_update & RQCF_ACT_SKIP)
return;
delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
if (delta < 0)
return;
rq->clock += delta;
update_rq_clock_task(rq, delta);
}
/*
* Debugging: various feature bits
*/
#define SCHED_FEAT(name, enabled) \
(1UL << __SCHED_FEAT_##name) * enabled |
const_debug unsigned int sysctl_sched_features =
#include "features.h"
0;
#undef SCHED_FEAT
/*
* Number of tasks to iterate in a single balance run.
* Limited because this is done with IRQs disabled.
*/
const_debug unsigned int sysctl_sched_nr_migrate = 32;
/*
* period over which we average the RT time consumption, measured
* in ms.
*
* default: 1s
*/
const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
/*
* period over which we measure -rt task cpu usage in us.
* default: 1s
*/
unsigned int sysctl_sched_rt_period = 1000000;
__read_mostly int scheduler_running;
/*
* part of the period that we allow rt tasks to run in us.
* default: 0.95s
*/
int sysctl_sched_rt_runtime = 950000;
/* cpus with isolated domains */
cpumask_var_t cpu_isolated_map;
/*
* this_rq_lock - lock this runqueue and disable interrupts.
*/
static struct rq *this_rq_lock(void)
__acquires(rq->lock)
{
struct rq *rq;
local_irq_disable();
rq = this_rq();
raw_spin_lock(&rq->lock);
return rq;
}
/*
* __task_rq_lock - lock the rq @p resides on.
*/
struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
__acquires(rq->lock)
{
struct rq *rq;
lockdep_assert_held(&p->pi_lock);
for (;;) {
rq = task_rq(p);
raw_spin_lock(&rq->lock);
if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
rf->cookie = lockdep_pin_lock(&rq->lock);
return rq;
}
raw_spin_unlock(&rq->lock);
while (unlikely(task_on_rq_migrating(p)))
cpu_relax();
}
}
/*
* task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
*/
struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
__acquires(p->pi_lock)
__acquires(rq->lock)
{
struct rq *rq;
for (;;) {
raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
rq = task_rq(p);
raw_spin_lock(&rq->lock);
/*
* move_queued_task() task_rq_lock()
*
* ACQUIRE (rq->lock)
* [S] ->on_rq = MIGRATING [L] rq = task_rq()
* WMB (__set_task_cpu()) ACQUIRE (rq->lock);
* [S] ->cpu = new_cpu [L] task_rq()
* [L] ->on_rq
* RELEASE (rq->lock)
*
* If we observe the old cpu in task_rq_lock, the acquire of
* the old rq->lock will fully serialize against the stores.
*
* If we observe the new cpu in task_rq_lock, the acquire will
* pair with the WMB to ensure we must then also see migrating.
*/
if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
rf->cookie = lockdep_pin_lock(&rq->lock);
return rq;
}
raw_spin_unlock(&rq->lock);
raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
while (unlikely(task_on_rq_migrating(p)))
cpu_relax();
}
}
#ifdef CONFIG_SCHED_HRTICK
/*
* Use HR-timers to deliver accurate preemption points.
*/
static void hrtick_clear(struct rq *rq)
{
if (hrtimer_active(&rq->hrtick_timer))
hrtimer_cancel(&rq->hrtick_timer);
}
/*
* High-resolution timer tick.
* Runs from hardirq context with interrupts disabled.
*/
static enum hrtimer_restart hrtick(struct hrtimer *timer)
{
struct rq *rq = container_of(timer, struct rq, hrtick_timer);
WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
raw_spin_lock(&rq->lock);
update_rq_clock(rq);
rq->curr->sched_class->task_tick(rq, rq->curr, 1);
raw_spin_unlock(&rq->lock);
return HRTIMER_NORESTART;
}
#ifdef CONFIG_SMP
static void __hrtick_restart(struct rq *rq)
{
struct hrtimer *timer = &rq->hrtick_timer;
hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
}
/*
* called from hardirq (IPI) context
*/
static void __hrtick_start(void *arg)
{
struct rq *rq = arg;
raw_spin_lock(&rq->lock);
__hrtick_restart(rq);
rq->hrtick_csd_pending = 0;
raw_spin_unlock(&rq->lock);
}
/*
* Called to set the hrtick timer state.
*
* called with rq->lock held and irqs disabled
*/
void hrtick_start(struct rq *rq, u64 delay)
{
struct hrtimer *timer = &rq->hrtick_timer;
ktime_t time;
s64 delta;
/*
* Don't schedule slices shorter than 10000ns, that just
* doesn't make sense and can cause timer DoS.
*/
delta = max_t(s64, delay, 10000LL);
time = ktime_add_ns(timer->base->get_time(), delta);
hrtimer_set_expires(timer, time);
if (rq == this_rq()) {
__hrtick_restart(rq);
} else if (!rq->hrtick_csd_pending) {
smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
rq->hrtick_csd_pending = 1;
}
}
#else
/*
* Called to set the hrtick timer state.
*
* called with rq->lock held and irqs disabled
*/
void hrtick_start(struct rq *rq, u64 delay)
{
/*
* Don't schedule slices shorter than 10000ns, that just
* doesn't make sense. Rely on vruntime for fairness.
*/
delay = max_t(u64, delay, 10000LL);
hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
HRTIMER_MODE_REL_PINNED);
}
#endif /* CONFIG_SMP */
static void init_rq_hrtick(struct rq *rq)
{
#ifdef CONFIG_SMP
rq->hrtick_csd_pending = 0;
rq->hrtick_csd.flags = 0;
rq->hrtick_csd.func = __hrtick_start;
rq->hrtick_csd.info = rq;
#endif
hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
rq->hrtick_timer.function = hrtick;
}
#else /* CONFIG_SCHED_HRTICK */
static inline void hrtick_clear(struct rq *rq)
{
}
static inline void init_rq_hrtick(struct rq *rq)
{
}
#endif /* CONFIG_SCHED_HRTICK */
/*
* cmpxchg based fetch_or, macro so it works for different integer types
*/
#define fetch_or(ptr, mask) \
({ \
typeof(ptr) _ptr = (ptr); \
typeof(mask) _mask = (mask); \
typeof(*_ptr) _old, _val = *_ptr; \
\
for (;;) { \
_old = cmpxchg(_ptr, _val, _val | _mask); \
if (_old == _val) \
break; \
_val = _old; \
} \
_old; \
})
#if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
/*
* Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
* this avoids any races wrt polling state changes and thereby avoids
* spurious IPIs.
*/
static bool set_nr_and_not_polling(struct task_struct *p)
{
struct thread_info *ti = task_thread_info(p);
return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
}
/*
* Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
*
* If this returns true, then the idle task promises to call
* sched_ttwu_pending() and reschedule soon.
*/
static bool set_nr_if_polling(struct task_struct *p)
{
struct thread_info *ti = task_thread_info(p);
typeof(ti->flags) old, val = READ_ONCE(ti->flags);
for (;;) {
if (!(val & _TIF_POLLING_NRFLAG))
return false;
if (val & _TIF_NEED_RESCHED)
return true;
old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
if (old == val)
break;
val = old;
}
return true;
}
#else
static bool set_nr_and_not_polling(struct task_struct *p)
{
set_tsk_need_resched(p);
return true;
}
#ifdef CONFIG_SMP
static bool set_nr_if_polling(struct task_struct *p)
{
return false;
}
#endif
#endif
void wake_q_add(struct wake_q_head *head, struct task_struct *task)
{
struct wake_q_node *node = &task->wake_q;
/*
* Atomically grab the task, if ->wake_q is !nil already it means
* its already queued (either by us or someone else) and will get the
* wakeup due to that.
*
* This cmpxchg() implies a full barrier, which pairs with the write
* barrier implied by the wakeup in wake_up_q().
*/
if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
return;
get_task_struct(task);
/*
* The head is context local, there can be no concurrency.
*/
*head->lastp = node;
head->lastp = &node->next;
}
void wake_up_q(struct wake_q_head *head)
{
struct wake_q_node *node = head->first;
while (node != WAKE_Q_TAIL) {
struct task_struct *task;
task = container_of(node, struct task_struct, wake_q);
BUG_ON(!task);
/* task can safely be re-inserted now */
node = node->next;
task->wake_q.next = NULL;
/*
* wake_up_process() implies a wmb() to pair with the queueing
* in wake_q_add() so as not to miss wakeups.
*/
wake_up_process(task);
put_task_struct(task);
}
}
/*
* resched_curr - mark rq's current task 'to be rescheduled now'.
*
* On UP this means the setting of the need_resched flag, on SMP it
* might also involve a cross-CPU call to trigger the scheduler on
* the target CPU.
*/
void resched_curr(struct rq *rq)
{
struct task_struct *curr = rq->curr;
int cpu;
lockdep_assert_held(&rq->lock);
if (test_tsk_need_resched(curr))
return;
cpu = cpu_of(rq);
if (cpu == smp_processor_id()) {
set_tsk_need_resched(curr);
set_preempt_need_resched();
return;
}
if (set_nr_and_not_polling(curr))
smp_send_reschedule(cpu);
else
trace_sched_wake_idle_without_ipi(cpu);
}
void resched_cpu(int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long flags;
if (!raw_spin_trylock_irqsave(&rq->lock, flags))
return;
resched_curr(rq);
raw_spin_unlock_irqrestore(&rq->lock, flags);
}
#ifdef CONFIG_SMP
#ifdef CONFIG_NO_HZ_COMMON
/*
* In the semi idle case, use the nearest busy cpu for migrating timers
* from an idle cpu. This is good for power-savings.
*
* We don't do similar optimization for completely idle system, as
* selecting an idle cpu will add more delays to the timers than intended
* (as that cpu's timer base may not be uptodate wrt jiffies etc).
*/
int get_nohz_timer_target(void)
{
int i, cpu = smp_processor_id();
struct sched_domain *sd;
if (!idle_cpu(cpu) && is_housekeeping_cpu(cpu))
return cpu;
rcu_read_lock();
for_each_domain(cpu, sd) {
for_each_cpu(i, sched_domain_span(sd)) {
if (cpu == i)
continue;
if (!idle_cpu(i) && is_housekeeping_cpu(i)) {
cpu = i;
goto unlock;
}
}
}
if (!is_housekeeping_cpu(cpu))
cpu = housekeeping_any_cpu();
unlock:
rcu_read_unlock();
return cpu;
}
/*
* When add_timer_on() enqueues a timer into the timer wheel of an
* idle CPU then this timer might expire before the next timer event
* which is scheduled to wake up that CPU. In case of a completely
* idle system the next event might even be infinite time into the
* future. wake_up_idle_cpu() ensures that the CPU is woken up and
* leaves the inner idle loop so the newly added timer is taken into
* account when the CPU goes back to idle and evaluates the timer
* wheel for the next timer event.
*/
static void wake_up_idle_cpu(int cpu)
{
struct rq *rq = cpu_rq(cpu);
if (cpu == smp_processor_id())
return;
if (set_nr_and_not_polling(rq->idle))
smp_send_reschedule(cpu);
else
trace_sched_wake_idle_without_ipi(cpu);
}
static bool wake_up_full_nohz_cpu(int cpu)
{
/*
* We just need the target to call irq_exit() and re-evaluate
* the next tick. The nohz full kick at least implies that.
* If needed we can still optimize that later with an
* empty IRQ.
*/
if (tick_nohz_full_cpu(cpu)) {
if (cpu != smp_processor_id() ||
tick_nohz_tick_stopped())
tick_nohz_full_kick_cpu(cpu);
return true;
}
return false;
}
void wake_up_nohz_cpu(int cpu)
{
if (!wake_up_full_nohz_cpu(cpu))
wake_up_idle_cpu(cpu);
}
static inline bool got_nohz_idle_kick(void)
{
int cpu = smp_processor_id();
if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
return false;
if (idle_cpu(cpu) && !need_resched())
return true;
/*
* We can't run Idle Load Balance on this CPU for this time so we
* cancel it and clear NOHZ_BALANCE_KICK
*/
clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
return false;
}
#else /* CONFIG_NO_HZ_COMMON */
static inline bool got_nohz_idle_kick(void)
{
return false;
}
#endif /* CONFIG_NO_HZ_COMMON */
#ifdef CONFIG_NO_HZ_FULL
bool sched_can_stop_tick(struct rq *rq)
{
int fifo_nr_running;
/* Deadline tasks, even if single, need the tick */
if (rq->dl.dl_nr_running)
return false;
/*
* If there are more than one RR tasks, we need the tick to effect the
* actual RR behaviour.
*/
if (rq->rt.rr_nr_running) {
if (rq->rt.rr_nr_running == 1)
return true;
else
return false;
}
/*
* If there's no RR tasks, but FIFO tasks, we can skip the tick, no
* forced preemption between FIFO tasks.
*/
fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
if (fifo_nr_running)
return true;
/*
* If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
* if there's more than one we need the tick for involuntary
* preemption.
*/
if (rq->nr_running > 1)
return false;
return true;
}
#endif /* CONFIG_NO_HZ_FULL */
void sched_avg_update(struct rq *rq)
{
s64 period = sched_avg_period();
while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
/*
* Inline assembly required to prevent the compiler
* optimising this loop into a divmod call.
* See __iter_div_u64_rem() for another example of this.
*/
asm("" : "+rm" (rq->age_stamp));
rq->age_stamp += period;
rq->rt_avg /= 2;
}
}
#endif /* CONFIG_SMP */
#if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
(defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
/*
* Iterate task_group tree rooted at *from, calling @down when first entering a
* node and @up when leaving it for the final time.
*
* Caller must hold rcu_lock or sufficient equivalent.
*/
int walk_tg_tree_from(struct task_group *from,
tg_visitor down, tg_visitor up, void *data)
{
struct task_group *parent, *child;
int ret;
parent = from;
down:
ret = (*down)(parent, data);
if (ret)
goto out;
list_for_each_entry_rcu(child, &parent->children, siblings) {
parent = child;
goto down;
up:
continue;
}
ret = (*up)(parent, data);
if (ret || parent == from)
goto out;
child = parent;
parent = parent->parent;
if (parent)
goto up;
out:
return ret;
}
int tg_nop(struct task_group *tg, void *data)
{
return 0;
}
#endif
static void set_load_weight(struct task_struct *p)
{
int prio = p->static_prio - MAX_RT_PRIO;
struct load_weight *load = &p->se.load;
/*
* SCHED_IDLE tasks get minimal weight:
*/
if (idle_policy(p->policy)) {
load->weight = scale_load(WEIGHT_IDLEPRIO);
load->inv_weight = WMULT_IDLEPRIO;
return;
}
load->weight = scale_load(sched_prio_to_weight[prio]);
load->inv_weight = sched_prio_to_wmult[prio];
}
static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
{
update_rq_clock(rq);
if (!(flags & ENQUEUE_RESTORE))
sched_info_queued(rq, p);
p->sched_class->enqueue_task(rq, p, flags);
}
static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
{
update_rq_clock(rq);
if (!(flags & DEQUEUE_SAVE))
sched_info_dequeued(rq, p);
p->sched_class->dequeue_task(rq, p, flags);
}
void activate_task(struct rq *rq, struct task_struct *p, int flags)
{
if (task_contributes_to_load(p))
rq->nr_uninterruptible--;
enqueue_task(rq, p, flags);
}
void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
{
if (task_contributes_to_load(p))
rq->nr_uninterruptible++;
dequeue_task(rq, p, flags);
}
static void update_rq_clock_task(struct rq *rq, s64 delta)
{
/*
* In theory, the compile should just see 0 here, and optimize out the call
* to sched_rt_avg_update. But I don't trust it...
*/
#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
s64 steal = 0, irq_delta = 0;
#endif
#ifdef CONFIG_IRQ_TIME_ACCOUNTING
irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
/*
* Since irq_time is only updated on {soft,}irq_exit, we might run into
* this case when a previous update_rq_clock() happened inside a
* {soft,}irq region.
*
* When this happens, we stop ->clock_task and only update the
* prev_irq_time stamp to account for the part that fit, so that a next
* update will consume the rest. This ensures ->clock_task is
* monotonic.
*
* It does however cause some slight miss-attribution of {soft,}irq
* time, a more accurate solution would be to update the irq_time using
* the current rq->clock timestamp, except that would require using
* atomic ops.
*/
if (irq_delta > delta)
irq_delta = delta;
rq->prev_irq_time += irq_delta;
delta -= irq_delta;
#endif
#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
if (static_key_false((¶virt_steal_rq_enabled))) {
steal = paravirt_steal_clock(cpu_of(rq));
steal -= rq->prev_steal_time_rq;
if (unlikely(steal > delta))
steal = delta;
rq->prev_steal_time_rq += steal;
delta -= steal;
}
#endif
rq->clock_task += delta;
#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
sched_rt_avg_update(rq, irq_delta + steal);
#endif
}
void sched_set_stop_task(int cpu, struct task_struct *stop)
{
struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
struct task_struct *old_stop = cpu_rq(cpu)->stop;
if (stop) {
/*
* Make it appear like a SCHED_FIFO task, its something
* userspace knows about and won't get confused about.
*
* Also, it will make PI more or less work without too
* much confusion -- but then, stop work should not
* rely on PI working anyway.
*/
sched_setscheduler_nocheck(stop, SCHED_FIFO, ¶m);
stop->sched_class = &stop_sched_class;
}
cpu_rq(cpu)->stop = stop;
if (old_stop) {
/*
* Reset it back to a normal scheduling class so that
* it can die in pieces.
*/
old_stop->sched_class = &rt_sched_class;
}
}
/*
* __normal_prio - return the priority that is based on the static prio
*/
static inline int __normal_prio(struct task_struct *p)
{
return p->static_prio;
}
/*
* Calculate the expected normal priority: i.e. priority
* without taking RT-inheritance into account. Might be
* boosted by interactivity modifiers. Changes upon fork,
* setprio syscalls, and whenever the interactivity
* estimator recalculates.
*/
static inline int normal_prio(struct task_struct *p)
{
int prio;
if (task_has_dl_policy(p))
prio = MAX_DL_PRIO-1;
else if (task_has_rt_policy(p))
prio = MAX_RT_PRIO-1 - p->rt_priority;
else
prio = __normal_prio(p);
return prio;
}
/*
* Calculate the current priority, i.e. the priority
* taken into account by the scheduler. This value might
* be boosted by RT tasks, or might be boosted by
* interactivity modifiers. Will be RT if the task got
* RT-boosted. If not then it returns p->normal_prio.
*/
static int effective_prio(struct task_struct *p)
{
p->normal_prio = normal_prio(p);
/*
* If we are RT tasks or we were boosted to RT priority,
* keep the priority unchanged. Otherwise, update priority
* to the normal priority:
*/
if (!rt_prio(p->prio))
return p->normal_prio;
return p->prio;
}
/**
* task_curr - is this task currently executing on a CPU?
* @p: the task in question.
*
* Return: 1 if the task is currently executing. 0 otherwise.
*/
inline int task_curr(const struct task_struct *p)
{
return cpu_curr(task_cpu(p)) == p;
}
/*
* switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
* use the balance_callback list if you want balancing.
*
* this means any call to check_class_changed() must be followed by a call to
* balance_callback().
*/
static inline void check_class_changed(struct rq *rq, struct task_struct *p,
const struct sched_class *prev_class,
int oldprio)
{
if (prev_class != p->sched_class) {
if (prev_class->switched_from)
prev_class->switched_from(rq, p);
p->sched_class->switched_to(rq, p);
} else if (oldprio != p->prio || dl_task(p))
p->sched_class->prio_changed(rq, p, oldprio);
}
void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
{
const struct sched_class *class;
if (p->sched_class == rq->curr->sched_class) {
rq->curr->sched_class->check_preempt_curr(rq, p, flags);
} else {
for_each_class(class) {
if (class == rq->curr->sched_class)
break;
if (class == p->sched_class) {
resched_curr(rq);
break;
}
}
}
/*
* A queue event has occurred, and we're going to schedule. In
* this case, we can save a useless back to back clock update.
*/
if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
rq_clock_skip_update(rq, true);
}
#ifdef CONFIG_SMP
/*
* This is how migration works:
*
* 1) we invoke migration_cpu_stop() on the target CPU using
* stop_one_cpu().
* 2) stopper starts to run (implicitly forcing the migrated thread
* off the CPU)
* 3) it checks whether the migrated task is still in the wrong runqueue.
* 4) if it's in the wrong runqueue then the migration thread removes
* it and puts it into the right queue.
* 5) stopper completes and stop_one_cpu() returns and the migration
* is done.
*/
/*
* move_queued_task - move a queued task to new rq.
*
* Returns (locked) new rq. Old rq's lock is released.
*/
static struct rq *move_queued_task(struct rq *rq, struct task_struct *p, int new_cpu)
{
lockdep_assert_held(&rq->lock);
p->on_rq = TASK_ON_RQ_MIGRATING;
dequeue_task(rq, p, 0);
set_task_cpu(p, new_cpu);
raw_spin_unlock(&rq->lock);
rq = cpu_rq(new_cpu);
raw_spin_lock(&rq->lock);
BUG_ON(task_cpu(p) != new_cpu);
enqueue_task(rq, p, 0);
p->on_rq = TASK_ON_RQ_QUEUED;
check_preempt_curr(rq, p, 0);
return rq;
}
struct migration_arg {
struct task_struct *task;
int dest_cpu;
};
/*
* Move (not current) task off this cpu, onto dest cpu. We're doing
* this because either it can't run here any more (set_cpus_allowed()
* away from this CPU, or CPU going down), or because we're
* attempting to rebalance this task on exec (sched_exec).
*
* So we race with normal scheduler movements, but that's OK, as long
* as the task is no longer on this CPU.
*/
static struct rq *__migrate_task(struct rq *rq, struct task_struct *p, int dest_cpu)
{
if (unlikely(!cpu_active(dest_cpu)))
return rq;
/* Affinity changed (again). */
if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
return rq;
rq = move_queued_task(rq, p, dest_cpu);
return rq;
}
/*
* migration_cpu_stop - this will be executed by a highprio stopper thread
* and performs thread migration by bumping thread off CPU then
* 'pushing' onto another runqueue.
*/
static int migration_cpu_stop(void *data)
{
struct migration_arg *arg = data;
struct task_struct *p = arg->task;
struct rq *rq = this_rq();
/*
* The original target cpu might have gone down and we might
* be on another cpu but it doesn't matter.
*/
local_irq_disable();
/*
* We need to explicitly wake pending tasks before running
* __migrate_task() such that we will not miss enforcing cpus_allowed
* during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
*/
sched_ttwu_pending();
raw_spin_lock(&p->pi_lock);
raw_spin_lock(&rq->lock);
/*
* If task_rq(p) != rq, it cannot be migrated here, because we're
* holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
* we're holding p->pi_lock.
*/
if (task_rq(p) == rq && task_on_rq_queued(p))
rq = __migrate_task(rq, p, arg->dest_cpu);
raw_spin_unlock(&rq->lock);
raw_spin_unlock(&p->pi_lock);
local_irq_enable();
return 0;
}
/*
* sched_class::set_cpus_allowed must do the below, but is not required to
* actually call this function.
*/
void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
{
cpumask_copy(&p->cpus_allowed, new_mask);
p->nr_cpus_allowed = cpumask_weight(new_mask);
}
void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
{
struct rq *rq = task_rq(p);
bool queued, running;
lockdep_assert_held(&p->pi_lock);
queued = task_on_rq_queued(p);
running = task_current(rq, p);
if (queued) {
/*
* Because __kthread_bind() calls this on blocked tasks without
* holding rq->lock.
*/
lockdep_assert_held(&rq->lock);
dequeue_task(rq, p, DEQUEUE_SAVE);
}
if (running)
put_prev_task(rq, p);
p->sched_class->set_cpus_allowed(p, new_mask);
if (running)
p->sched_class->set_curr_task(rq);
if (queued)
enqueue_task(rq, p, ENQUEUE_RESTORE);
}
/*
* Change a given task's CPU affinity. Migrate the thread to a
* proper CPU and schedule it away if the CPU it's executing on
* is removed from the allowed bitmask.
*
* NOTE: the caller must have a valid reference to the task, the
* task must not exit() & deallocate itself prematurely. The
* call is not atomic; no spinlocks may be held.
*/
static int __set_cpus_allowed_ptr(struct task_struct *p,
const struct cpumask *new_mask, bool check)
{
const struct cpumask *cpu_valid_mask = cpu_active_mask;
unsigned int dest_cpu;
struct rq_flags rf;
struct rq *rq;
int ret = 0;
rq = task_rq_lock(p, &rf);
if (p->flags & PF_KTHREAD) {
/*
* Kernel threads are allowed on online && !active CPUs
*/
cpu_valid_mask = cpu_online_mask;
}
/*
* Must re-check here, to close a race against __kthread_bind(),
* sched_setaffinity() is not guaranteed to observe the flag.
*/
if (check && (p->flags & PF_NO_SETAFFINITY)) {
ret = -EINVAL;
goto out;
}
if (cpumask_equal(&p->cpus_allowed, new_mask))
goto out;
if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
ret = -EINVAL;
goto out;
}
do_set_cpus_allowed(p, new_mask);
if (p->flags & PF_KTHREAD) {
/*
* For kernel threads that do indeed end up on online &&
* !active we want to ensure they are strict per-cpu threads.
*/
WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
!cpumask_intersects(new_mask, cpu_active_mask) &&
p->nr_cpus_allowed != 1);
}
/* Can the task run on the task's current CPU? If so, we're done */
if (cpumask_test_cpu(task_cpu(p), new_mask))
goto out;
dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
if (task_running(rq, p) || p->state == TASK_WAKING) {
struct migration_arg arg = { p, dest_cpu };
/* Need help from migration thread: drop lock and wait. */
task_rq_unlock(rq, p, &rf);
stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
tlb_migrate_finish(p->mm);
return 0;
} else if (task_on_rq_queued(p)) {
/*
* OK, since we're going to drop the lock immediately
* afterwards anyway.
*/
lockdep_unpin_lock(&rq->lock, rf.cookie);
rq = move_queued_task(rq, p, dest_cpu);
lockdep_repin_lock(&rq->lock, rf.cookie);
}
out:
task_rq_unlock(rq, p, &rf);
return ret;
}
int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
{
return __set_cpus_allowed_ptr(p, new_mask, false);
}
EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
{
#ifdef CONFIG_SCHED_DEBUG
/*
* We should never call set_task_cpu() on a blocked task,
* ttwu() will sort out the placement.
*/
WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
!p->on_rq);
/*
* Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
* because schedstat_wait_{start,end} rebase migrating task's wait_start
* time relying on p->on_rq.
*/
WARN_ON_ONCE(p->state == TASK_RUNNING &&
p->sched_class == &fair_sched_class &&
(p->on_rq && !task_on_rq_migrating(p)));
#ifdef CONFIG_LOCKDEP
/*
* The caller should hold either p->pi_lock or rq->lock, when changing
* a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
*
* sched_move_task() holds both and thus holding either pins the cgroup,
* see task_group().
*
* Furthermore, all task_rq users should acquire both locks, see
* task_rq_lock().
*/
WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
lockdep_is_held(&task_rq(p)->lock)));
#endif
#endif
trace_sched_migrate_task(p, new_cpu);
if (task_cpu(p) != new_cpu) {
if (p->sched_class->migrate_task_rq)
p->sched_class->migrate_task_rq(p);
p->se.nr_migrations++;
perf_event_task_migrate(p);
}
__set_task_cpu(p, new_cpu);
}
static void __migrate_swap_task(struct task_struct *p, int cpu)
{
if (task_on_rq_queued(p)) {
struct rq *src_rq, *dst_rq;
src_rq = task_rq(p);
dst_rq = cpu_rq(cpu);
p->on_rq = TASK_ON_RQ_MIGRATING;
deactivate_task(src_rq, p, 0);
set_task_cpu(p, cpu);
activate_task(dst_rq, p, 0);
p->on_rq = TASK_ON_RQ_QUEUED;
check_preempt_curr(dst_rq, p, 0);
} else {
/*
* Task isn't running anymore; make it appear like we migrated
* it before it went to sleep. This means on wakeup we make the
* previous cpu our targer instead of where it really is.
*/
p->wake_cpu = cpu;
}
}
struct migration_swap_arg {
struct task_struct *src_task, *dst_task;
int src_cpu, dst_cpu;
};
static int migrate_swap_stop(void *data)
{
struct migration_swap_arg *arg = data;
struct rq *src_rq, *dst_rq;
int ret = -EAGAIN;
if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
return -EAGAIN;
src_rq = cpu_rq(arg->src_cpu);
dst_rq = cpu_rq(arg->dst_cpu);
double_raw_lock(&arg->src_task->pi_lock,
&arg->dst_task->pi_lock);
double_rq_lock(src_rq, dst_rq);
if (task_cpu(arg->dst_task) != arg->dst_cpu)
goto unlock;
if (task_cpu(arg->src_task) != arg->src_cpu)
goto unlock;
if (!cpumask_test_cpu(arg->dst_cpu, tsk_cpus_allowed(arg->src_task)))
goto unlock;
if (!cpumask_test_cpu(arg->src_cpu, tsk_cpus_allowed(arg->dst_task)))
goto unlock;
__migrate_swap_task(arg->src_task, arg->dst_cpu);
__migrate_swap_task(arg->dst_task, arg->src_cpu);
ret = 0;
unlock:
double_rq_unlock(src_rq, dst_rq);
raw_spin_unlock(&arg->dst_task->pi_lock);
raw_spin_unlock(&arg->src_task->pi_lock);
return ret;
}
/*
* Cross migrate two tasks
*/
int migrate_swap(struct task_struct *cur, struct task_struct *p)
{
struct migration_swap_arg arg;
int ret = -EINVAL;
arg = (struct migration_swap_arg){
.src_task = cur,
.src_cpu = task_cpu(cur),
.dst_task = p,
.dst_cpu = task_cpu(p),
};
if (arg.src_cpu == arg.dst_cpu)
goto out;
/*
* These three tests are all lockless; this is OK since all of them
* will be re-checked with proper locks held further down the line.
*/
if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
goto out;
if (!cpumask_test_cpu(arg.dst_cpu, tsk_cpus_allowed(arg.src_task)))
goto out;
if (!cpumask_test_cpu(arg.src_cpu, tsk_cpus_allowed(arg.dst_task)))
goto out;
trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
out:
return ret;
}
/*
* wait_task_inactive - wait for a thread to unschedule.
*
* If @match_state is nonzero, it's the @p->state value just checked and
* not expected to change. If it changes, i.e. @p might have woken up,
* then return zero. When we succeed in waiting for @p to be off its CPU,
* we return a positive number (its total switch count). If a second call
* a short while later returns the same number, the caller can be sure that
* @p has remained unscheduled the whole time.
*
* The caller must ensure that the task *will* unschedule sometime soon,
* else this function might spin for a *long* time. This function can't
* be called with interrupts off, or it may introduce deadlock with
* smp_call_function() if an IPI is sent by the same process we are
* waiting to become inactive.
*/
unsigned long wait_task_inactive(struct task_struct *p, long match_state)
{
int running, queued;
struct rq_flags rf;
unsigned long ncsw;
struct rq *rq;
for (;;) {
/*
* We do the initial early heuristics without holding
* any task-queue locks at all. We'll only try to get
* the runqueue lock when things look like they will
* work out!
*/
rq = task_rq(p);
/*
* If the task is actively running on another CPU
* still, just relax and busy-wait without holding
* any locks.
*
* NOTE! Since we don't hold any locks, it's not
* even sure that "rq" stays as the right runqueue!
* But we don't care, since "task_running()" will
* return false if the runqueue has changed and p
* is actually now running somewhere else!
*/
while (task_running(rq, p)) {
if (match_state && unlikely(p->state != match_state))
return 0;
cpu_relax();
}
/*
* Ok, time to look more closely! We need the rq
* lock now, to be *sure*. If we're wrong, we'll
* just go back and repeat.
*/
rq = task_rq_lock(p, &rf);
trace_sched_wait_task(p);
running = task_running(rq, p);
queued = task_on_rq_queued(p);
ncsw = 0;
if (!match_state || p->state == match_state)
ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
task_rq_unlock(rq, p, &rf);
/*
* If it changed from the expected state, bail out now.
*/
if (unlikely(!ncsw))
break;
/*
* Was it really running after all now that we
* checked with the proper locks actually held?
*
* Oops. Go back and try again..
*/
if (unlikely(running)) {
cpu_relax();
continue;
}
/*
* It's not enough that it's not actively running,
* it must be off the runqueue _entirely_, and not
* preempted!
*
* So if it was still runnable (but just not actively
* running right now), it's preempted, and we should
* yield - it could be a while.
*/
if (unlikely(queued)) {
ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_hrtimeout(&to, HRTIMER_MODE_REL);
continue;
}
/*
* Ahh, all good. It wasn't running, and it wasn't
* runnable, which means that it will never become
* running in the future either. We're all done!
*/
break;
}
return ncsw;
}
/***
* kick_process - kick a running thread to enter/exit the kernel
* @p: the to-be-kicked thread
*
* Cause a process which is running on another CPU to enter
* kernel-mode, without any delay. (to get signals handled.)
*
* NOTE: this function doesn't have to take the runqueue lock,
* because all it wants to ensure is that the remote task enters
* the kernel. If the IPI races and the task has been migrated
* to another CPU then no harm is done and the purpose has been
* achieved as well.
*/
void kick_process(struct task_struct *p)
{
int cpu;
preempt_disable();
cpu = task_cpu(p);
if ((cpu != smp_processor_id()) && task_curr(p))
smp_send_reschedule(cpu);
preempt_enable();
}
EXPORT_SYMBOL_GPL(kick_process);
/*
* ->cpus_allowed is protected by both rq->lock and p->pi_lock
*
* A few notes on cpu_active vs cpu_online:
*
* - cpu_active must be a subset of cpu_online
*
* - on cpu-up we allow per-cpu kthreads on the online && !active cpu,
* see __set_cpus_allowed_ptr(). At this point the newly online
* cpu isn't yet part of the sched domains, and balancing will not
* see it.
*
* - on cpu-down we clear cpu_active() to mask the sched domains and
* avoid the load balancer to place new tasks on the to be removed
* cpu. Existing tasks will remain running there and will be taken
* off.
*
* This means that fallback selection must not select !active CPUs.
* And can assume that any active CPU must be online. Conversely
* select_task_rq() below may allow selection of !active CPUs in order
* to satisfy the above rules.
*/
static int select_fallback_rq(int cpu, struct task_struct *p)
{
int nid = cpu_to_node(cpu);
const struct cpumask *nodemask = NULL;
enum { cpuset, possible, fail } state = cpuset;
int dest_cpu;
/*
* If the node that the cpu is on has been offlined, cpu_to_node()
* will return -1. There is no cpu on the node, and we should
* select the cpu on the other node.
*/
if (nid != -1) {
nodemask = cpumask_of_node(nid);
/* Look for allowed, online CPU in same node. */
for_each_cpu(dest_cpu, nodemask) {
if (!cpu_active(dest_cpu))
continue;
if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
return dest_cpu;
}
}
for (;;) {
/* Any allowed, online CPU? */
for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
if (!cpu_active(dest_cpu))
continue;
goto out;
}
/* No more Mr. Nice Guy. */
switch (state) {
case cpuset:
if (IS_ENABLED(CONFIG_CPUSETS)) {
cpuset_cpus_allowed_fallback(p);
state = possible;
break;
}
/* fall-through */
case possible:
do_set_cpus_allowed(p, cpu_possible_mask);
state = fail;
break;
case fail:
BUG();
break;
}
}
out:
if (state != cpuset) {
/*
* Don't tell them about moving exiting tasks or
* kernel threads (both mm NULL), since they never
* leave kernel.
*/
if (p->mm && printk_ratelimit()) {
printk_deferred("process %d (%s) no longer affine to cpu%d\n",
task_pid_nr(p), p->comm, cpu);
}
}
return dest_cpu;
}
/*
* The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
*/
static inline
int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
{
lockdep_assert_held(&p->pi_lock);
if (tsk_nr_cpus_allowed(p) > 1)
cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
else
cpu = cpumask_any(tsk_cpus_allowed(p));
/*
* In order not to call set_task_cpu() on a blocking task we need
* to rely on ttwu() to place the task on a valid ->cpus_allowed
* cpu.
*
* Since this is common to all placement strategies, this lives here.
*
* [ this allows ->select_task() to simply return task_cpu(p) and
* not worry about this generic constraint ]
*/
if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
!cpu_online(cpu)))
cpu = select_fallback_rq(task_cpu(p), p);
return cpu;
}
static void update_avg(u64 *avg, u64 sample)
{
s64 diff = sample - *avg;
*avg += diff >> 3;
}
#else
static inline int __set_cpus_allowed_ptr(struct task_struct *p,
const struct cpumask *new_mask, bool check)
{
return set_cpus_allowed_ptr(p, new_mask);
}
#endif /* CONFIG_SMP */
static void
ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
{
#ifdef CONFIG_SCHEDSTATS
struct rq *rq = this_rq();
#ifdef CONFIG_SMP
int this_cpu = smp_processor_id();
if (cpu == this_cpu) {
schedstat_inc(rq, ttwu_local);
schedstat_inc(p, se.statistics.nr_wakeups_local);
} else {
struct sched_domain *sd;
schedstat_inc(p, se.statistics.nr_wakeups_remote);
rcu_read_lock();
for_each_domain(this_cpu, sd) {
if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
schedstat_inc(sd, ttwu_wake_remote);
break;
}
}
rcu_read_unlock();
}
if (wake_flags & WF_MIGRATED)
schedstat_inc(p, se.statistics.nr_wakeups_migrate);
#endif /* CONFIG_SMP */
schedstat_inc(rq, ttwu_count);
schedstat_inc(p, se.statistics.nr_wakeups);
if (wake_flags & WF_SYNC)
schedstat_inc(p, se.statistics.nr_wakeups_sync);
#endif /* CONFIG_SCHEDSTATS */
}
static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
{
activate_task(rq, p, en_flags);
p->on_rq = TASK_ON_RQ_QUEUED;
/* if a worker is waking up, notify workqueue */
if (p->flags & PF_WQ_WORKER)
wq_worker_waking_up(p, cpu_of(rq));
}
/*
* Mark the task runnable and perform wakeup-preemption.
*/
static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
struct pin_cookie cookie)
{
check_preempt_curr(rq, p, wake_flags);
p->state = TASK_RUNNING;
trace_sched_wakeup(p);
#ifdef CONFIG_SMP
if (p->sched_class->task_woken) {
/*
* Our task @p is fully woken up and running; so its safe to
* drop the rq->lock, hereafter rq is only used for statistics.
*/
lockdep_unpin_lock(&rq->lock, cookie);
p->sched_class->task_woken(rq, p);
lockdep_repin_lock(&rq->lock, cookie);
}
if (rq->idle_stamp) {
u64 delta = rq_clock(rq) - rq->idle_stamp;
u64 max = 2*rq->max_idle_balance_cost;
update_avg(&rq->avg_idle, delta);
if (rq->avg_idle > max)
rq->avg_idle = max;
rq->idle_stamp = 0;
}
#endif
}
static void
ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
struct pin_cookie cookie)
{
int en_flags = ENQUEUE_WAKEUP;
lockdep_assert_held(&rq->lock);
#ifdef CONFIG_SMP
if (p->sched_contributes_to_load)
rq->nr_uninterruptible--;
if (wake_flags & WF_MIGRATED)
en_flags |= ENQUEUE_MIGRATED;
#endif
ttwu_activate(rq, p, en_flags);
ttwu_do_wakeup(rq, p, wake_flags, cookie);
}
/*
* Called in case the task @p isn't fully descheduled from its runqueue,
* in this case we must do a remote wakeup. Its a 'light' wakeup though,
* since all we need to do is flip p->state to TASK_RUNNING, since
* the task is still ->on_rq.
*/
static int ttwu_remote(struct task_struct *p, int wake_flags)
{
struct rq_flags rf;
struct rq *rq;
int ret = 0;
rq = __task_rq_lock(p, &rf);
if (task_on_rq_queued(p)) {
/* check_preempt_curr() may use rq clock */
update_rq_clock(rq);
ttwu_do_wakeup(rq, p, wake_flags, rf.cookie);
ret = 1;
}
__task_rq_unlock(rq, &rf);
return ret;
}
#ifdef CONFIG_SMP
void sched_ttwu_pending(void)
{
struct rq *rq = this_rq();
struct llist_node *llist = llist_del_all(&rq->wake_list);
struct pin_cookie cookie;
struct task_struct *p;
unsigned long flags;
if (!llist)
return;
raw_spin_lock_irqsave(&rq->lock, flags);
cookie = lockdep_pin_lock(&rq->lock);
while (llist) {
int wake_flags = 0;
p = llist_entry(llist, struct task_struct, wake_entry);
llist = llist_next(llist);
if (p->sched_remote_wakeup)
wake_flags = WF_MIGRATED;
ttwu_do_activate(rq, p, wake_flags, cookie);
}
lockdep_unpin_lock(&rq->lock, cookie);
raw_spin_unlock_irqrestore(&rq->lock, flags);
}
void scheduler_ipi(void)
{
/*
* Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
* TIF_NEED_RESCHED remotely (for the first time) will also send
* this IPI.
*/
preempt_fold_need_resched();
if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
return;
/*
* Not all reschedule IPI handlers call irq_enter/irq_exit, since
* traditionally all their work was done from the interrupt return
* path. Now that we actually do some work, we need to make sure
* we do call them.
*
* Some archs already do call them, luckily irq_enter/exit nest
* properly.
*
* Arguably we should visit all archs and update all handlers,
* however a fair share of IPIs are still resched only so this would
* somewhat pessimize the simple resched case.
*/
irq_enter();
sched_ttwu_pending();
/*
* Check if someone kicked us for doing the nohz idle load balance.
*/
if (unlikely(got_nohz_idle_kick())) {
this_rq()->idle_balance = 1;
raise_softirq_irqoff(SCHED_SOFTIRQ);
}
irq_exit();
}
static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
{
struct rq *rq = cpu_rq(cpu);
p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
if (!set_nr_if_polling(rq->idle))
smp_send_reschedule(cpu);
else
trace_sched_wake_idle_without_ipi(cpu);
}
}
void wake_up_if_idle(int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long flags;
rcu_read_lock();
if (!is_idle_task(rcu_dereference(rq->curr)))
goto out;
if (set_nr_if_polling(rq->idle)) {
trace_sched_wake_idle_without_ipi(cpu);
} else {
raw_spin_lock_irqsave(&rq->lock, flags);
if (is_idle_task(rq->curr))
smp_send_reschedule(cpu);
/* Else cpu is not in idle, do nothing here */
raw_spin_unlock_irqrestore(&rq->lock, flags);
}
out:
rcu_read_unlock();
}
bool cpus_share_cache(int this_cpu, int that_cpu)
{
return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
}
#endif /* CONFIG_SMP */
static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
{
struct rq *rq = cpu_rq(cpu);
struct pin_cookie cookie;
#if defined(CONFIG_SMP)
if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
sched_clock_cpu(cpu); /* sync clocks x-cpu */
ttwu_queue_remote(p, cpu, wake_flags);
return;
}
#endif
raw_spin_lock(&rq->lock);
cookie = lockdep_pin_lock(&rq->lock);
ttwu_do_activate(rq, p, wake_flags, cookie);
lockdep_unpin_lock(&rq->lock, cookie);
raw_spin_unlock(&rq->lock);
}
/*
* Notes on Program-Order guarantees on SMP systems.
*
* MIGRATION
*
* The basic program-order guarantee on SMP systems is that when a task [t]
* migrates, all its activity on its old cpu [c0] happens-before any subsequent
* execution on its new cpu [c1].
*
* For migration (of runnable tasks) this is provided by the following means:
*
* A) UNLOCK of the rq(c0)->lock scheduling out task t
* B) migration for t is required to synchronize *both* rq(c0)->lock and
* rq(c1)->lock (if not at the same time, then in that order).
* C) LOCK of the rq(c1)->lock scheduling in task
*
* Transitivity guarantees that B happens after A and C after B.
* Note: we only require RCpc transitivity.
* Note: the cpu doing B need not be c0 or c1
*
* Example:
*
* CPU0 CPU1 CPU2
*
* LOCK rq(0)->lock
* sched-out X
* sched-in Y
* UNLOCK rq(0)->lock
*
* LOCK rq(0)->lock // orders against CPU0
* dequeue X
* UNLOCK rq(0)->lock
*
* LOCK rq(1)->lock
* enqueue X
* UNLOCK rq(1)->lock
*
* LOCK rq(1)->lock // orders against CPU2
* sched-out Z
* sched-in X
* UNLOCK rq(1)->lock
*
*
* BLOCKING -- aka. SLEEP + WAKEUP
*
* For blocking we (obviously) need to provide the same guarantee as for
* migration. However the means are completely different as there is no lock
* chain to provide order. Instead we do:
*
* 1) smp_store_release(X->on_cpu, 0)
* 2) smp_cond_acquire(!X->on_cpu)
*
* Example:
*
* CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
*
* LOCK rq(0)->lock LOCK X->pi_lock
* dequeue X
* sched-out X
* smp_store_release(X->on_cpu, 0);
*
* smp_cond_acquire(!X->on_cpu);
* X->state = WAKING
* set_task_cpu(X,2)
*
* LOCK rq(2)->lock
* enqueue X
* X->state = RUNNING
* UNLOCK rq(2)->lock
*
* LOCK rq(2)->lock // orders against CPU1
* sched-out Z
* sched-in X
* UNLOCK rq(2)->lock
*
* UNLOCK X->pi_lock
* UNLOCK rq(0)->lock
*
*
* However; for wakeups there is a second guarantee we must provide, namely we
* must observe the state that lead to our wakeup. That is, not only must our
* task observe its own prior state, it must also observe the stores prior to
* its wakeup.
*
* This means that any means of doing remote wakeups must order the CPU doing
* the wakeup against the CPU the task is going to end up running on. This,
* however, is already required for the regular Program-Order guarantee above,
* since the waking CPU is the one issueing the ACQUIRE (smp_cond_acquire).
*
*/
/**
* try_to_wake_up - wake up a thread
* @p: the thread to be awakened
* @state: the mask of task states that can be woken
* @wake_flags: wake modifier flags (WF_*)
*
* Put it on the run-queue if it's not already there. The "current"
* thread is always on the run-queue (except when the actual
* re-schedule is in progress), and as such you're allowed to do
* the simpler "current->state = TASK_RUNNING" to mark yourself
* runnable without the overhead of this.
*
* Return: %true if @p was woken up, %false if it was already running.
* or @state didn't match @p's state.
*/
static int
try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
{
unsigned long flags;
int cpu, success = 0;
/*
* If we are going to wake up a thread waiting for CONDITION we
* need to ensure that CONDITION=1 done by the caller can not be
* reordered with p->state check below. This pairs with mb() in
* set_current_state() the waiting thread does.
*/
smp_mb__before_spinlock();
raw_spin_lock_irqsave(&p->pi_lock, flags);
if (!(p->state & state))
goto out;
trace_sched_waking(p);
success = 1; /* we're going to change ->state */
cpu = task_cpu(p);
if (p->on_rq && ttwu_remote(p, wake_flags))
goto stat;
#ifdef CONFIG_SMP
/*
* Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
* possible to, falsely, observe p->on_cpu == 0.
*
* One must be running (->on_cpu == 1) in order to remove oneself
* from the runqueue.
*
* [S] ->on_cpu = 1; [L] ->on_rq
* UNLOCK rq->lock
* RMB
* LOCK rq->lock
* [S] ->on_rq = 0; [L] ->on_cpu
*
* Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
* from the consecutive calls to schedule(); the first switching to our
* task, the second putting it to sleep.
*/
smp_rmb();
/*
* If the owning (remote) cpu is still in the middle of schedule() with
* this task as prev, wait until its done referencing the task.
*
* Pairs with the smp_store_release() in finish_lock_switch().
*
* This ensures that tasks getting woken will be fully ordered against
* their previous state and preserve Program Order.
*/
smp_cond_acquire(!p->on_cpu);
p->sched_contributes_to_load = !!task_contributes_to_load(p);
p->state = TASK_WAKING;
cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
if (task_cpu(p) != cpu) {
wake_flags |= WF_MIGRATED;
set_task_cpu(p, cpu);
}
#endif /* CONFIG_SMP */
ttwu_queue(p, cpu, wake_flags);
stat:
if (schedstat_enabled())
ttwu_stat(p, cpu, wake_flags);
out:
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
return success;
}
/**
* try_to_wake_up_local - try to wake up a local task with rq lock held
* @p: the thread to be awakened
*
* Put @p on the run-queue if it's not already there. The caller must
* ensure that this_rq() is locked, @p is bound to this_rq() and not
* the current task.
*/
static void try_to_wake_up_local(struct task_struct *p, struct pin_cookie cookie)
{
struct rq *rq = task_rq(p);
if (WARN_ON_ONCE(rq != this_rq()) ||
WARN_ON_ONCE(p == current))
return;
lockdep_assert_held(&rq->lock);
if (!raw_spin_trylock(&p->pi_lock)) {
/*
* This is OK, because current is on_cpu, which avoids it being
* picked for load-balance and preemption/IRQs are still
* disabled avoiding further scheduler activity on it and we've
* not yet picked a replacement task.
*/
lockdep_unpin_lock(&rq->lock, cookie);
raw_spin_unlock(&rq->lock);
raw_spin_lock(&p->pi_lock);
raw_spin_lock(&rq->lock);
lockdep_repin_lock(&rq->lock, cookie);
}
if (!(p->state & TASK_NORMAL))
goto out;
trace_sched_waking(p);
if (!task_on_rq_queued(p))
ttwu_activate(rq, p, ENQUEUE_WAKEUP);
ttwu_do_wakeup(rq, p, 0, cookie);
if (schedstat_enabled())
ttwu_stat(p, smp_processor_id(), 0);
out:
raw_spin_unlock(&p->pi_lock);
}
/**
* wake_up_process - Wake up a specific process
* @p: The process to be woken up.
*
* Attempt to wake up the nominated process and move it to the set of runnable
* processes.
*
* Return: 1 if the process was woken up, 0 if it was already running.
*
* It may be assumed that this function implies a write memory barrier before
* changing the task state if and only if any tasks are woken up.
*/
int wake_up_process(struct task_struct *p)
{
return try_to_wake_up(p, TASK_NORMAL, 0);
}
EXPORT_SYMBOL(wake_up_process);
int wake_up_state(struct task_struct *p, unsigned int state)
{
return try_to_wake_up(p, state, 0);
}
/*
* This function clears the sched_dl_entity static params.
*/
void __dl_clear_params(struct task_struct *p)
{
struct sched_dl_entity *dl_se = &p->dl;
dl_se->dl_runtime = 0;
dl_se->dl_deadline = 0;
dl_se->dl_period = 0;
dl_se->flags = 0;
dl_se->dl_bw = 0;
dl_se->dl_throttled = 0;
dl_se->dl_yielded = 0;
}
/*
* Perform scheduler related setup for a newly forked process p.
* p is forked by current.
*
* __sched_fork() is basic setup used by init_idle() too:
*/
static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
{
p->on_rq = 0;
p->se.on_rq = 0;
p->se.exec_start = 0;
p->se.sum_exec_runtime = 0;
p->se.prev_sum_exec_runtime = 0;
p->se.nr_migrations = 0;
p->se.vruntime = 0;
INIT_LIST_HEAD(&p->se.group_node);
#ifdef CONFIG_FAIR_GROUP_SCHED
p->se.cfs_rq = NULL;
#endif
#ifdef CONFIG_SCHEDSTATS
/* Even if schedstat is disabled, there should not be garbage */
memset(&p->se.statistics, 0, sizeof(p->se.statistics));
#endif
RB_CLEAR_NODE(&p->dl.rb_node);
init_dl_task_timer(&p->dl);
__dl_clear_params(p);
INIT_LIST_HEAD(&p->rt.run_list);
p->rt.timeout = 0;
p->rt.time_slice = sched_rr_timeslice;
p->rt.on_rq = 0;
p->rt.on_list = 0;
#ifdef CONFIG_PREEMPT_NOTIFIERS
INIT_HLIST_HEAD(&p->preempt_notifiers);
#endif
#ifdef CONFIG_NUMA_BALANCING
if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
p->mm->numa_scan_seq = 0;
}
if (clone_flags & CLONE_VM)
p->numa_preferred_nid = current->numa_preferred_nid;
else
p->numa_preferred_nid = -1;
p->node_stamp = 0ULL;
p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
p->numa_scan_period = sysctl_numa_balancing_scan_delay;
p->numa_work.next = &p->numa_work;
p->numa_faults = NULL;
p->last_task_numa_placement = 0;
p->last_sum_exec_runtime = 0;
p->numa_group = NULL;
#endif /* CONFIG_NUMA_BALANCING */
}
DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
#ifdef CONFIG_NUMA_BALANCING
void set_numabalancing_state(bool enabled)
{
if (enabled)
static_branch_enable(&sched_numa_balancing);
else
static_branch_disable(&sched_numa_balancing);
}
#ifdef CONFIG_PROC_SYSCTL
int sysctl_numa_balancing(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
struct ctl_table t;
int err;
int state = static_branch_likely(&sched_numa_balancing);
if (write && !capable(CAP_SYS_ADMIN))
return -EPERM;
t = *table;
t.data = &state;
err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
if (err < 0)
return err;
if (write)
set_numabalancing_state(state);
return err;
}
#endif
#endif
#ifdef CONFIG_SCHEDSTATS
DEFINE_STATIC_KEY_FALSE(sched_schedstats);
static bool __initdata __sched_schedstats = false;
static void set_schedstats(bool enabled)
{
if (enabled)
static_branch_enable(&sched_schedstats);
else
static_branch_disable(&sched_schedstats);
}
void force_schedstat_enabled(void)
{
if (!schedstat_enabled()) {
pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
static_branch_enable(&sched_schedstats);
}
}
static int __init setup_schedstats(char *str)
{
int ret = 0;
if (!str)
goto out;
/*
* This code is called before jump labels have been set up, so we can't
* change the static branch directly just yet. Instead set a temporary
* variable so init_schedstats() can do it later.
*/
if (!strcmp(str, "enable")) {
__sched_schedstats = true;
ret = 1;
} else if (!strcmp(str, "disable")) {
__sched_schedstats = false;
ret = 1;
}
out:
if (!ret)
pr_warn("Unable to parse schedstats=\n");
return ret;
}
__setup("schedstats=", setup_schedstats);
static void __init init_schedstats(void)
{
set_schedstats(__sched_schedstats);
}
#ifdef CONFIG_PROC_SYSCTL
int sysctl_schedstats(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
struct ctl_table t;
int err;
int state = static_branch_likely(&sched_schedstats);
if (write && !capable(CAP_SYS_ADMIN))
return -EPERM;
t = *table;
t.data = &state;
err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
if (err < 0)
return err;
if (write)
set_schedstats(state);
return err;
}
#endif /* CONFIG_PROC_SYSCTL */
#else /* !CONFIG_SCHEDSTATS */
static inline void init_schedstats(void) {}
#endif /* CONFIG_SCHEDSTATS */
/*
* fork()/clone()-time setup:
*/
int sched_fork(unsigned long clone_flags, struct task_struct *p)
{
unsigned long flags;
int cpu = get_cpu();
__sched_fork(clone_flags, p);
/*
* We mark the process as running here. This guarantees that
* nobody will actually run it, and a signal or other external
* event cannot wake it up and insert it on the runqueue either.
*/
p->state = TASK_RUNNING;
/*
* Make sure we do not leak PI boosting priority to the child.
*/
p->prio = current->normal_prio;
/*
* Revert to default priority/policy on fork if requested.
*/
if (unlikely(p->sched_reset_on_fork)) {
if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
p->policy = SCHED_NORMAL;
p->static_prio = NICE_TO_PRIO(0);
p->rt_priority = 0;
} else if (PRIO_TO_NICE(p->static_prio) < 0)
p->static_prio = NICE_TO_PRIO(0);
p->prio = p->normal_prio = __normal_prio(p);
set_load_weight(p);
/*
* We don't need the reset flag anymore after the fork. It has
* fulfilled its duty:
*/
p->sched_reset_on_fork = 0;
}
if (dl_prio(p->prio)) {
put_cpu();
return -EAGAIN;
} else if (rt_prio(p->prio)) {
p->sched_class = &rt_sched_class;
} else {
p->sched_class = &fair_sched_class;
}
if (p->sched_class->task_fork)
p->sched_class->task_fork(p);
/*
* The child is not yet in the pid-hash so no cgroup attach races,
* and the cgroup is pinned to this child due to cgroup_fork()
* is ran before sched_fork().
*
* Silence PROVE_RCU.
*/
raw_spin_lock_irqsave(&p->pi_lock, flags);
set_task_cpu(p, cpu);
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
#ifdef CONFIG_SCHED_INFO
if (likely(sched_info_on()))
memset(&p->sched_info, 0, sizeof(p->sched_info));
#endif
#if defined(CONFIG_SMP)
p->on_cpu = 0;
#endif
init_task_preempt_count(p);
#ifdef CONFIG_SMP
plist_node_init(&p->pushable_tasks, MAX_PRIO);
RB_CLEAR_NODE(&p->pushable_dl_tasks);
#endif
put_cpu();
return 0;
}
unsigned long to_ratio(u64 period, u64 runtime)
{
if (runtime == RUNTIME_INF)
return 1ULL << 20;
/*
* Doing this here saves a lot of checks in all
* the calling paths, and returning zero seems
* safe for them anyway.
*/
if (period == 0)
return 0;
return div64_u64(runtime << 20, period);
}
#ifdef CONFIG_SMP
inline struct dl_bw *dl_bw_of(int i)
{
RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
"sched RCU must be held");
return &cpu_rq(i)->rd->dl_bw;
}
static inline int dl_bw_cpus(int i)
{
struct root_domain *rd = cpu_rq(i)->rd;
int cpus = 0;
RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
"sched RCU must be held");
for_each_cpu_and(i, rd->span, cpu_active_mask)
cpus++;
return cpus;
}
#else
inline struct dl_bw *dl_bw_of(int i)
{
return &cpu_rq(i)->dl.dl_bw;
}
static inline int dl_bw_cpus(int i)
{
return 1;
}
#endif
/*
* We must be sure that accepting a new task (or allowing changing the
* parameters of an existing one) is consistent with the bandwidth
* constraints. If yes, this function also accordingly updates the currently
* allocated bandwidth to reflect the new situation.
*
* This function is called while holding p's rq->lock.
*
* XXX we should delay bw change until the task's 0-lag point, see
* __setparam_dl().
*/
static int dl_overflow(struct task_struct *p, int policy,
const struct sched_attr *attr)
{
struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
u64 period = attr->sched_period ?: attr->sched_deadline;
u64 runtime = attr->sched_runtime;
u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
int cpus, err = -1;
/* !deadline task may carry old deadline bandwidth */
if (new_bw == p->dl.dl_bw && task_has_dl_policy(p))
return 0;
/*
* Either if a task, enters, leave, or stays -deadline but changes
* its parameters, we may need to update accordingly the total
* allocated bandwidth of the container.
*/
raw_spin_lock(&dl_b->lock);
cpus = dl_bw_cpus(task_cpu(p));
if (dl_policy(policy) && !task_has_dl_policy(p) &&
!__dl_overflow(dl_b, cpus, 0, new_bw)) {
__dl_add(dl_b, new_bw);
err = 0;
} else if (dl_policy(policy) && task_has_dl_policy(p) &&
!__dl_overflow(dl_b, cpus, p->dl.dl_bw, new_bw)) {
__dl_clear(dl_b, p->dl.dl_bw);
__dl_add(dl_b, new_bw);
err = 0;
} else if (!dl_policy(policy) && task_has_dl_policy(p)) {
__dl_clear(dl_b, p->dl.dl_bw);
err = 0;
}
raw_spin_unlock(&dl_b->lock);
return err;
}
extern void init_dl_bw(struct dl_bw *dl_b);
/*
* wake_up_new_task - wake up a newly created task for the first time.
*
* This function will do some initial scheduler statistics housekeeping
* that must be done for every newly created context, then puts the task
* on the runqueue and wakes it.
*/
void wake_up_new_task(struct task_struct *p)
{
struct rq_flags rf;
struct rq *rq;
/* Initialize new task's runnable average */
init_entity_runnable_average(&p->se);
raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
#ifdef CONFIG_SMP
/*
* Fork balancing, do it here and not earlier because:
* - cpus_allowed can change in the fork path
* - any previously selected cpu might disappear through hotplug
*/
set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
#endif
/* Post initialize new task's util average when its cfs_rq is set */
post_init_entity_util_avg(&p->se);
rq = __task_rq_lock(p, &rf);
activate_task(rq, p, 0);
p->on_rq = TASK_ON_RQ_QUEUED;
trace_sched_wakeup_new(p);
check_preempt_curr(rq, p, WF_FORK);
#ifdef CONFIG_SMP
if (p->sched_class->task_woken) {
/*
* Nothing relies on rq->lock after this, so its fine to
* drop it.
*/
lockdep_unpin_lock(&rq->lock, rf.cookie);
p->sched_class->task_woken(rq, p);
lockdep_repin_lock(&rq->lock, rf.cookie);
}
#endif
task_rq_unlock(rq, p, &rf);
}
#ifdef CONFIG_PREEMPT_NOTIFIERS
static struct static_key preempt_notifier_key = STATIC_KEY_INIT_FALSE;
void preempt_notifier_inc(void)
{
static_key_slow_inc(&preempt_notifier_key);
}
EXPORT_SYMBOL_GPL(preempt_notifier_inc);
void preempt_notifier_dec(void)
{
static_key_slow_dec(&preempt_notifier_key);
}
EXPORT_SYMBOL_GPL(preempt_notifier_dec);
/**
* preempt_notifier_register - tell me when current is being preempted & rescheduled
* @notifier: notifier struct to register
*/
void preempt_notifier_register(struct preempt_notifier *notifier)
{
if (!static_key_false(&preempt_notifier_key))
WARN(1, "registering preempt_notifier while notifiers disabled\n");
hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
}
EXPORT_SYMBOL_GPL(preempt_notifier_register);
/**
* preempt_notifier_unregister - no longer interested in preemption notifications
* @notifier: notifier struct to unregister
*
* This is *not* safe to call from within a preemption notifier.
*/
void preempt_notifier_unregister(struct preempt_notifier *notifier)
{
hlist_del(¬ifier->link);
}
EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
{
struct preempt_notifier *notifier;
hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
notifier->ops->sched_in(notifier, raw_smp_processor_id());
}
static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
{
if (static_key_false(&preempt_notifier_key))
__fire_sched_in_preempt_notifiers(curr);
}
static void
__fire_sched_out_preempt_notifiers(struct task_struct *curr,
struct task_struct *next)
{
struct preempt_notifier *notifier;
hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
notifier->ops->sched_out(notifier, next);
}
static __always_inline void
fire_sched_out_preempt_notifiers(struct task_struct *curr,
struct task_struct *next)
{
if (static_key_false(&preempt_notifier_key))
__fire_sched_out_preempt_notifiers(curr, next);
}
#else /* !CONFIG_PREEMPT_NOTIFIERS */
static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
{
}
static inline void
fire_sched_out_preempt_notifiers(struct task_struct *curr,
struct task_struct *next)
{
}
#endif /* CONFIG_PREEMPT_NOTIFIERS */
/**
* prepare_task_switch - prepare to switch tasks
* @rq: the runqueue preparing to switch
* @prev: the current task that is being switched out
* @next: the task we are going to switch to.
*
* This is called with the rq lock held and interrupts off. It must
* be paired with a subsequent finish_task_switch after the context
* switch.
*
* prepare_task_switch sets up locking and calls architecture specific
* hooks.
*/
static inline void
prepare_task_switch(struct rq *rq, struct task_struct *prev,
struct task_struct *next)
{
sched_info_switch(rq, prev, next);
perf_event_task_sched_out(prev, next);
fire_sched_out_preempt_notifiers(prev, next);
prepare_lock_switch(rq, next);
prepare_arch_switch(next);
}
/**
* finish_task_switch - clean up after a task-switch
* @prev: the thread we just switched away from.
*
* finish_task_switch must be called after the context switch, paired
* with a prepare_task_switch call before the context switch.
* finish_task_switch will reconcile locking set up by prepare_task_switch,
* and do any other architecture-specific cleanup actions.
*
* Note that we may have delayed dropping an mm in context_switch(). If
* so, we finish that here outside of the runqueue lock. (Doing it
* with the lock held can cause deadlocks; see schedule() for
* details.)
*
* The context switch have flipped the stack from under us and restored the
* local variables which were saved when this task called schedule() in the
* past. prev == current is still correct but we need to recalculate this_rq
* because prev may have moved to another CPU.
*/
static struct rq *finish_task_switch(struct task_struct *prev)
__releases(rq->lock)
{
struct rq *rq = this_rq();
struct mm_struct *mm = rq->prev_mm;
long prev_state;
/*
* The previous task will have left us with a preempt_count of 2
* because it left us after:
*
* schedule()
* preempt_disable(); // 1
* __schedule()
* raw_spin_lock_irq(&rq->lock) // 2
*
* Also, see FORK_PREEMPT_COUNT.
*/
if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
"corrupted preempt_count: %s/%d/0x%x\n",
current->comm, current->pid, preempt_count()))
preempt_count_set(FORK_PREEMPT_COUNT);
rq->prev_mm = NULL;
/*
* A task struct has one reference for the use as "current".
* If a task dies, then it sets TASK_DEAD in tsk->state and calls
* schedule one last time. The schedule call will never return, and
* the scheduled task must drop that reference.
*
* We must observe prev->state before clearing prev->on_cpu (in
* finish_lock_switch), otherwise a concurrent wakeup can get prev
* running on another CPU and we could rave with its RUNNING -> DEAD
* transition, resulting in a double drop.
*/
prev_state = prev->state;
vtime_task_switch(prev);
perf_event_task_sched_in(prev, current);
finish_lock_switch(rq, prev);
finish_arch_post_lock_switch();
fire_sched_in_preempt_notifiers(current);
if (mm)
mmdrop(mm);
if (unlikely(prev_state == TASK_DEAD)) {
if (prev->sched_class->task_dead)
prev->sched_class->task_dead(prev);
/*
* Remove function-return probe instances associated with this
* task and put them back on the free list.
*/
kprobe_flush_task(prev);
put_task_struct(prev);
}
tick_nohz_task_switch();
return rq;
}
#ifdef CONFIG_SMP
/* rq->lock is NOT held, but preemption is disabled */
static void __balance_callback(struct rq *rq)
{
struct callback_head *head, *next;
void (*func)(struct rq *rq);
unsigned long flags;
raw_spin_lock_irqsave(&rq->lock, flags);
head = rq->balance_callback;
rq->balance_callback = NULL;
while (head) {
func = (void (*)(struct rq *))head->func;
next = head->next;
head->next = NULL;
head = next;
func(rq);
}
raw_spin_unlock_irqrestore(&rq->lock, flags);
}
static inline void balance_callback(struct rq *rq)
{
if (unlikely(rq->balance_callback))
__balance_callback(rq);
}
#else
static inline void balance_callback(struct rq *rq)
{
}
#endif
/**
* schedule_tail - first thing a freshly forked thread must call.
* @prev: the thread we just switched away from.
*/
asmlinkage __visible void schedule_tail(struct task_struct *prev)
__releases(rq->lock)
{
struct rq *rq;
/*
* New tasks start with FORK_PREEMPT_COUNT, see there and
* finish_task_switch() for details.
*
* finish_task_switch() will drop rq->lock() and lower preempt_count
* and the preempt_enable() will end up enabling preemption (on
* PREEMPT_COUNT kernels).
*/
rq = finish_task_switch(prev);
balance_callback(rq);
preempt_enable();
if (current->set_child_tid)
put_user(task_pid_vnr(current), current->set_child_tid);
}
/*
* context_switch - switch to the new MM and the new thread's register state.
*/
static __always_inline struct rq *
context_switch(struct rq *rq, struct task_struct *prev,
struct task_struct *next, struct pin_cookie cookie)
{
struct mm_struct *mm, *oldmm;
prepare_task_switch(rq, prev, next);
mm = next->mm;
oldmm = prev->active_mm;
/*
* For paravirt, this is coupled with an exit in switch_to to
* combine the page table reload and the switch backend into
* one hypercall.
*/
arch_start_context_switch(prev);
if (!mm) {
next->active_mm = oldmm;
atomic_inc(&oldmm->mm_count);
enter_lazy_tlb(oldmm, next);
} else
switch_mm_irqs_off(oldmm, mm, next);
if (!prev->mm) {
prev->active_mm = NULL;
rq->prev_mm = oldmm;
}
/*
* Since the runqueue lock will be released by the next
* task (which is an invalid locking op but in the case
* of the scheduler it's an obvious special-case), so we
* do an early lockdep release here:
*/
lockdep_unpin_lock(&rq->lock, cookie);
spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
/* Here we just switch the register state and the stack. */
switch_to(prev, next, prev);
barrier();
return finish_task_switch(prev);
}
/*
* nr_running and nr_context_switches:
*
* externally visible scheduler statistics: current number of runnable
* threads, total number of context switches performed since bootup.
*/
unsigned long nr_running(void)
{
unsigned long i, sum = 0;
for_each_online_cpu(i)
sum += cpu_rq(i)->nr_running;
return sum;
}
/*
* Check if only the current task is running on the cpu.
*
* Caution: this function does not check that the caller has disabled
* preemption, thus the result might have a time-of-check-to-time-of-use
* race. The caller is responsible to use it correctly, for example:
*
* - from a non-preemptable section (of course)
*
* - from a thread that is bound to a single CPU
*
* - in a loop with very short iterations (e.g. a polling loop)
*/
bool single_task_running(void)
{
return raw_rq()->nr_running == 1;
}
EXPORT_SYMBOL(single_task_running);
unsigned long long nr_context_switches(void)
{
int i;
unsigned long long sum = 0;
for_each_possible_cpu(i)
sum += cpu_rq(i)->nr_switches;
return sum;
}
unsigned long nr_iowait(void)
{
unsigned long i, sum = 0;
for_each_possible_cpu(i)
sum += atomic_read(&cpu_rq(i)->nr_iowait);
return sum;
}
unsigned long nr_iowait_cpu(int cpu)
{
struct rq *this = cpu_rq(cpu);
return atomic_read(&this->nr_iowait);
}
void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
{
struct rq *rq = this_rq();
*nr_waiters = atomic_read(&rq->nr_iowait);
*load = rq->load.weight;
}
#ifdef CONFIG_SMP
/*
* sched_exec - execve() is a valuable balancing opportunity, because at
* this point the task has the smallest effective memory and cache footprint.
*/
void sched_exec(void)
{
struct task_struct *p = current;
unsigned long flags;
int dest_cpu;
raw_spin_lock_irqsave(&p->pi_lock, flags);
dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
if (dest_cpu == smp_processor_id())
goto unlock;
if (likely(cpu_active(dest_cpu))) {
struct migration_arg arg = { p, dest_cpu };
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
return;
}
unlock:
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
}
#endif
DEFINE_PER_CPU(struct kernel_stat, kstat);
DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
EXPORT_PER_CPU_SYMBOL(kstat);
EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
/*
* Return accounted runtime for the task.
* In case the task is currently running, return the runtime plus current's
* pending runtime that have not been accounted yet.
*/
unsigned long long task_sched_runtime(struct task_struct *p)
{
struct rq_flags rf;
struct rq *rq;
u64 ns;
#if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
/*
* 64-bit doesn't need locks to atomically read a 64bit value.
* So we have a optimization chance when the task's delta_exec is 0.
* Reading ->on_cpu is racy, but this is ok.
*
* If we race with it leaving cpu, we'll take a lock. So we're correct.
* If we race with it entering cpu, unaccounted time is 0. This is
* indistinguishable from the read occurring a few cycles earlier.
* If we see ->on_cpu without ->on_rq, the task is leaving, and has
* been accounted, so we're correct here as well.
*/
if (!p->on_cpu || !task_on_rq_queued(p))
return p->se.sum_exec_runtime;
#endif
rq = task_rq_lock(p, &rf);
/*
* Must be ->curr _and_ ->on_rq. If dequeued, we would
* project cycles that may never be accounted to this
* thread, breaking clock_gettime().
*/
if (task_current(rq, p) && task_on_rq_queued(p)) {
update_rq_clock(rq);
p->sched_class->update_curr(rq);
}
ns = p->se.sum_exec_runtime;
task_rq_unlock(rq, p, &rf);
return ns;
}
/*
* This function gets called by the timer code, with HZ frequency.
* We call it with interrupts disabled.
*/
void scheduler_tick(void)
{
int cpu = smp_processor_id();
struct rq *rq = cpu_rq(cpu);
struct task_struct *curr = rq->curr;
sched_clock_tick();
raw_spin_lock(&rq->lock);
update_rq_clock(rq);
curr->sched_class->task_tick(rq, curr, 0);
cpu_load_update_active(rq);
calc_global_load_tick(rq);
raw_spin_unlock(&rq->lock);
perf_event_task_tick();
#ifdef CONFIG_SMP
rq->idle_balance = idle_cpu(cpu);
trigger_load_balance(rq);
#endif
rq_last_tick_reset(rq);
}
#ifdef CONFIG_NO_HZ_FULL
/**
* scheduler_tick_max_deferment
*
* Keep at least one tick per second when a single
* active task is running because the scheduler doesn't
* yet completely support full dynticks environment.
*
* This makes sure that uptime, CFS vruntime, load
* balancing, etc... continue to move forward, even
* with a very low granularity.
*
* Return: Maximum deferment in nanoseconds.
*/
u64 scheduler_tick_max_deferment(void)
{
struct rq *rq = this_rq();
unsigned long next, now = READ_ONCE(jiffies);
next = rq->last_sched_tick + HZ;
if (time_before_eq(next, now))
return 0;
return jiffies_to_nsecs(next - now);
}
#endif
#if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
defined(CONFIG_PREEMPT_TRACER))
/*
* If the value passed in is equal to the current preempt count
* then we just disabled preemption. Start timing the latency.
*/
static inline void preempt_latency_start(int val)
{
if (preempt_count() == val) {
unsigned long ip = get_lock_parent_ip();
#ifdef CONFIG_DEBUG_PREEMPT
current->preempt_disable_ip = ip;
#endif
trace_preempt_off(CALLER_ADDR0, ip);
}
}
void preempt_count_add(int val)
{
#ifdef CONFIG_DEBUG_PREEMPT
/*
* Underflow?
*/
if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
return;
#endif
__preempt_count_add(val);
#ifdef CONFIG_DEBUG_PREEMPT
/*
* Spinlock count overflowing soon?
*/
DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
PREEMPT_MASK - 10);
#endif
preempt_latency_start(val);
}
EXPORT_SYMBOL(preempt_count_add);
NOKPROBE_SYMBOL(preempt_count_add);
/*
* If the value passed in equals to the current preempt count
* then we just enabled preemption. Stop timing the latency.
*/
static inline void preempt_latency_stop(int val)
{
if (preempt_count() == val)
trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
}
void preempt_count_sub(int val)
{
#ifdef CONFIG_DEBUG_PREEMPT
/*
* Underflow?
*/
if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
return;
/*
* Is the spinlock portion underflowing?
*/
if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
!(preempt_count() & PREEMPT_MASK)))
return;
#endif
preempt_latency_stop(val);
__preempt_count_sub(val);
}
EXPORT_SYMBOL(preempt_count_sub);
NOKPROBE_SYMBOL(preempt_count_sub);
#else
static inline void preempt_latency_start(int val) { }
static inline void preempt_latency_stop(int val) { }
#endif
/*
* Print scheduling while atomic bug:
*/
static noinline void __schedule_bug(struct task_struct *prev)
{
if (oops_in_progress)
return;
printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
prev->comm, prev->pid, preempt_count());
debug_show_held_locks(prev);
print_modules();
if (irqs_disabled())
print_irqtrace_events(prev);
#ifdef CONFIG_DEBUG_PREEMPT
if (in_atomic_preempt_off()) {
pr_err("Preemption disabled at:");
print_ip_sym(current->preempt_disable_ip);
pr_cont("\n");
}
#endif
dump_stack();
add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
}
/*
* Various schedule()-time debugging checks and statistics:
*/
static inline void schedule_debug(struct task_struct *prev)
{
#ifdef CONFIG_SCHED_STACK_END_CHECK
if (task_stack_end_corrupted(prev))
panic("corrupted stack end detected inside scheduler\n");
#endif
if (unlikely(in_atomic_preempt_off())) {
__schedule_bug(prev);
preempt_count_set(PREEMPT_DISABLED);
}
rcu_sleep_check();
profile_hit(SCHED_PROFILING, __builtin_return_address(0));
schedstat_inc(this_rq(), sched_count);
}
/*
* Pick up the highest-prio task:
*/
static inline struct task_struct *
pick_next_task(struct rq *rq, struct task_struct *prev, struct pin_cookie cookie)
{
const struct sched_class *class = &fair_sched_class;
struct task_struct *p;
/*
* Optimization: we know that if all tasks are in
* the fair class we can call that function directly:
*/
if (likely(prev->sched_class == class &&
rq->nr_running == rq->cfs.h_nr_running)) {
p = fair_sched_class.pick_next_task(rq, prev, cookie);
if (unlikely(p == RETRY_TASK))
goto again;
/* assumes fair_sched_class->next == idle_sched_class */
if (unlikely(!p))
p = idle_sched_class.pick_next_task(rq, prev, cookie);
return p;
}
again:
for_each_class(class) {
p = class->pick_next_task(rq, prev, cookie);
if (p) {
if (unlikely(p == RETRY_TASK))
goto again;
return p;
}
}
BUG(); /* the idle class will always have a runnable task */
}
/*
* __schedule() is the main scheduler function.
*
* The main means of driving the scheduler and thus entering this function are:
*
* 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
*
* 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
* paths. For example, see arch/x86/entry_64.S.
*
* To drive preemption between tasks, the scheduler sets the flag in timer
* interrupt handler scheduler_tick().
*
* 3. Wakeups don't really cause entry into schedule(). They add a
* task to the run-queue and that's it.
*
* Now, if the new task added to the run-queue preempts the current
* task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
* called on the nearest possible occasion:
*
* - If the kernel is preemptible (CONFIG_PREEMPT=y):
*
* - in syscall or exception context, at the next outmost
* preempt_enable(). (this might be as soon as the wake_up()'s
* spin_unlock()!)
*
* - in IRQ context, return from interrupt-handler to
* preemptible context
*
* - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
* then at the next:
*
* - cond_resched() call
* - explicit schedule() call
* - return from syscall or exception to user-space
* - return from interrupt-handler to user-space
*
* WARNING: must be called with preemption disabled!
*/
static void __sched notrace __schedule(bool preempt)
{
struct task_struct *prev, *next;
unsigned long *switch_count;
struct pin_cookie cookie;
struct rq *rq;
int cpu;
cpu = smp_processor_id();
rq = cpu_rq(cpu);
prev = rq->curr;
/*
* do_exit() calls schedule() with preemption disabled as an exception;
* however we must fix that up, otherwise the next task will see an
* inconsistent (higher) preempt count.
*
* It also avoids the below schedule_debug() test from complaining
* about this.
*/
if (unlikely(prev->state == TASK_DEAD))
preempt_enable_no_resched_notrace();
schedule_debug(prev);
if (sched_feat(HRTICK))
hrtick_clear(rq);
local_irq_disable();
rcu_note_context_switch();
/*
* Make sure that signal_pending_state()->signal_pending() below
* can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
* done by the caller to avoid the race with signal_wake_up().
*/
smp_mb__before_spinlock();
raw_spin_lock(&rq->lock);
cookie = lockdep_pin_lock(&rq->lock);
rq->clock_skip_update <<= 1; /* promote REQ to ACT */
switch_count = &prev->nivcsw;
if (!preempt && prev->state) {
if (unlikely(signal_pending_state(prev->state, prev))) {
prev->state = TASK_RUNNING;
} else {
deactivate_task(rq, prev, DEQUEUE_SLEEP);
prev->on_rq = 0;
/*
* If a worker went to sleep, notify and ask workqueue
* whether it wants to wake up a task to maintain
* concurrency.
*/
if (prev->flags & PF_WQ_WORKER) {
struct task_struct *to_wakeup;
to_wakeup = wq_worker_sleeping(prev);
if (to_wakeup)
try_to_wake_up_local(to_wakeup, cookie);
}
}
switch_count = &prev->nvcsw;
}
if (task_on_rq_queued(prev))
update_rq_clock(rq);
next = pick_next_task(rq, prev, cookie);
clear_tsk_need_resched(prev);
clear_preempt_need_resched();
rq->clock_skip_update = 0;
if (likely(prev != next)) {
rq->nr_switches++;
rq->curr = next;
++*switch_count;
trace_sched_switch(preempt, prev, next);
rq = context_switch(rq, prev, next, cookie); /* unlocks the rq */
} else {
lockdep_unpin_lock(&rq->lock, cookie);
raw_spin_unlock_irq(&rq->lock);
}
balance_callback(rq);
}
STACK_FRAME_NON_STANDARD(__schedule); /* switch_to() */
static inline void sched_submit_work(struct task_struct *tsk)
{
if (!tsk->state || tsk_is_pi_blocked(tsk))
return;
/*
* If we are going to sleep and we have plugged IO queued,
* make sure to submit it to avoid deadlocks.
*/
if (blk_needs_flush_plug(tsk))
blk_schedule_flush_plug(tsk);
}
asmlinkage __visible void __sched schedule(void)
{
struct task_struct *tsk = current;
sched_submit_work(tsk);
do {
preempt_disable();
__schedule(false);
sched_preempt_enable_no_resched();
} while (need_resched());
}
EXPORT_SYMBOL(schedule);
#ifdef CONFIG_CONTEXT_TRACKING
asmlinkage __visible void __sched schedule_user(void)
{
/*
* If we come here after a random call to set_need_resched(),
* or we have been woken up remotely but the IPI has not yet arrived,
* we haven't yet exited the RCU idle mode. Do it here manually until
* we find a better solution.
*
* NB: There are buggy callers of this function. Ideally we
* should warn if prev_state != CONTEXT_USER, but that will trigger
* too frequently to make sense yet.
*/
enum ctx_state prev_state = exception_enter();
schedule();
exception_exit(prev_state);
}
#endif
/**
* schedule_preempt_disabled - called with preemption disabled
*
* Returns with preemption disabled. Note: preempt_count must be 1
*/
void __sched schedule_preempt_disabled(void)
{
sched_preempt_enable_no_resched();
schedule();
preempt_disable();
}
static void __sched notrace preempt_schedule_common(void)
{
do {
/*
* Because the function tracer can trace preempt_count_sub()
* and it also uses preempt_enable/disable_notrace(), if
* NEED_RESCHED is set, the preempt_enable_notrace() called
* by the function tracer will call this function again and
* cause infinite recursion.
*
* Preemption must be disabled here before the function
* tracer can trace. Break up preempt_disable() into two
* calls. One to disable preemption without fear of being
* traced. The other to still record the preemption latency,
* which can also be traced by the function tracer.
*/
preempt_disable_notrace();
preempt_latency_start(1);
__schedule(true);
preempt_latency_stop(1);
preempt_enable_no_resched_notrace();
/*
* Check again in case we missed a preemption opportunity
* between schedule and now.
*/
} while (need_resched());
}
#ifdef CONFIG_PREEMPT
/*
* this is the entry point to schedule() from in-kernel preemption
* off of preempt_enable. Kernel preemptions off return from interrupt
* occur there and call schedule directly.
*/
asmlinkage __visible void __sched notrace preempt_schedule(void)
{
/*
* If there is a non-zero preempt_count or interrupts are disabled,
* we do not want to preempt the current task. Just return..
*/
if (likely(!preemptible()))
return;
preempt_schedule_common();
}
NOKPROBE_SYMBOL(preempt_schedule);
EXPORT_SYMBOL(preempt_schedule);
/**
* preempt_schedule_notrace - preempt_schedule called by tracing
*
* The tracing infrastructure uses preempt_enable_notrace to prevent
* recursion and tracing preempt enabling caused by the tracing
* infrastructure itself. But as tracing can happen in areas coming
* from userspace or just about to enter userspace, a preempt enable
* can occur before user_exit() is called. This will cause the scheduler
* to be called when the system is still in usermode.
*
* To prevent this, the preempt_enable_notrace will use this function
* instead of preempt_schedule() to exit user context if needed before
* calling the scheduler.
*/
asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
{
enum ctx_state prev_ctx;
if (likely(!preemptible()))
return;
do {
/*
* Because the function tracer can trace preempt_count_sub()
* and it also uses preempt_enable/disable_notrace(), if
* NEED_RESCHED is set, the preempt_enable_notrace() called
* by the function tracer will call this function again and
* cause infinite recursion.
*
* Preemption must be disabled here before the function
* tracer can trace. Break up preempt_disable() into two
* calls. One to disable preemption without fear of being
* traced. The other to still record the preemption latency,
* which can also be traced by the function tracer.
*/
preempt_disable_notrace();
preempt_latency_start(1);
/*
* Needs preempt disabled in case user_exit() is traced
* and the tracer calls preempt_enable_notrace() causing
* an infinite recursion.
*/
prev_ctx = exception_enter();
__schedule(true);
exception_exit(prev_ctx);
preempt_latency_stop(1);
preempt_enable_no_resched_notrace();
} while (need_resched());
}
EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
#endif /* CONFIG_PREEMPT */
/*
* this is the entry point to schedule() from kernel preemption
* off of irq context.
* Note, that this is called and return with irqs disabled. This will
* protect us against recursive calling from irq.
*/
asmlinkage __visible void __sched preempt_schedule_irq(void)
{
enum ctx_state prev_state;
/* Catch callers which need to be fixed */
BUG_ON(preempt_count() || !irqs_disabled());
prev_state = exception_enter();
do {
preempt_disable();
local_irq_enable();
__schedule(true);
local_irq_disable();
sched_preempt_enable_no_resched();
} while (need_resched());
exception_exit(prev_state);
}
int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
void *key)
{
return try_to_wake_up(curr->private, mode, wake_flags);
}
EXPORT_SYMBOL(default_wake_function);
#ifdef CONFIG_RT_MUTEXES
/*
* rt_mutex_setprio - set the current priority of a task
* @p: task
* @prio: prio value (kernel-internal form)
*
* This function changes the 'effective' priority of a task. It does
* not touch ->normal_prio like __setscheduler().
*
* Used by the rt_mutex code to implement priority inheritance
* logic. Call site only calls if the priority of the task changed.
*/
void rt_mutex_setprio(struct task_struct *p, int prio)
{
int oldprio, queued, running, queue_flag = DEQUEUE_SAVE | DEQUEUE_MOVE;
const struct sched_class *prev_class;
struct rq_flags rf;
struct rq *rq;
BUG_ON(prio > MAX_PRIO);
rq = __task_rq_lock(p, &rf);
/*
* Idle task boosting is a nono in general. There is one
* exception, when PREEMPT_RT and NOHZ is active:
*
* The idle task calls get_next_timer_interrupt() and holds
* the timer wheel base->lock on the CPU and another CPU wants
* to access the timer (probably to cancel it). We can safely
* ignore the boosting request, as the idle CPU runs this code
* with interrupts disabled and will complete the lock
* protected section without being interrupted. So there is no
* real need to boost.
*/
if (unlikely(p == rq->idle)) {
WARN_ON(p != rq->curr);
WARN_ON(p->pi_blocked_on);
goto out_unlock;
}
trace_sched_pi_setprio(p, prio);
oldprio = p->prio;
if (oldprio == prio)
queue_flag &= ~DEQUEUE_MOVE;
prev_class = p->sched_class;
queued = task_on_rq_queued(p);
running = task_current(rq, p);
if (queued)
dequeue_task(rq, p, queue_flag);
if (running)
put_prev_task(rq, p);
/*
* Boosting condition are:
* 1. -rt task is running and holds mutex A
* --> -dl task blocks on mutex A
*
* 2. -dl task is running and holds mutex A
* --> -dl task blocks on mutex A and could preempt the
* running task
*/
if (dl_prio(prio)) {
struct task_struct *pi_task = rt_mutex_get_top_task(p);
if (!dl_prio(p->normal_prio) ||
(pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
p->dl.dl_boosted = 1;
queue_flag |= ENQUEUE_REPLENISH;
} else
p->dl.dl_boosted = 0;
p->sched_class = &dl_sched_class;
} else if (rt_prio(prio)) {
if (dl_prio(oldprio))
p->dl.dl_boosted = 0;
if (oldprio < prio)
queue_flag |= ENQUEUE_HEAD;
p->sched_class = &rt_sched_class;
} else {
if (dl_prio(oldprio))
p->dl.dl_boosted = 0;
if (rt_prio(oldprio))
p->rt.timeout = 0;
p->sched_class = &fair_sched_class;
}
p->prio = prio;
if (running)
p->sched_class->set_curr_task(rq);
if (queued)
enqueue_task(rq, p, queue_flag);
check_class_changed(rq, p, prev_class, oldprio);
out_unlock:
preempt_disable(); /* avoid rq from going away on us */
__task_rq_unlock(rq, &rf);
balance_callback(rq);
preempt_enable();
}
#endif
void set_user_nice(struct task_struct *p, long nice)
{
int old_prio, delta, queued;
struct rq_flags rf;
struct rq *rq;
if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
return;
/*
* We have to be careful, if called from sys_setpriority(),
* the task might be in the middle of scheduling on another CPU.
*/
rq = task_rq_lock(p, &rf);
/*
* The RT priorities are set via sched_setscheduler(), but we still
* allow the 'normal' nice value to be set - but as expected
* it wont have any effect on scheduling until the task is
* SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
*/
if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
p->static_prio = NICE_TO_PRIO(nice);
goto out_unlock;
}
queued = task_on_rq_queued(p);
if (queued)
dequeue_task(rq, p, DEQUEUE_SAVE);
p->static_prio = NICE_TO_PRIO(nice);
set_load_weight(p);
old_prio = p->prio;
p->prio = effective_prio(p);
delta = p->prio - old_prio;
if (queued) {
enqueue_task(rq, p, ENQUEUE_RESTORE);
/*
* If the task increased its priority or is running and
* lowered its priority, then reschedule its CPU:
*/
if (delta < 0 || (delta > 0 && task_running(rq, p)))
resched_curr(rq);
}
out_unlock:
task_rq_unlock(rq, p, &rf);
}
EXPORT_SYMBOL(set_user_nice);
/*
* can_nice - check if a task can reduce its nice value
* @p: task
* @nice: nice value
*/
int can_nice(const struct task_struct *p, const int nice)
{
/* convert nice value [19,-20] to rlimit style value [1,40] */
int nice_rlim = nice_to_rlimit(nice);
return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
capable(CAP_SYS_NICE));
}
#ifdef __ARCH_WANT_SYS_NICE
/*
* sys_nice - change the priority of the current process.
* @increment: priority increment
*
* sys_setpriority is a more generic, but much slower function that
* does similar things.
*/
SYSCALL_DEFINE1(nice, int, increment)
{
long nice, retval;
/*
* Setpriority might change our priority at the same moment.
* We don't have to worry. Conceptually one call occurs first
* and we have a single winner.
*/
increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
nice = task_nice(current) + increment;
nice = clamp_val(nice, MIN_NICE, MAX_NICE);
if (increment < 0 && !can_nice(current, nice))
return -EPERM;
retval = security_task_setnice(current, nice);
if (retval)
return retval;
set_user_nice(current, nice);
return 0;
}
#endif
/**
* task_prio - return the priority value of a given task.
* @p: the task in question.
*
* Return: The priority value as seen by users in /proc.
* RT tasks are offset by -200. Normal tasks are centered
* around 0, value goes from -16 to +15.
*/
int task_prio(const struct task_struct *p)
{
return p->prio - MAX_RT_PRIO;
}
/**
* idle_cpu - is a given cpu idle currently?
* @cpu: the processor in question.
*
* Return: 1 if the CPU is currently idle. 0 otherwise.
*/
int idle_cpu(int cpu)
{
struct rq *rq = cpu_rq(cpu);
if (rq->curr != rq->idle)
return 0;
if (rq->nr_running)
return 0;
#ifdef CONFIG_SMP
if (!llist_empty(&rq->wake_list))
return 0;
#endif
return 1;
}
/**
* idle_task - return the idle task for a given cpu.
* @cpu: the processor in question.
*
* Return: The idle task for the cpu @cpu.
*/
struct task_struct *idle_task(int cpu)
{
return cpu_rq(cpu)->idle;
}
/**
* find_process_by_pid - find a process with a matching PID value.
* @pid: the pid in question.
*
* The task of @pid, if found. %NULL otherwise.
*/
static struct task_struct *find_process_by_pid(pid_t pid)
{
return pid ? find_task_by_vpid(pid) : current;
}
/*
* This function initializes the sched_dl_entity of a newly becoming
* SCHED_DEADLINE task.
*
* Only the static values are considered here, the actual runtime and the
* absolute deadline will be properly calculated when the task is enqueued
* for the first time with its new policy.
*/
static void
__setparam_dl(struct task_struct *p, const struct sched_attr *attr)
{
struct sched_dl_entity *dl_se = &p->dl;
dl_se->dl_runtime = attr->sched_runtime;
dl_se->dl_deadline = attr->sched_deadline;
dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
dl_se->flags = attr->sched_flags;
dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
/*
* Changing the parameters of a task is 'tricky' and we're not doing
* the correct thing -- also see task_dead_dl() and switched_from_dl().
*
* What we SHOULD do is delay the bandwidth release until the 0-lag
* point. This would include retaining the task_struct until that time
* and change dl_overflow() to not immediately decrement the current
* amount.
*
* Instead we retain the current runtime/deadline and let the new
* parameters take effect after the current reservation period lapses.
* This is safe (albeit pessimistic) because the 0-lag point is always
* before the current scheduling deadline.
*
* We can still have temporary overloads because we do not delay the
* change in bandwidth until that time; so admission control is
* not on the safe side. It does however guarantee tasks will never
* consume more than promised.
*/
}
/*
* sched_setparam() passes in -1 for its policy, to let the functions
* it calls know not to change it.
*/
#define SETPARAM_POLICY -1
static void __setscheduler_params(struct task_struct *p,
const struct sched_attr *attr)
{
int policy = attr->sched_policy;
if (policy == SETPARAM_POLICY)
policy = p->policy;
p->policy = policy;
if (dl_policy(policy))
__setparam_dl(p, attr);
else if (fair_policy(policy))
p->static_prio = NICE_TO_PRIO(attr->sched_nice);
/*
* __sched_setscheduler() ensures attr->sched_priority == 0 when
* !rt_policy. Always setting this ensures that things like
* getparam()/getattr() don't report silly values for !rt tasks.
*/
p->rt_priority = attr->sched_priority;
p->normal_prio = normal_prio(p);
set_load_weight(p);
}
/* Actually do priority change: must hold pi & rq lock. */
static void __setscheduler(struct rq *rq, struct task_struct *p,
const struct sched_attr *attr, bool keep_boost)
{
__setscheduler_params(p, attr);
/*
* Keep a potential priority boosting if called from
* sched_setscheduler().
*/
if (keep_boost)
p->prio = rt_mutex_get_effective_prio(p, normal_prio(p));
else
p->prio = normal_prio(p);
if (dl_prio(p->prio))
p->sched_class = &dl_sched_class;
else if (rt_prio(p->prio))
p->sched_class = &rt_sched_class;
else
p->sched_class = &fair_sched_class;
}
static void
__getparam_dl(struct task_struct *p, struct sched_attr *attr)
{
struct sched_dl_entity *dl_se = &p->dl;
attr->sched_priority = p->rt_priority;
attr->sched_runtime = dl_se->dl_runtime;
attr->sched_deadline = dl_se->dl_deadline;
attr->sched_period = dl_se->dl_period;
attr->sched_flags = dl_se->flags;
}
/*
* This function validates the new parameters of a -deadline task.
* We ask for the deadline not being zero, and greater or equal
* than the runtime, as well as the period of being zero or
* greater than deadline. Furthermore, we have to be sure that
* user parameters are above the internal resolution of 1us (we
* check sched_runtime only since it is always the smaller one) and
* below 2^63 ns (we have to check both sched_deadline and
* sched_period, as the latter can be zero).
*/
static bool
__checkparam_dl(const struct sched_attr *attr)
{
/* deadline != 0 */
if (attr->sched_deadline == 0)
return false;
/*
* Since we truncate DL_SCALE bits, make sure we're at least
* that big.
*/
if (attr->sched_runtime < (1ULL << DL_SCALE))
return false;
/*
* Since we use the MSB for wrap-around and sign issues, make
* sure it's not set (mind that period can be equal to zero).
*/
if (attr->sched_deadline & (1ULL << 63) ||
attr->sched_period & (1ULL << 63))
return false;
/* runtime <= deadline <= period (if period != 0) */
if ((attr->sched_period != 0 &&
attr->sched_period < attr->sched_deadline) ||
attr->sched_deadline < attr->sched_runtime)
return false;
return true;
}
/*
* check the target process has a UID that matches the current process's
*/
static bool check_same_owner(struct task_struct *p)
{
const struct cred *cred = current_cred(), *pcred;
bool match;
rcu_read_lock();
pcred = __task_cred(p);
match = (uid_eq(cred->euid, pcred->euid) ||
uid_eq(cred->euid, pcred->uid));
rcu_read_unlock();
return match;
}
static bool dl_param_changed(struct task_struct *p,
const struct sched_attr *attr)
{
struct sched_dl_entity *dl_se = &p->dl;
if (dl_se->dl_runtime != attr->sched_runtime ||
dl_se->dl_deadline != attr->sched_deadline ||
dl_se->dl_period != attr->sched_period ||
dl_se->flags != attr->sched_flags)
return true;
return false;
}
static int __sched_setscheduler(struct task_struct *p,
const struct sched_attr *attr,
bool user, bool pi)
{
int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
MAX_RT_PRIO - 1 - attr->sched_priority;
int retval, oldprio, oldpolicy = -1, queued, running;
int new_effective_prio, policy = attr->sched_policy;
const struct sched_class *prev_class;
struct rq_flags rf;
int reset_on_fork;
int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
struct rq *rq;
/* may grab non-irq protected spin_locks */
BUG_ON(in_interrupt());
recheck:
/* double check policy once rq lock held */
if (policy < 0) {
reset_on_fork = p->sched_reset_on_fork;
policy = oldpolicy = p->policy;
} else {
reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
if (!valid_policy(policy))
return -EINVAL;
}
if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK))
return -EINVAL;
/*
* Valid priorities for SCHED_FIFO and SCHED_RR are
* 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
* SCHED_BATCH and SCHED_IDLE is 0.
*/
if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
(!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
return -EINVAL;
if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
(rt_policy(policy) != (attr->sched_priority != 0)))
return -EINVAL;
/*
* Allow unprivileged RT tasks to decrease priority:
*/
if (user && !capable(CAP_SYS_NICE)) {
if (fair_policy(policy)) {
if (attr->sched_nice < task_nice(p) &&
!can_nice(p, attr->sched_nice))
return -EPERM;
}
if (rt_policy(policy)) {
unsigned long rlim_rtprio =
task_rlimit(p, RLIMIT_RTPRIO);
/* can't set/change the rt policy */
if (policy != p->policy && !rlim_rtprio)
return -EPERM;
/* can't increase priority */
if (attr->sched_priority > p->rt_priority &&
attr->sched_priority > rlim_rtprio)
return -EPERM;
}
/*
* Can't set/change SCHED_DEADLINE policy at all for now
* (safest behavior); in the future we would like to allow
* unprivileged DL tasks to increase their relative deadline
* or reduce their runtime (both ways reducing utilization)
*/
if (dl_policy(policy))
return -EPERM;
/*
* Treat SCHED_IDLE as nice 20. Only allow a switch to
* SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
*/
if (idle_policy(p->policy) && !idle_policy(policy)) {
if (!can_nice(p, task_nice(p)))
return -EPERM;
}
/* can't change other user's priorities */
if (!check_same_owner(p))
return -EPERM;
/* Normal users shall not reset the sched_reset_on_fork flag */
if (p->sched_reset_on_fork && !reset_on_fork)
return -EPERM;
}
if (user) {
retval = security_task_setscheduler(p);
if (retval)
return retval;
}
/*
* make sure no PI-waiters arrive (or leave) while we are
* changing the priority of the task:
*
* To be able to change p->policy safely, the appropriate
* runqueue lock must be held.
*/
rq = task_rq_lock(p, &rf);
/*
* Changing the policy of the stop threads its a very bad idea
*/
if (p == rq->stop) {
task_rq_unlock(rq, p, &rf);
return -EINVAL;
}
/*
* If not changing anything there's no need to proceed further,
* but store a possible modification of reset_on_fork.
*/
if (unlikely(policy == p->policy)) {
if (fair_policy(policy) && attr->sched_nice != task_nice(p))
goto change;
if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
goto change;
if (dl_policy(policy) && dl_param_changed(p, attr))
goto change;
p->sched_reset_on_fork = reset_on_fork;
task_rq_unlock(rq, p, &rf);
return 0;
}
change:
if (user) {
#ifdef CONFIG_RT_GROUP_SCHED
/*
* Do not allow realtime tasks into groups that have no runtime
* assigned.
*/
if (rt_bandwidth_enabled() && rt_policy(policy) &&
task_group(p)->rt_bandwidth.rt_runtime == 0 &&
!task_group_is_autogroup(task_group(p))) {
task_rq_unlock(rq, p, &rf);
return -EPERM;
}
#endif
#ifdef CONFIG_SMP
if (dl_bandwidth_enabled() && dl_policy(policy)) {
cpumask_t *span = rq->rd->span;
/*
* Don't allow tasks with an affinity mask smaller than
* the entire root_domain to become SCHED_DEADLINE. We
* will also fail if there's no bandwidth available.
*/
if (!cpumask_subset(span, &p->cpus_allowed) ||
rq->rd->dl_bw.bw == 0) {
task_rq_unlock(rq, p, &rf);
return -EPERM;
}
}
#endif
}
/* recheck policy now with rq lock held */
if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
policy = oldpolicy = -1;
task_rq_unlock(rq, p, &rf);
goto recheck;
}
/*
* If setscheduling to SCHED_DEADLINE (or changing the parameters
* of a SCHED_DEADLINE task) we need to check if enough bandwidth
* is available.
*/
if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) {
task_rq_unlock(rq, p, &rf);
return -EBUSY;
}
p->sched_reset_on_fork = reset_on_fork;
oldprio = p->prio;
if (pi) {
/*
* Take priority boosted tasks into account. If the new
* effective priority is unchanged, we just store the new
* normal parameters and do not touch the scheduler class and
* the runqueue. This will be done when the task deboost
* itself.
*/
new_effective_prio = rt_mutex_get_effective_prio(p, newprio);
if (new_effective_prio == oldprio)
queue_flags &= ~DEQUEUE_MOVE;
}
queued = task_on_rq_queued(p);
running = task_current(rq, p);
if (queued)
dequeue_task(rq, p, queue_flags);
if (running)
put_prev_task(rq, p);
prev_class = p->sched_class;
__setscheduler(rq, p, attr, pi);
if (running)
p->sched_class->set_curr_task(rq);
if (queued) {
/*
* We enqueue to tail when the priority of a task is
* increased (user space view).
*/
if (oldprio < p->prio)
queue_flags |= ENQUEUE_HEAD;
enqueue_task(rq, p, queue_flags);
}
check_class_changed(rq, p, prev_class, oldprio);
preempt_disable(); /* avoid rq from going away on us */
task_rq_unlock(rq, p, &rf);
if (pi)
rt_mutex_adjust_pi(p);
/*
* Run balance callbacks after we've adjusted the PI chain.
*/
balance_callback(rq);
preempt_enable();
return 0;
}
static int _sched_setscheduler(struct task_struct *p, int policy,
const struct sched_param *param, bool check)
{
struct sched_attr attr = {
.sched_policy = policy,
.sched_priority = param->sched_priority,
.sched_nice = PRIO_TO_NICE(p->static_prio),
};
/* Fixup the legacy SCHED_RESET_ON_FORK hack. */
if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
policy &= ~SCHED_RESET_ON_FORK;
attr.sched_policy = policy;
}
return __sched_setscheduler(p, &attr, check, true);
}
/**
* sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
* @p: the task in question.
* @policy: new policy.
* @param: structure containing the new RT priority.
*
* Return: 0 on success. An error code otherwise.
*
* NOTE that the task may be already dead.
*/
int sched_setscheduler(struct task_struct *p, int policy,
const struct sched_param *param)
{
return _sched_setscheduler(p, policy, param, true);
}
EXPORT_SYMBOL_GPL(sched_setscheduler);
int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
{
return __sched_setscheduler(p, attr, true, true);
}
EXPORT_SYMBOL_GPL(sched_setattr);
/**
* sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
* @p: the task in question.
* @policy: new policy.
* @param: structure containing the new RT priority.
*
* Just like sched_setscheduler, only don't bother checking if the
* current context has permission. For example, this is needed in
* stop_machine(): we create temporary high priority worker threads,
* but our caller might not have that capability.
*
* Return: 0 on success. An error code otherwise.
*/
int sched_setscheduler_nocheck(struct task_struct *p, int policy,
const struct sched_param *param)
{
return _sched_setscheduler(p, policy, param, false);
}
EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
static int
do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
{
struct sched_param lparam;
struct task_struct *p;
int retval;
if (!param || pid < 0)
return -EINVAL;
if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
return -EFAULT;
rcu_read_lock();
retval = -ESRCH;
p = find_process_by_pid(pid);
if (p != NULL)
retval = sched_setscheduler(p, policy, &lparam);
rcu_read_unlock();
return retval;
}
/*
* Mimics kernel/events/core.c perf_copy_attr().
*/
static int sched_copy_attr(struct sched_attr __user *uattr,
struct sched_attr *attr)
{
u32 size;
int ret;
if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
return -EFAULT;
/*
* zero the full structure, so that a short copy will be nice.
*/
memset(attr, 0, sizeof(*attr));
ret = get_user(size, &uattr->size);
if (ret)
return ret;
if (size > PAGE_SIZE) /* silly large */
goto err_size;
if (!size) /* abi compat */
size = SCHED_ATTR_SIZE_VER0;
if (size < SCHED_ATTR_SIZE_VER0)
goto err_size;
/*
* If we're handed a bigger struct than we know of,
* ensure all the unknown bits are 0 - i.e. new
* user-space does not rely on any kernel feature
* extensions we dont know about yet.
*/
if (size > sizeof(*attr)) {
unsigned char __user *addr;
unsigned char __user *end;
unsigned char val;
addr = (void __user *)uattr + sizeof(*attr);
end = (void __user *)uattr + size;
for (; addr < end; addr++) {
ret = get_user(val, addr);
if (ret)
return ret;
if (val)
goto err_size;
}
size = sizeof(*attr);
}
ret = copy_from_user(attr, uattr, size);
if (ret)
return -EFAULT;
/*
* XXX: do we want to be lenient like existing syscalls; or do we want
* to be strict and return an error on out-of-bounds values?
*/
attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
return 0;
err_size:
put_user(sizeof(*attr), &uattr->size);
return -E2BIG;
}
/**
* sys_sched_setscheduler - set/change the scheduler policy and RT priority
* @pid: the pid in question.
* @policy: new policy.
* @param: structure containing the new RT priority.
*
* Return: 0 on success. An error code otherwise.
*/
SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
struct sched_param __user *, param)
{
/* negative values for policy are not valid */
if (policy < 0)
return -EINVAL;
return do_sched_setscheduler(pid, policy, param);
}
/**
* sys_sched_setparam - set/change the RT priority of a thread
* @pid: the pid in question.
* @param: structure containing the new RT priority.
*
* Return: 0 on success. An error code otherwise.
*/
SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
{
return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
}
/**
* sys_sched_setattr - same as above, but with extended sched_attr
* @pid: the pid in question.
* @uattr: structure containing the extended parameters.
* @flags: for future extension.
*/
SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
unsigned int, flags)
{
struct sched_attr attr;
struct task_struct *p;
int retval;
if (!uattr || pid < 0 || flags)
return -EINVAL;
retval = sched_copy_attr(uattr, &attr);
if (retval)
return retval;
if ((int)attr.sched_policy < 0)
return -EINVAL;
rcu_read_lock();
retval = -ESRCH;
p = find_process_by_pid(pid);
if (p != NULL)
retval = sched_setattr(p, &attr);
rcu_read_unlock();
return retval;
}
/**
* sys_sched_getscheduler - get the policy (scheduling class) of a thread
* @pid: the pid in question.
*
* Return: On success, the policy of the thread. Otherwise, a negative error
* code.
*/
SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
{
struct task_struct *p;
int retval;
if (pid < 0)
return -EINVAL;
retval = -ESRCH;
rcu_read_lock();
p = find_process_by_pid(pid);
if (p) {
retval = security_task_getscheduler(p);
if (!retval)
retval = p->policy
| (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
}
rcu_read_unlock();
return retval;
}
/**
* sys_sched_getparam - get the RT priority of a thread
* @pid: the pid in question.
* @param: structure containing the RT priority.
*
* Return: On success, 0 and the RT priority is in @param. Otherwise, an error
* code.
*/
SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
{
struct sched_param lp = { .sched_priority = 0 };
struct task_struct *p;
int retval;
if (!param || pid < 0)
return -EINVAL;
rcu_read_lock();
p = find_process_by_pid(pid);
retval = -ESRCH;
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
if (task_has_rt_policy(p))
lp.sched_priority = p->rt_priority;
rcu_read_unlock();
/*
* This one might sleep, we cannot do it with a spinlock held ...
*/
retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
return retval;
out_unlock:
rcu_read_unlock();
return retval;
}
static int sched_read_attr(struct sched_attr __user *uattr,
struct sched_attr *attr,
unsigned int usize)
{
int ret;
if (!access_ok(VERIFY_WRITE, uattr, usize))
return -EFAULT;
/*
* If we're handed a smaller struct than we know of,
* ensure all the unknown bits are 0 - i.e. old
* user-space does not get uncomplete information.
*/
if (usize < sizeof(*attr)) {
unsigned char *addr;
unsigned char *end;
addr = (void *)attr + usize;
end = (void *)attr + sizeof(*attr);
for (; addr < end; addr++) {
if (*addr)
return -EFBIG;
}
attr->size = usize;
}
ret = copy_to_user(uattr, attr, attr->size);
if (ret)
return -EFAULT;
return 0;
}
/**
* sys_sched_getattr - similar to sched_getparam, but with sched_attr
* @pid: the pid in question.
* @uattr: structure containing the extended parameters.
* @size: sizeof(attr) for fwd/bwd comp.
* @flags: for future extension.
*/
SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
unsigned int, size, unsigned int, flags)
{
struct sched_attr attr = {
.size = sizeof(struct sched_attr),
};
struct task_struct *p;
int retval;
if (!uattr || pid < 0 || size > PAGE_SIZE ||
size < SCHED_ATTR_SIZE_VER0 || flags)
return -EINVAL;
rcu_read_lock();
p = find_process_by_pid(pid);
retval = -ESRCH;
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
attr.sched_policy = p->policy;
if (p->sched_reset_on_fork)
attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
if (task_has_dl_policy(p))
__getparam_dl(p, &attr);
else if (task_has_rt_policy(p))
attr.sched_priority = p->rt_priority;
else
attr.sched_nice = task_nice(p);
rcu_read_unlock();
retval = sched_read_attr(uattr, &attr, size);
return retval;
out_unlock:
rcu_read_unlock();
return retval;
}
long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
{
cpumask_var_t cpus_allowed, new_mask;
struct task_struct *p;
int retval;
rcu_read_lock();
p = find_process_by_pid(pid);
if (!p) {
rcu_read_unlock();
return -ESRCH;
}
/* Prevent p going away */
get_task_struct(p);
rcu_read_unlock();
if (p->flags & PF_NO_SETAFFINITY) {
retval = -EINVAL;
goto out_put_task;
}
if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
retval = -ENOMEM;
goto out_put_task;
}
if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
retval = -ENOMEM;
goto out_free_cpus_allowed;
}
retval = -EPERM;
if (!check_same_owner(p)) {
rcu_read_lock();
if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
rcu_read_unlock();
goto out_free_new_mask;
}
rcu_read_unlock();
}
retval = security_task_setscheduler(p);
if (retval)
goto out_free_new_mask;
cpuset_cpus_allowed(p, cpus_allowed);
cpumask_and(new_mask, in_mask, cpus_allowed);
/*
* Since bandwidth control happens on root_domain basis,
* if admission test is enabled, we only admit -deadline
* tasks allowed to run on all the CPUs in the task's
* root_domain.
*/
#ifdef CONFIG_SMP
if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
rcu_read_lock();
if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
retval = -EBUSY;
rcu_read_unlock();
goto out_free_new_mask;
}
rcu_read_unlock();
}
#endif
again:
retval = __set_cpus_allowed_ptr(p, new_mask, true);
if (!retval) {
cpuset_cpus_allowed(p, cpus_allowed);
if (!cpumask_subset(new_mask, cpus_allowed)) {
/*
* We must have raced with a concurrent cpuset
* update. Just reset the cpus_allowed to the
* cpuset's cpus_allowed
*/
cpumask_copy(new_mask, cpus_allowed);
goto again;
}
}
out_free_new_mask:
free_cpumask_var(new_mask);
out_free_cpus_allowed:
free_cpumask_var(cpus_allowed);
out_put_task:
put_task_struct(p);
return retval;
}
static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
struct cpumask *new_mask)
{
if (len < cpumask_size())
cpumask_clear(new_mask);
else if (len > cpumask_size())
len = cpumask_size();
return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
}
/**
* sys_sched_setaffinity - set the cpu affinity of a process
* @pid: pid of the process
* @len: length in bytes of the bitmask pointed to by user_mask_ptr
* @user_mask_ptr: user-space pointer to the new cpu mask
*
* Return: 0 on success. An error code otherwise.
*/
SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
unsigned long __user *, user_mask_ptr)
{
cpumask_var_t new_mask;
int retval;
if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
return -ENOMEM;
retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
if (retval == 0)
retval = sched_setaffinity(pid, new_mask);
free_cpumask_var(new_mask);
return retval;
}
long sched_getaffinity(pid_t pid, struct cpumask *mask)
{
struct task_struct *p;
unsigned long flags;
int retval;
rcu_read_lock();
retval = -ESRCH;
p = find_process_by_pid(pid);
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
raw_spin_lock_irqsave(&p->pi_lock, flags);
cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
raw_spin_unlock_irqrestore(&p->pi_lock, flags);
out_unlock:
rcu_read_unlock();
return retval;
}
/**
* sys_sched_getaffinity - get the cpu affinity of a process
* @pid: pid of the process
* @len: length in bytes of the bitmask pointed to by user_mask_ptr
* @user_mask_ptr: user-space pointer to hold the current cpu mask
*
* Return: 0 on success. An error code otherwise.
*/
SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
unsigned long __user *, user_mask_ptr)
{
int ret;
cpumask_var_t mask;
if ((len * BITS_PER_BYTE) < nr_cpu_ids)
return -EINVAL;
if (len & (sizeof(unsigned long)-1))
return -EINVAL;
if (!alloc_cpumask_var(&mask, GFP_KERNEL))
return -ENOMEM;
ret = sched_getaffinity(pid, mask);
if (ret == 0) {
size_t retlen = min_t(size_t, len, cpumask_size());
if (copy_to_user(user_mask_ptr, mask, retlen))
ret = -EFAULT;
else
ret = retlen;
}
free_cpumask_var(mask);
return ret;
}
/**
* sys_sched_yield - yield the current processor to other threads.
*
* This function yields the current CPU to other tasks. If there are no
* other threads running on this CPU then this function will return.
*
* Return: 0.
*/
SYSCALL_DEFINE0(sched_yield)
{
struct rq *rq = this_rq_lock();
schedstat_inc(rq, yld_count);
current->sched_class->yield_task(rq);
/*
* Since we are going to call schedule() anyway, there's
* no need to preempt or enable interrupts:
*/
__release(rq->lock);
spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
do_raw_spin_unlock(&rq->lock);
sched_preempt_enable_no_resched();
schedule();
return 0;
}
int __sched _cond_resched(void)
{
if (should_resched(0)) {
preempt_schedule_common();
return 1;
}
return 0;
}
EXPORT_SYMBOL(_cond_resched);
/*
* __cond_resched_lock() - if a reschedule is pending, drop the given lock,
* call schedule, and on return reacquire the lock.
*
* This works OK both with and without CONFIG_PREEMPT. We do strange low-level
* operations here to prevent schedule() from being called twice (once via
* spin_unlock(), once by hand).
*/
int __cond_resched_lock(spinlock_t *lock)
{
int resched = should_resched(PREEMPT_LOCK_OFFSET);
int ret = 0;
lockdep_assert_held(lock);
if (spin_needbreak(lock) || resched) {
spin_unlock(lock);
if (resched)
preempt_schedule_common();
else
cpu_relax();
ret = 1;
spin_lock(lock);
}
return ret;
}
EXPORT_SYMBOL(__cond_resched_lock);
int __sched __cond_resched_softirq(void)
{
BUG_ON(!in_softirq());
if (should_resched(SOFTIRQ_DISABLE_OFFSET)) {
local_bh_enable();
preempt_schedule_common();
local_bh_disable();
return 1;
}
return 0;
}
EXPORT_SYMBOL(__cond_resched_softirq);
/**
* yield - yield the current processor to other threads.
*
* Do not ever use this function, there's a 99% chance you're doing it wrong.
*
* The scheduler is at all times free to pick the calling task as the most
* eligible task to run, if removing the yield() call from your code breaks
* it, its already broken.
*
* Typical broken usage is:
*
* while (!event)
* yield();
*
* where one assumes that yield() will let 'the other' process run that will
* make event true. If the current task is a SCHED_FIFO task that will never
* happen. Never use yield() as a progress guarantee!!
*
* If you want to use yield() to wait for something, use wait_event().
* If you want to use yield() to be 'nice' for others, use cond_resched().
* If you still want to use yield(), do not!
*/
void __sched yield(void)
{
set_current_state(TASK_RUNNING);
sys_sched_yield();
}
EXPORT_SYMBOL(yield);
/**
* yield_to - yield the current processor to another thread in
* your thread group, or accelerate that thread toward the
* processor it's on.
* @p: target task
* @preempt: whether task preemption is allowed or not
*
* It's the caller's job to ensure that the target task struct
* can't go away on us before we can do any checks.
*
* Return:
* true (>0) if we indeed boosted the target task.
* false (0) if we failed to boost the target.
* -ESRCH if there's no task to yield to.
*/
int __sched yield_to(struct task_struct *p, bool preempt)
{
struct task_struct *curr = current;
struct rq *rq, *p_rq;
unsigned long flags;
int yielded = 0;
local_irq_save(flags);
rq = this_rq();
again:
p_rq = task_rq(p);
/*
* If we're the only runnable task on the rq and target rq also
* has only one task, there's absolutely no point in yielding.
*/
if (rq->nr_running == 1 && p_rq->nr_running == 1) {
yielded = -ESRCH;
goto out_irq;
}
double_rq_lock(rq, p_rq);
if (task_rq(p) != p_rq) {
double_rq_unlock(rq, p_rq);
goto again;
}
if (!curr->sched_class->yield_to_task)
goto out_unlock;
if (curr->sched_class != p->sched_class)
goto out_unlock;
if (task_running(p_rq, p) || p->state)
goto out_unlock;
yielded = curr->sched_class->yield_to_task(rq, p, preempt);
if (yielded) {
schedstat_inc(rq, yld_count);
/*
* Make p's CPU reschedule; pick_next_entity takes care of
* fairness.
*/
if (preempt && rq != p_rq)
resched_curr(p_rq);
}
out_unlock:
double_rq_unlock(rq, p_rq);
out_irq:
local_irq_restore(flags);
if (yielded > 0)
schedule();
return yielded;
}
EXPORT_SYMBOL_GPL(yield_to);
/*
* This task is about to go to sleep on IO. Increment rq->nr_iowait so
* that process accounting knows that this is a task in IO wait state.
*/
long __sched io_schedule_timeout(long timeout)
{
int old_iowait = current->in_iowait;
struct rq *rq;
long ret;
current->in_iowait = 1;
blk_schedule_flush_plug(current);
delayacct_blkio_start();
rq = raw_rq();
atomic_inc(&rq->nr_iowait);
ret = schedule_timeout(timeout);
current->in_iowait = old_iowait;
atomic_dec(&rq->nr_iowait);
delayacct_blkio_end();
return ret;
}
EXPORT_SYMBOL(io_schedule_timeout);
/**
* sys_sched_get_priority_max - return maximum RT priority.
* @policy: scheduling class.
*
* Return: On success, this syscall returns the maximum
* rt_priority that can be used by a given scheduling class.
* On failure, a negative error code is returned.
*/
SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
{
int ret = -EINVAL;
switch (policy) {
case SCHED_FIFO:
case SCHED_RR:
ret = MAX_USER_RT_PRIO-1;
break;
case SCHED_DEADLINE:
case SCHED_NORMAL:
case SCHED_BATCH:
case SCHED_IDLE:
ret = 0;
break;
}
return ret;
}
/**
* sys_sched_get_priority_min - return minimum RT priority.
* @policy: scheduling class.
*
* Return: On success, this syscall returns the minimum
* rt_priority that can be used by a given scheduling class.
* On failure, a negative error code is returned.
*/
SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
{
int ret = -EINVAL;
switch (policy) {
case SCHED_FIFO:
case SCHED_RR:
ret = 1;
break;
case SCHED_DEADLINE:
case SCHED_NORMAL:
case SCHED_BATCH:
case SCHED_IDLE:
ret = 0;
}
return ret;
}
/**
* sys_sched_rr_get_interval - return the default timeslice of a process.
* @pid: pid of the process.
* @interval: userspace pointer to the timeslice value.
*
* this syscall writes the default timeslice value of a given process
* into the user-space timespec buffer. A value of '0' means infinity.
*
* Return: On success, 0 and the timeslice is in @interval. Otherwise,
* an error code.
*/
SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
struct timespec __user *, interval)
{
struct task_struct *p;
unsigned int time_slice;
struct rq_flags rf;
struct timespec t;
struct rq *rq;
int retval;
if (pid < 0)
return -EINVAL;
retval = -ESRCH;
rcu_read_lock();
p = find_process_by_pid(pid);
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
rq = task_rq_lock(p, &rf);
time_slice = 0;
if (p->sched_class->get_rr_interval)
time_slice = p->sched_class->get_rr_interval(rq, p);
task_rq_unlock(rq, p, &rf);
rcu_read_unlock();
jiffies_to_timespec(time_slice, &t);
retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
return retval;
out_unlock:
rcu_read_unlock();
return retval;
}
static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
void sched_show_task(struct task_struct *p)
{
unsigned long free = 0;
int ppid;
unsigned long state = p->state;
if (state)
state = __ffs(state) + 1;
printk(KERN_INFO "%-15.15s %c", p->comm,
state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
#if BITS_PER_LONG == 32
if (state == TASK_RUNNING)
printk(KERN_CONT " running ");
else
printk(KERN_CONT " %08lx ", thread_saved_pc(p));
#else
if (state == TASK_RUNNING)
printk(KERN_CONT " running task ");
else
printk(KERN_CONT " %016lx ", thread_saved_pc(p));
#endif
#ifdef CONFIG_DEBUG_STACK_USAGE
free = stack_not_used(p);
#endif
ppid = 0;
rcu_read_lock();
if (pid_alive(p))
ppid = task_pid_nr(rcu_dereference(p->real_parent));
rcu_read_unlock();
printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
task_pid_nr(p), ppid,
(unsigned long)task_thread_info(p)->flags);
print_worker_info(KERN_INFO, p);
show_stack(p, NULL);
}
void show_state_filter(unsigned long state_filter)
{
struct task_struct *g, *p;
#if BITS_PER_LONG == 32
printk(KERN_INFO
" task PC stack pid father\n");
#else
printk(KERN_INFO
" task PC stack pid father\n");
#endif
rcu_read_lock();
for_each_process_thread(g, p) {
/*
* reset the NMI-timeout, listing all files on a slow
* console might take a lot of time:
*/
touch_nmi_watchdog();
if (!state_filter || (p->state & state_filter))
sched_show_task(p);
}
touch_all_softlockup_watchdogs();
#ifdef CONFIG_SCHED_DEBUG
if (!state_filter)
sysrq_sched_debug_show();
#endif
rcu_read_unlock();
/*
* Only show locks if all tasks are dumped:
*/
if (!state_filter)
debug_show_all_locks();
}
void init_idle_bootup_task(struct task_struct *idle)
{
idle->sched_class = &idle_sched_class;
}
/**
* init_idle - set up an idle thread for a given CPU
* @idle: task in question
* @cpu: cpu the idle task belongs to
*
* NOTE: this function does not set the idle thread's NEED_RESCHED
* flag, to make booting more robust.
*/
void init_idle(struct task_struct *idle, int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long flags;
raw_spin_lock_irqsave(&idle->pi_lock, flags);
raw_spin_lock(&rq->lock);
__sched_fork(0, idle);
idle->state = TASK_RUNNING;
idle->se.exec_start = sched_clock();
kasan_unpoison_task_stack(idle);
#ifdef CONFIG_SMP
/*
* Its possible that init_idle() gets called multiple times on a task,
* in that case do_set_cpus_allowed() will not do the right thing.
*
* And since this is boot we can forgo the serialization.
*/
set_cpus_allowed_common(idle, cpumask_of(cpu));
#endif
/*
* We're having a chicken and egg problem, even though we are
* holding rq->lock, the cpu isn't yet set to this cpu so the
* lockdep check in task_group() will fail.
*
* Similar case to sched_fork(). / Alternatively we could
* use task_rq_lock() here and obtain the other rq->lock.
*
* Silence PROVE_RCU
*/
rcu_read_lock();
__set_task_cpu(idle, cpu);
rcu_read_unlock();
rq->curr = rq->idle = idle;
idle->on_rq = TASK_ON_RQ_QUEUED;
#ifdef CONFIG_SMP
idle->on_cpu = 1;
#endif
raw_spin_unlock(&rq->lock);
raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
/* Set the preempt count _outside_ the spinlocks! */
init_idle_preempt_count(idle, cpu);
/*
* The idle tasks have their own, simple scheduling class:
*/
idle->sched_class = &idle_sched_class;
ftrace_graph_init_idle_task(idle, cpu);
vtime_init_idle(idle, cpu);
#ifdef CONFIG_SMP
sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
#endif
}
int cpuset_cpumask_can_shrink(const struct cpumask *cur,
const struct cpumask *trial)
{
int ret = 1, trial_cpus;
struct dl_bw *cur_dl_b;
unsigned long flags;
if (!cpumask_weight(cur))
return ret;
rcu_read_lock_sched();
cur_dl_b = dl_bw_of(cpumask_any(cur));
trial_cpus = cpumask_weight(trial);
raw_spin_lock_irqsave(&cur_dl_b->lock, flags);
if (cur_dl_b->bw != -1 &&
cur_dl_b->bw * trial_cpus < cur_dl_b->total_bw)
ret = 0;
raw_spin_unlock_irqrestore(&cur_dl_b->lock, flags);
rcu_read_unlock_sched();
return ret;
}
int task_can_attach(struct task_struct *p,
const struct cpumask *cs_cpus_allowed)
{
int ret = 0;
/*
* Kthreads which disallow setaffinity shouldn't be moved
* to a new cpuset; we don't want to change their cpu
* affinity and isolating such threads by their set of
* allowed nodes is unnecessary. Thus, cpusets are not
* applicable for such threads. This prevents checking for
* success of set_cpus_allowed_ptr() on all attached tasks
* before cpus_allowed may be changed.
*/
if (p->flags & PF_NO_SETAFFINITY) {
ret = -EINVAL;
goto out;
}
#ifdef CONFIG_SMP
if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
cs_cpus_allowed)) {
unsigned int dest_cpu = cpumask_any_and(cpu_active_mask,
cs_cpus_allowed);
struct dl_bw *dl_b;
bool overflow;
int cpus;
unsigned long flags;
rcu_read_lock_sched();
dl_b = dl_bw_of(dest_cpu);
raw_spin_lock_irqsave(&dl_b->lock, flags);
cpus = dl_bw_cpus(dest_cpu);
overflow = __dl_overflow(dl_b, cpus, 0, p->dl.dl_bw);
if (overflow)
ret = -EBUSY;
else {
/*
* We reserve space for this task in the destination
* root_domain, as we can't fail after this point.
* We will free resources in the source root_domain
* later on (see set_cpus_allowed_dl()).
*/
__dl_add(dl_b, p->dl.dl_bw);
}
raw_spin_unlock_irqrestore(&dl_b->lock, flags);
rcu_read_unlock_sched();
}
#endif
out:
return ret;
}
#ifdef CONFIG_SMP
static bool sched_smp_initialized __read_mostly;
#ifdef CONFIG_NUMA_BALANCING
/* Migrate current task p to target_cpu */
int migrate_task_to(struct task_struct *p, int target_cpu)
{
struct migration_arg arg = { p, target_cpu };
int curr_cpu = task_cpu(p);
if (curr_cpu == target_cpu)
return 0;
if (!cpumask_test_cpu(target_cpu, tsk_cpus_allowed(p)))
return -EINVAL;
/* TODO: This is not properly updating schedstats */
trace_sched_move_numa(p, curr_cpu, target_cpu);
return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
}
/*
* Requeue a task on a given node and accurately track the number of NUMA
* tasks on the runqueues
*/
void sched_setnuma(struct task_struct *p, int nid)
{
bool queued, running;
struct rq_flags rf;
struct rq *rq;
rq = task_rq_lock(p, &rf);
queued = task_on_rq_queued(p);
running = task_current(rq, p);
if (queued)
dequeue_task(rq, p, DEQUEUE_SAVE);
if (running)
put_prev_task(rq, p);
p->numa_preferred_nid = nid;
if (running)
p->sched_class->set_curr_task(rq);
if (queued)
enqueue_task(rq, p, ENQUEUE_RESTORE);
task_rq_unlock(rq, p, &rf);
}
#endif /* CONFIG_NUMA_BALANCING */
#ifdef CONFIG_HOTPLUG_CPU
/*
* Ensures that the idle task is using init_mm right before its cpu goes
* offline.
*/
void idle_task_exit(void)
{
struct mm_struct *mm = current->active_mm;
BUG_ON(cpu_online(smp_processor_id()));
if (mm != &init_mm) {
switch_mm_irqs_off(mm, &init_mm, current);
finish_arch_post_lock_switch();
}
mmdrop(mm);
}
/*
* Since this CPU is going 'away' for a while, fold any nr_active delta
* we might have. Assumes we're called after migrate_tasks() so that the
* nr_active count is stable.
*
* Also see the comment "Global load-average calculations".
*/
static void calc_load_migrate(struct rq *rq)
{
long delta = calc_load_fold_active(rq);
if (delta)
atomic_long_add(delta, &calc_load_tasks);
}
static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
{
}
static const struct sched_class fake_sched_class = {
.put_prev_task = put_prev_task_fake,
};
static struct task_struct fake_task = {
/*
* Avoid pull_{rt,dl}_task()
*/
.prio = MAX_PRIO + 1,
.sched_class = &fake_sched_class,
};
/*
* Migrate all tasks from the rq, sleeping tasks will be migrated by
* try_to_wake_up()->select_task_rq().
*
* Called with rq->lock held even though we'er in stop_machine() and
* there's no concurrency possible, we hold the required locks anyway
* because of lock validation efforts.
*/
static void migrate_tasks(struct rq *dead_rq)
{
struct rq *rq = dead_rq;
struct task_struct *next, *stop = rq->stop;
struct pin_cookie cookie;
int dest_cpu;
/*
* Fudge the rq selection such that the below task selection loop
* doesn't get stuck on the currently eligible stop task.
*
* We're currently inside stop_machine() and the rq is either stuck
* in the stop_machine_cpu_stop() loop, or we're executing this code,
* either way we should never end up calling schedule() until we're
* done here.
*/
rq->stop = NULL;
/*
* put_prev_task() and pick_next_task() sched
* class method both need to have an up-to-date
* value of rq->clock[_task]
*/
update_rq_clock(rq);
for (;;) {
/*
* There's this thread running, bail when that's the only
* remaining thread.
*/
if (rq->nr_running == 1)
break;
/*
* pick_next_task assumes pinned rq->lock.
*/
cookie = lockdep_pin_lock(&rq->lock);
next = pick_next_task(rq, &fake_task, cookie);
BUG_ON(!next);
next->sched_class->put_prev_task(rq, next);
/*
* Rules for changing task_struct::cpus_allowed are holding
* both pi_lock and rq->lock, such that holding either
* stabilizes the mask.
*
* Drop rq->lock is not quite as disastrous as it usually is
* because !cpu_active at this point, which means load-balance
* will not interfere. Also, stop-machine.
*/
lockdep_unpin_lock(&rq->lock, cookie);
raw_spin_unlock(&rq->lock);
raw_spin_lock(&next->pi_lock);
raw_spin_lock(&rq->lock);
/*
* Since we're inside stop-machine, _nothing_ should have
* changed the task, WARN if weird stuff happened, because in
* that case the above rq->lock drop is a fail too.
*/
if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
raw_spin_unlock(&next->pi_lock);
continue;
}
/* Find suitable destination for @next, with force if needed. */
dest_cpu = select_fallback_rq(dead_rq->cpu, next);
rq = __migrate_task(rq, next, dest_cpu);
if (rq != dead_rq) {
raw_spin_unlock(&rq->lock);
rq = dead_rq;
raw_spin_lock(&rq->lock);
}
raw_spin_unlock(&next->pi_lock);
}
rq->stop = stop;
}
#endif /* CONFIG_HOTPLUG_CPU */
static void set_rq_online(struct rq *rq)
{
if (!rq->online) {
const struct sched_class *class;
cpumask_set_cpu(rq->cpu, rq->rd->online);
rq->online = 1;
for_each_class(class) {
if (class->rq_online)
class->rq_online(rq);
}
}
}
static void set_rq_offline(struct rq *rq)
{
if (rq->online) {
const struct sched_class *class;
for_each_class(class) {
if (class->rq_offline)
class->rq_offline(rq);
}
cpumask_clear_cpu(rq->cpu, rq->rd->online);
rq->online = 0;
}
}
static void set_cpu_rq_start_time(unsigned int cpu)
{
struct rq *rq = cpu_rq(cpu);
rq->age_stamp = sched_clock_cpu(cpu);
}
static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
#ifdef CONFIG_SCHED_DEBUG
static __read_mostly int sched_debug_enabled;
static int __init sched_debug_setup(char *str)
{
sched_debug_enabled = 1;
return 0;
}
early_param("sched_debug", sched_debug_setup);
static inline bool sched_debug(void)
{
return sched_debug_enabled;
}
static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
struct cpumask *groupmask)
{
struct sched_group *group = sd->groups;
cpumask_clear(groupmask);
printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
if (!(sd->flags & SD_LOAD_BALANCE)) {
printk("does not load-balance\n");
if (sd->parent)
printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
" has parent");
return -1;
}
printk(KERN_CONT "span %*pbl level %s\n",
cpumask_pr_args(sched_domain_span(sd)), sd->name);
if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
printk(KERN_ERR "ERROR: domain->span does not contain "
"CPU%d\n", cpu);
}
if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
printk(KERN_ERR "ERROR: domain->groups does not contain"
" CPU%d\n", cpu);
}
printk(KERN_DEBUG "%*s groups:", level + 1, "");
do {
if (!group) {
printk("\n");
printk(KERN_ERR "ERROR: group is NULL\n");
break;
}
if (!cpumask_weight(sched_group_cpus(group))) {
printk(KERN_CONT "\n");
printk(KERN_ERR "ERROR: empty group\n");
break;
}
if (!(sd->flags & SD_OVERLAP) &&
cpumask_intersects(groupmask, sched_group_cpus(group))) {
printk(KERN_CONT "\n");
printk(KERN_ERR "ERROR: repeated CPUs\n");
break;
}
cpumask_or(groupmask, groupmask, sched_group_cpus(group));
printk(KERN_CONT " %*pbl",
cpumask_pr_args(sched_group_cpus(group)));
if (group->sgc->capacity != SCHED_CAPACITY_SCALE) {
printk(KERN_CONT " (cpu_capacity = %d)",
group->sgc->capacity);
}
group = group->next;
} while (group != sd->groups);
printk(KERN_CONT "\n");
if (!cpumask_equal(sched_domain_span(sd), groupmask))
printk(KERN_ERR "ERROR: groups don't span domain->span\n");
if (sd->parent &&
!cpumask_subset(groupmask, sched_domain_span(sd->parent)))
printk(KERN_ERR "ERROR: parent span is not a superset "
"of domain->span\n");
return 0;
}
static void sched_domain_debug(struct sched_domain *sd, int cpu)
{
int level = 0;
if (!sched_debug_enabled)
return;
if (!sd) {
printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
return;
}
printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
for (;;) {
if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
break;
level++;
sd = sd->parent;
if (!sd)
break;
}
}
#else /* !CONFIG_SCHED_DEBUG */
# define sched_domain_debug(sd, cpu) do { } while (0)
static inline bool sched_debug(void)
{
return false;
}
#endif /* CONFIG_SCHED_DEBUG */
static int sd_degenerate(struct sched_domain *sd)
{
if (cpumask_weight(sched_domain_span(sd)) == 1)
return 1;
/* Following flags need at least 2 groups */
if (sd->flags & (SD_LOAD_BALANCE |
SD_BALANCE_NEWIDLE |
SD_BALANCE_FORK |
SD_BALANCE_EXEC |
SD_SHARE_CPUCAPACITY |
SD_SHARE_PKG_RESOURCES |
SD_SHARE_POWERDOMAIN)) {
if (sd->groups != sd->groups->next)
return 0;
}
/* Following flags don't use groups */
if (sd->flags & (SD_WAKE_AFFINE))
return 0;
return 1;
}
static int
sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
{
unsigned long cflags = sd->flags, pflags = parent->flags;
if (sd_degenerate(parent))
return 1;
if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
return 0;
/* Flags needing groups don't count if only 1 group in parent */
if (parent->groups == parent->groups->next) {
pflags &= ~(SD_LOAD_BALANCE |
SD_BALANCE_NEWIDLE |
SD_BALANCE_FORK |
SD_BALANCE_EXEC |
SD_SHARE_CPUCAPACITY |
SD_SHARE_PKG_RESOURCES |
SD_PREFER_SIBLING |
SD_SHARE_POWERDOMAIN);
if (nr_node_ids == 1)
pflags &= ~SD_SERIALIZE;
}
if (~cflags & pflags)
return 0;
return 1;
}
static void free_rootdomain(struct rcu_head *rcu)
{
struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
cpupri_cleanup(&rd->cpupri);
cpudl_cleanup(&rd->cpudl);
free_cpumask_var(rd->dlo_mask);
free_cpumask_var(rd->rto_mask);
free_cpumask_var(rd->online);
free_cpumask_var(rd->span);
kfree(rd);
}
static void rq_attach_root(struct rq *rq, struct root_domain *rd)
{
struct root_domain *old_rd = NULL;
unsigned long flags;
raw_spin_lock_irqsave(&rq->lock, flags);
if (rq->rd) {
old_rd = rq->rd;
if (cpumask_test_cpu(rq->cpu, old_rd->online))
set_rq_offline(rq);
cpumask_clear_cpu(rq->cpu, old_rd->span);
/*
* If we dont want to free the old_rd yet then
* set old_rd to NULL to skip the freeing later
* in this function:
*/
if (!atomic_dec_and_test(&old_rd->refcount))
old_rd = NULL;
}
atomic_inc(&rd->refcount);
rq->rd = rd;
cpumask_set_cpu(rq->cpu, rd->span);
if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
set_rq_online(rq);
raw_spin_unlock_irqrestore(&rq->lock, flags);
if (old_rd)
call_rcu_sched(&old_rd->rcu, free_rootdomain);
}
static int init_rootdomain(struct root_domain *rd)
{
memset(rd, 0, sizeof(*rd));
if (!zalloc_cpumask_var(&rd->span, GFP_KERNEL))
goto out;
if (!zalloc_cpumask_var(&rd->online, GFP_KERNEL))
goto free_span;
if (!zalloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL))
goto free_online;
if (!zalloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
goto free_dlo_mask;
init_dl_bw(&rd->dl_bw);
if (cpudl_init(&rd->cpudl) != 0)
goto free_dlo_mask;
if (cpupri_init(&rd->cpupri) != 0)
goto free_rto_mask;
return 0;
free_rto_mask:
free_cpumask_var(rd->rto_mask);
free_dlo_mask:
free_cpumask_var(rd->dlo_mask);
free_online:
free_cpumask_var(rd->online);
free_span:
free_cpumask_var(rd->span);
out:
return -ENOMEM;
}
/*
* By default the system creates a single root-domain with all cpus as
* members (mimicking the global state we have today).
*/
struct root_domain def_root_domain;
static void init_defrootdomain(void)
{
init_rootdomain(&def_root_domain);
atomic_set(&def_root_domain.refcount, 1);
}
static struct root_domain *alloc_rootdomain(void)
{
struct root_domain *rd;
rd = kmalloc(sizeof(*rd), GFP_KERNEL);
if (!rd)
return NULL;
if (init_rootdomain(rd) != 0) {
kfree(rd);
return NULL;
}
return rd;
}
static void free_sched_groups(struct sched_group *sg, int free_sgc)
{
struct sched_group *tmp, *first;
if (!sg)
return;
first = sg;
do {
tmp = sg->next;
if (free_sgc && atomic_dec_and_test(&sg->sgc->ref))
kfree(sg->sgc);
kfree(sg);
sg = tmp;
} while (sg != first);
}
static void free_sched_domain(struct rcu_head *rcu)
{
struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
/*
* If its an overlapping domain it has private groups, iterate and
* nuke them all.
*/
if (sd->flags & SD_OVERLAP) {
free_sched_groups(sd->groups, 1);
} else if (atomic_dec_and_test(&sd->groups->ref)) {
kfree(sd->groups->sgc);
kfree(sd->groups);
}
kfree(sd);
}
static void destroy_sched_domain(struct sched_domain *sd, int cpu)
{
call_rcu(&sd->rcu, free_sched_domain);
}
static void destroy_sched_domains(struct sched_domain *sd, int cpu)
{
for (; sd; sd = sd->parent)
destroy_sched_domain(sd, cpu);
}
/*
* Keep a special pointer to the highest sched_domain that has
* SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
* allows us to avoid some pointer chasing select_idle_sibling().
*
* Also keep a unique ID per domain (we use the first cpu number in
* the cpumask of the domain), this allows us to quickly tell if
* two cpus are in the same cache domain, see cpus_share_cache().
*/
DEFINE_PER_CPU(struct sched_domain *, sd_llc);
DEFINE_PER_CPU(int, sd_llc_size);
DEFINE_PER_CPU(int, sd_llc_id);
DEFINE_PER_CPU(struct sched_domain *, sd_numa);
DEFINE_PER_CPU(struct sched_domain *, sd_busy);
DEFINE_PER_CPU(struct sched_domain *, sd_asym);
static void update_top_cache_domain(int cpu)
{
struct sched_domain *sd;
struct sched_domain *busy_sd = NULL;
int id = cpu;
int size = 1;
sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
if (sd) {
id = cpumask_first(sched_domain_span(sd));
size = cpumask_weight(sched_domain_span(sd));
busy_sd = sd->parent; /* sd_busy */
}
rcu_assign_pointer(per_cpu(sd_busy, cpu), busy_sd);
rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
per_cpu(sd_llc_size, cpu) = size;
per_cpu(sd_llc_id, cpu) = id;
sd = lowest_flag_domain(cpu, SD_NUMA);
rcu_assign_pointer(per_cpu(sd_numa, cpu), sd);
sd = highest_flag_domain(cpu, SD_ASYM_PACKING);
rcu_assign_pointer(per_cpu(sd_asym, cpu), sd);
}
/*
* Attach the domain 'sd' to 'cpu' as its base domain. Callers must
* hold the hotplug lock.
*/
static void
cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
{
struct rq *rq = cpu_rq(cpu);
struct sched_domain *tmp;
/* Remove the sched domains which do not contribute to scheduling. */
for (tmp = sd; tmp; ) {
struct sched_domain *parent = tmp->parent;
if (!parent)
break;
if (sd_parent_degenerate(tmp, parent)) {
tmp->parent = parent->parent;
if (parent->parent)
parent->parent->child = tmp;
/*
* Transfer SD_PREFER_SIBLING down in case of a
* degenerate parent; the spans match for this
* so the property transfers.
*/
if (parent->flags & SD_PREFER_SIBLING)
tmp->flags |= SD_PREFER_SIBLING;
destroy_sched_domain(parent, cpu);
} else
tmp = tmp->parent;
}
if (sd && sd_degenerate(sd)) {
tmp = sd;
sd = sd->parent;
destroy_sched_domain(tmp, cpu);
if (sd)
sd->child = NULL;
}
sched_domain_debug(sd, cpu);
rq_attach_root(rq, rd);
tmp = rq->sd;
rcu_assign_pointer(rq->sd, sd);
destroy_sched_domains(tmp, cpu);
update_top_cache_domain(cpu);
}
/* Setup the mask of cpus configured for isolated domains */
static int __init isolated_cpu_setup(char *str)
{
int ret;
alloc_bootmem_cpumask_var(&cpu_isolated_map);
ret = cpulist_parse(str, cpu_isolated_map);
if (ret) {
pr_err("sched: Error, all isolcpus= values must be between 0 and %d\n", nr_cpu_ids);
return 0;
}
return 1;
}
__setup("isolcpus=", isolated_cpu_setup);
struct s_data {
struct sched_domain ** __percpu sd;
struct root_domain *rd;
};
enum s_alloc {
sa_rootdomain,
sa_sd,
sa_sd_storage,
sa_none,
};
/*
* Build an iteration mask that can exclude certain CPUs from the upwards
* domain traversal.
*
* Asymmetric node setups can result in situations where the domain tree is of
* unequal depth, make sure to skip domains that already cover the entire
* range.
*
* In that case build_sched_domains() will have terminated the iteration early
* and our sibling sd spans will be empty. Domains should always include the
* cpu they're built on, so check that.
*
*/
static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
{
const struct cpumask *span = sched_domain_span(sd);
struct sd_data *sdd = sd->private;
struct sched_domain *sibling;
int i;
for_each_cpu(i, span) {
sibling = *per_cpu_ptr(sdd->sd, i);
if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
continue;
cpumask_set_cpu(i, sched_group_mask(sg));
}
}
/*
* Return the canonical balance cpu for this group, this is the first cpu
* of this group that's also in the iteration mask.
*/
int group_balance_cpu(struct sched_group *sg)
{
return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
}
static int
build_overlap_sched_groups(struct sched_domain *sd, int cpu)
{
struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
const struct cpumask *span = sched_domain_span(sd);
struct cpumask *covered = sched_domains_tmpmask;
struct sd_data *sdd = sd->private;
struct sched_domain *sibling;
int i;
cpumask_clear(covered);
for_each_cpu(i, span) {
struct cpumask *sg_span;
if (cpumask_test_cpu(i, covered))
continue;
sibling = *per_cpu_ptr(sdd->sd, i);
/* See the comment near build_group_mask(). */
if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
continue;
sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
GFP_KERNEL, cpu_to_node(cpu));
if (!sg)
goto fail;
sg_span = sched_group_cpus(sg);
if (sibling->child)
cpumask_copy(sg_span, sched_domain_span(sibling->child));
else
cpumask_set_cpu(i, sg_span);
cpumask_or(covered, covered, sg_span);
sg->sgc = *per_cpu_ptr(sdd->sgc, i);
if (atomic_inc_return(&sg->sgc->ref) == 1)
build_group_mask(sd, sg);
/*
* Initialize sgc->capacity such that even if we mess up the
* domains and no possible iteration will get us here, we won't
* die on a /0 trap.
*/
sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sg_span);
/*
* Make sure the first group of this domain contains the
* canonical balance cpu. Otherwise the sched_domain iteration
* breaks. See update_sg_lb_stats().
*/
if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
group_balance_cpu(sg) == cpu)
groups = sg;
if (!first)
first = sg;
if (last)
last->next = sg;
last = sg;
last->next = first;
}
sd->groups = groups;
return 0;
fail:
free_sched_groups(first, 0);
return -ENOMEM;
}
static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
{
struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
struct sched_domain *child = sd->child;
if (child)
cpu = cpumask_first(sched_domain_span(child));
if (sg) {
*sg = *per_cpu_ptr(sdd->sg, cpu);
(*sg)->sgc = *per_cpu_ptr(sdd->sgc, cpu);
atomic_set(&(*sg)->sgc->ref, 1); /* for claim_allocations */
}
return cpu;
}
/*
* build_sched_groups will build a circular linked list of the groups
* covered by the given span, and will set each group's ->cpumask correctly,
* and ->cpu_capacity to 0.
*
* Assumes the sched_domain tree is fully constructed
*/
static int
build_sched_groups(struct sched_domain *sd, int cpu)
{
struct sched_group *first = NULL, *last = NULL;
struct sd_data *sdd = sd->private;
const struct cpumask *span = sched_domain_span(sd);
struct cpumask *covered;
int i;
get_group(cpu, sdd, &sd->groups);
atomic_inc(&sd->groups->ref);
if (cpu != cpumask_first(span))
return 0;
lockdep_assert_held(&sched_domains_mutex);
covered = sched_domains_tmpmask;
cpumask_clear(covered);
for_each_cpu(i, span) {
struct sched_group *sg;
int group, j;
if (cpumask_test_cpu(i, covered))
continue;
group = get_group(i, sdd, &sg);
cpumask_setall(sched_group_mask(sg));
for_each_cpu(j, span) {
if (get_group(j, sdd, NULL) != group)
continue;
cpumask_set_cpu(j, covered);
cpumask_set_cpu(j, sched_group_cpus(sg));
}
if (!first)
first = sg;
if (last)
last->next = sg;
last = sg;
}
last->next = first;
return 0;
}
/*
* Initialize sched groups cpu_capacity.
*
* cpu_capacity indicates the capacity of sched group, which is used while
* distributing the load between different sched groups in a sched domain.
* Typically cpu_capacity for all the groups in a sched domain will be same
* unless there are asymmetries in the topology. If there are asymmetries,
* group having more cpu_capacity will pickup more load compared to the
* group having less cpu_capacity.
*/
static void init_sched_groups_capacity(int cpu, struct sched_domain *sd)
{
struct sched_group *sg = sd->groups;
WARN_ON(!sg);
do {
sg->group_weight = cpumask_weight(sched_group_cpus(sg));
sg = sg->next;
} while (sg != sd->groups);
if (cpu != group_balance_cpu(sg))
return;
update_group_capacity(sd, cpu);
atomic_set(&sg->sgc->nr_busy_cpus, sg->group_weight);
}
/*
* Initializers for schedule domains
* Non-inlined to reduce accumulated stack pressure in build_sched_domains()
*/
static int default_relax_domain_level = -1;
int sched_domain_level_max;
static int __init setup_relax_domain_level(char *str)
{
if (kstrtoint(str, 0, &default_relax_domain_level))
pr_warn("Unable to set relax_domain_level\n");
return 1;
}
__setup("relax_domain_level=", setup_relax_domain_level);
static void set_domain_attribute(struct sched_domain *sd,
struct sched_domain_attr *attr)
{
int request;
if (!attr || attr->relax_domain_level < 0) {
if (default_relax_domain_level < 0)
return;
else
request = default_relax_domain_level;
} else
request = attr->relax_domain_level;
if (request < sd->level) {
/* turn off idle balance on this domain */
sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
} else {
/* turn on idle balance on this domain */
sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
}
}
static void __sdt_free(const struct cpumask *cpu_map);
static int __sdt_alloc(const struct cpumask *cpu_map);
static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
const struct cpumask *cpu_map)
{
switch (what) {
case sa_rootdomain:
if (!atomic_read(&d->rd->refcount))
free_rootdomain(&d->rd->rcu); /* fall through */
case sa_sd:
free_percpu(d->sd); /* fall through */
case sa_sd_storage:
__sdt_free(cpu_map); /* fall through */
case sa_none:
break;
}
}
static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
const struct cpumask *cpu_map)
{
memset(d, 0, sizeof(*d));
if (__sdt_alloc(cpu_map))
return sa_sd_storage;
d->sd = alloc_percpu(struct sched_domain *);
if (!d->sd)
return sa_sd_storage;
d->rd = alloc_rootdomain();
if (!d->rd)
return sa_sd;
return sa_rootdomain;
}
/*
* NULL the sd_data elements we've used to build the sched_domain and
* sched_group structure so that the subsequent __free_domain_allocs()
* will not free the data we're using.
*/
static void claim_allocations(int cpu, struct sched_domain *sd)
{
struct sd_data *sdd = sd->private;
WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
*per_cpu_ptr(sdd->sd, cpu) = NULL;
if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
*per_cpu_ptr(sdd->sg, cpu) = NULL;
if (atomic_read(&(*per_cpu_ptr(sdd->sgc, cpu))->ref))
*per_cpu_ptr(sdd->sgc, cpu) = NULL;
}
#ifdef CONFIG_NUMA
static int sched_domains_numa_levels;
enum numa_topology_type sched_numa_topology_type;
static int *sched_domains_numa_distance;
int sched_max_numa_distance;
static struct cpumask ***sched_domains_numa_masks;
static int sched_domains_curr_level;
#endif
/*
* SD_flags allowed in topology descriptions.
*
* SD_SHARE_CPUCAPACITY - describes SMT topologies
* SD_SHARE_PKG_RESOURCES - describes shared caches
* SD_NUMA - describes NUMA topologies
* SD_SHARE_POWERDOMAIN - describes shared power domain
*
* Odd one out:
* SD_ASYM_PACKING - describes SMT quirks
*/
#define TOPOLOGY_SD_FLAGS \
(SD_SHARE_CPUCAPACITY | \
SD_SHARE_PKG_RESOURCES | \
SD_NUMA | \
SD_ASYM_PACKING | \
SD_SHARE_POWERDOMAIN)
static struct sched_domain *
sd_init(struct sched_domain_topology_level *tl, int cpu)
{
struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu);
int sd_weight, sd_flags = 0;
#ifdef CONFIG_NUMA
/*
* Ugly hack to pass state to sd_numa_mask()...
*/
sched_domains_curr_level = tl->numa_level;
#endif
sd_weight = cpumask_weight(tl->mask(cpu));
if (tl->sd_flags)
sd_flags = (*tl->sd_flags)();
if (WARN_ONCE(sd_flags & ~TOPOLOGY_SD_FLAGS,
"wrong sd_flags in topology description\n"))
sd_flags &= ~TOPOLOGY_SD_FLAGS;
*sd = (struct sched_domain){
.min_interval = sd_weight,
.max_interval = 2*sd_weight,
.busy_factor = 32,
.imbalance_pct = 125,
.cache_nice_tries = 0,
.busy_idx = 0,
.idle_idx = 0,
.newidle_idx = 0,
.wake_idx = 0,
.forkexec_idx = 0,
.flags = 1*SD_LOAD_BALANCE
| 1*SD_BALANCE_NEWIDLE
| 1*SD_BALANCE_EXEC
| 1*SD_BALANCE_FORK
| 0*SD_BALANCE_WAKE
| 1*SD_WAKE_AFFINE
| 0*SD_SHARE_CPUCAPACITY
| 0*SD_SHARE_PKG_RESOURCES
| 0*SD_SERIALIZE
| 0*SD_PREFER_SIBLING
| 0*SD_NUMA
| sd_flags
,
.last_balance = jiffies,
.balance_interval = sd_weight,
.smt_gain = 0,
.max_newidle_lb_cost = 0,
.next_decay_max_lb_cost = jiffies,
#ifdef CONFIG_SCHED_DEBUG
.name = tl->name,
#endif
};
/*
* Convert topological properties into behaviour.
*/
if (sd->flags & SD_SHARE_CPUCAPACITY) {
sd->flags |= SD_PREFER_SIBLING;
sd->imbalance_pct = 110;
sd->smt_gain = 1178; /* ~15% */
} else if (sd->flags & SD_SHARE_PKG_RESOURCES) {
sd->imbalance_pct = 117;
sd->cache_nice_tries = 1;
sd->busy_idx = 2;
#ifdef CONFIG_NUMA
} else if (sd->flags & SD_NUMA) {
sd->cache_nice_tries = 2;
sd->busy_idx = 3;
sd->idle_idx = 2;
sd->flags |= SD_SERIALIZE;
if (sched_domains_numa_distance[tl->numa_level] > RECLAIM_DISTANCE) {
sd->flags &= ~(SD_BALANCE_EXEC |
SD_BALANCE_FORK |
SD_WAKE_AFFINE);
}
#endif
} else {
sd->flags |= SD_PREFER_SIBLING;
sd->cache_nice_tries = 1;
sd->busy_idx = 2;
sd->idle_idx = 1;
}
sd->private = &tl->data;
return sd;
}
/*
* Topology list, bottom-up.
*/
static struct sched_domain_topology_level default_topology[] = {
#ifdef CONFIG_SCHED_SMT
{ cpu_smt_mask, cpu_smt_flags, SD_INIT_NAME(SMT) },
#endif
#ifdef CONFIG_SCHED_MC
{ cpu_coregroup_mask, cpu_core_flags, SD_INIT_NAME(MC) },
#endif
{ cpu_cpu_mask, SD_INIT_NAME(DIE) },
{ NULL, },
};
static struct sched_domain_topology_level *sched_domain_topology =
default_topology;
#define for_each_sd_topology(tl) \
for (tl = sched_domain_topology; tl->mask; tl++)
void set_sched_topology(struct sched_domain_topology_level *tl)
{
sched_domain_topology = tl;
}
#ifdef CONFIG_NUMA
static const struct cpumask *sd_numa_mask(int cpu)
{
return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
}
static void sched_numa_warn(const char *str)
{
static int done = false;
int i,j;
if (done)
return;
done = true;
printk(KERN_WARNING "ERROR: %s\n\n", str);
for (i = 0; i < nr_node_ids; i++) {
printk(KERN_WARNING " ");
for (j = 0; j < nr_node_ids; j++)
printk(KERN_CONT "%02d ", node_distance(i,j));
printk(KERN_CONT "\n");
}
printk(KERN_WARNING "\n");
}
bool find_numa_distance(int distance)
{
int i;
if (distance == node_distance(0, 0))
return true;
for (i = 0; i < sched_domains_numa_levels; i++) {
if (sched_domains_numa_distance[i] == distance)
return true;
}
return false;
}
/*
* A system can have three types of NUMA topology:
* NUMA_DIRECT: all nodes are directly connected, or not a NUMA system
* NUMA_GLUELESS_MESH: some nodes reachable through intermediary nodes
* NUMA_BACKPLANE: nodes can reach other nodes through a backplane
*
* The difference between a glueless mesh topology and a backplane
* topology lies in whether communication between not directly
* connected nodes goes through intermediary nodes (where programs
* could run), or through backplane controllers. This affects
* placement of programs.
*
* The type of topology can be discerned with the following tests:
* - If the maximum distance between any nodes is 1 hop, the system
* is directly connected.
* - If for two nodes A and B, located N > 1 hops away from each other,
* there is an intermediary node C, which is < N hops away from both
* nodes A and B, the system is a glueless mesh.
*/
static void init_numa_topology_type(void)
{
int a, b, c, n;
n = sched_max_numa_distance;
if (sched_domains_numa_levels <= 1) {
sched_numa_topology_type = NUMA_DIRECT;
return;
}
for_each_online_node(a) {
for_each_online_node(b) {
/* Find two nodes furthest removed from each other. */
if (node_distance(a, b) < n)
continue;
/* Is there an intermediary node between a and b? */
for_each_online_node(c) {
if (node_distance(a, c) < n &&
node_distance(b, c) < n) {
sched_numa_topology_type =
NUMA_GLUELESS_MESH;
return;
}
}
sched_numa_topology_type = NUMA_BACKPLANE;
return;
}
}
}
static void sched_init_numa(void)
{
int next_distance, curr_distance = node_distance(0, 0);
struct sched_domain_topology_level *tl;
int level = 0;
int i, j, k;
sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
if (!sched_domains_numa_distance)
return;
/*
* O(nr_nodes^2) deduplicating selection sort -- in order to find the
* unique distances in the node_distance() table.
*
* Assumes node_distance(0,j) includes all distances in
* node_distance(i,j) in order to avoid cubic time.
*/
next_distance = curr_distance;
for (i = 0; i < nr_node_ids; i++) {
for (j = 0; j < nr_node_ids; j++) {
for (k = 0; k < nr_node_ids; k++) {
int distance = node_distance(i, k);
if (distance > curr_distance &&
(distance < next_distance ||
next_distance == curr_distance))
next_distance = distance;
/*
* While not a strong assumption it would be nice to know
* about cases where if node A is connected to B, B is not
* equally connected to A.
*/
if (sched_debug() && node_distance(k, i) != distance)
sched_numa_warn("Node-distance not symmetric");
if (sched_debug() && i && !find_numa_distance(distance))
sched_numa_warn("Node-0 not representative");
}
if (next_distance != curr_distance) {
sched_domains_numa_distance[level++] = next_distance;
sched_domains_numa_levels = level;
curr_distance = next_distance;
} else break;
}
/*
* In case of sched_debug() we verify the above assumption.
*/
if (!sched_debug())
break;
}
if (!level)
return;
/*
* 'level' contains the number of unique distances, excluding the
* identity distance node_distance(i,i).
*
* The sched_domains_numa_distance[] array includes the actual distance
* numbers.
*/
/*
* Here, we should temporarily reset sched_domains_numa_levels to 0.
* If it fails to allocate memory for array sched_domains_numa_masks[][],
* the array will contain less then 'level' members. This could be
* dangerous when we use it to iterate array sched_domains_numa_masks[][]
* in other functions.
*
* We reset it to 'level' at the end of this function.
*/
sched_domains_numa_levels = 0;
sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
if (!sched_domains_numa_masks)
return;
/*
* Now for each level, construct a mask per node which contains all
* cpus of nodes that are that many hops away from us.
*/
for (i = 0; i < level; i++) {
sched_domains_numa_masks[i] =
kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
if (!sched_domains_numa_masks[i])
return;
for (j = 0; j < nr_node_ids; j++) {
struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
if (!mask)
return;
sched_domains_numa_masks[i][j] = mask;
for_each_node(k) {
if (node_distance(j, k) > sched_domains_numa_distance[i])
continue;
cpumask_or(mask, mask, cpumask_of_node(k));
}
}
}
/* Compute default topology size */
for (i = 0; sched_domain_topology[i].mask; i++);
tl = kzalloc((i + level + 1) *
sizeof(struct sched_domain_topology_level), GFP_KERNEL);
if (!tl)
return;
/*
* Copy the default topology bits..
*/
for (i = 0; sched_domain_topology[i].mask; i++)
tl[i] = sched_domain_topology[i];
/*
* .. and append 'j' levels of NUMA goodness.
*/
for (j = 0; j < level; i++, j++) {
tl[i] = (struct sched_domain_topology_level){
.mask = sd_numa_mask,
.sd_flags = cpu_numa_flags,
.flags = SDTL_OVERLAP,
.numa_level = j,
SD_INIT_NAME(NUMA)
};
}
sched_domain_topology = tl;
sched_domains_numa_levels = level;
sched_max_numa_distance = sched_domains_numa_distance[level - 1];
init_numa_topology_type();
}
static void sched_domains_numa_masks_set(unsigned int cpu)
{
int node = cpu_to_node(cpu);
int i, j;
for (i = 0; i < sched_domains_numa_levels; i++) {
for (j = 0; j < nr_node_ids; j++) {
if (node_distance(j, node) <= sched_domains_numa_distance[i])
cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
}
}
}
static void sched_domains_numa_masks_clear(unsigned int cpu)
{
int i, j;
for (i = 0; i < sched_domains_numa_levels; i++) {
for (j = 0; j < nr_node_ids; j++)
cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
}
}
#else
static inline void sched_init_numa(void) { }
static void sched_domains_numa_masks_set(unsigned int cpu) { }
static void sched_domains_numa_masks_clear(unsigned int cpu) { }
#endif /* CONFIG_NUMA */
static int __sdt_alloc(const struct cpumask *cpu_map)
{
struct sched_domain_topology_level *tl;
int j;
for_each_sd_topology(tl) {
struct sd_data *sdd = &tl->data;
sdd->sd = alloc_percpu(struct sched_domain *);
if (!sdd->sd)
return -ENOMEM;
sdd->sg = alloc_percpu(struct sched_group *);
if (!sdd->sg)
return -ENOMEM;
sdd->sgc = alloc_percpu(struct sched_group_capacity *);
if (!sdd->sgc)
return -ENOMEM;
for_each_cpu(j, cpu_map) {
struct sched_domain *sd;
struct sched_group *sg;
struct sched_group_capacity *sgc;
sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
GFP_KERNEL, cpu_to_node(j));
if (!sd)
return -ENOMEM;
*per_cpu_ptr(sdd->sd, j) = sd;
sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
GFP_KERNEL, cpu_to_node(j));
if (!sg)
return -ENOMEM;
sg->next = sg;
*per_cpu_ptr(sdd->sg, j) = sg;
sgc = kzalloc_node(sizeof(struct sched_group_capacity) + cpumask_size(),
GFP_KERNEL, cpu_to_node(j));
if (!sgc)
return -ENOMEM;
*per_cpu_ptr(sdd->sgc, j) = sgc;
}
}
return 0;
}
static void __sdt_free(const struct cpumask *cpu_map)
{
struct sched_domain_topology_level *tl;
int j;
for_each_sd_topology(tl) {
struct sd_data *sdd = &tl->data;
for_each_cpu(j, cpu_map) {
struct sched_domain *sd;
if (sdd->sd) {
sd = *per_cpu_ptr(sdd->sd, j);
if (sd && (sd->flags & SD_OVERLAP))
free_sched_groups(sd->groups, 0);
kfree(*per_cpu_ptr(sdd->sd, j));
}
if (sdd->sg)
kfree(*per_cpu_ptr(sdd->sg, j));
if (sdd->sgc)
kfree(*per_cpu_ptr(sdd->sgc, j));
}
free_percpu(sdd->sd);
sdd->sd = NULL;
free_percpu(sdd->sg);
sdd->sg = NULL;
free_percpu(sdd->sgc);
sdd->sgc = NULL;
}
}
struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
const struct cpumask *cpu_map, struct sched_domain_attr *attr,
struct sched_domain *child, int cpu)
{
struct sched_domain *sd = sd_init(tl, cpu);
if (!sd)
return child;
cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
if (child) {
sd->level = child->level + 1;
sched_domain_level_max = max(sched_domain_level_max, sd->level);
child->parent = sd;
sd->child = child;
if (!cpumask_subset(sched_domain_span(child),
sched_domain_span(sd))) {
pr_err("BUG: arch topology borken\n");
#ifdef CONFIG_SCHED_DEBUG
pr_err(" the %s domain not a subset of the %s domain\n",
child->name, sd->name);
#endif
/* Fixup, ensure @sd has at least @child cpus. */
cpumask_or(sched_domain_span(sd),
sched_domain_span(sd),
sched_domain_span(child));
}
}
set_domain_attribute(sd, attr);
return sd;
}
/*
* Build sched domains for a given set of cpus and attach the sched domains
* to the individual cpus
*/
static int build_sched_domains(const struct cpumask *cpu_map,
struct sched_domain_attr *attr)
{
enum s_alloc alloc_state;
struct sched_domain *sd;
struct s_data d;
int i, ret = -ENOMEM;
alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
if (alloc_state != sa_rootdomain)
goto error;
/* Set up domains for cpus specified by the cpu_map. */
for_each_cpu(i, cpu_map) {
struct sched_domain_topology_level *tl;
sd = NULL;
for_each_sd_topology(tl) {
sd = build_sched_domain(tl, cpu_map, attr, sd, i);
if (tl == sched_domain_topology)
*per_cpu_ptr(d.sd, i) = sd;
if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
sd->flags |= SD_OVERLAP;
if (cpumask_equal(cpu_map, sched_domain_span(sd)))
break;
}
}
/* Build the groups for the domains */
for_each_cpu(i, cpu_map) {
for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
sd->span_weight = cpumask_weight(sched_domain_span(sd));
if (sd->flags & SD_OVERLAP) {
if (build_overlap_sched_groups(sd, i))
goto error;
} else {
if (build_sched_groups(sd, i))
goto error;
}
}
}
/* Calculate CPU capacity for physical packages and nodes */
for (i = nr_cpumask_bits-1; i >= 0; i--) {
if (!cpumask_test_cpu(i, cpu_map))
continue;
for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
claim_allocations(i, sd);
init_sched_groups_capacity(i, sd);
}
}
/* Attach the domains */
rcu_read_lock();
for_each_cpu(i, cpu_map) {
sd = *per_cpu_ptr(d.sd, i);
cpu_attach_domain(sd, d.rd, i);
}
rcu_read_unlock();
ret = 0;
error:
__free_domain_allocs(&d, alloc_state, cpu_map);
return ret;
}
static cpumask_var_t *doms_cur; /* current sched domains */
static int ndoms_cur; /* number of sched domains in 'doms_cur' */
static struct sched_domain_attr *dattr_cur;
/* attribues of custom domains in 'doms_cur' */
/*
* Special case: If a kmalloc of a doms_cur partition (array of
* cpumask) fails, then fallback to a single sched domain,
* as determined by the single cpumask fallback_doms.
*/
static cpumask_var_t fallback_doms;
/*
* arch_update_cpu_topology lets virtualized architectures update the
* cpu core maps. It is supposed to return 1 if the topology changed
* or 0 if it stayed the same.
*/
int __weak arch_update_cpu_topology(void)
{
return 0;
}
cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
{
int i;
cpumask_var_t *doms;
doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
if (!doms)
return NULL;
for (i = 0; i < ndoms; i++) {
if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
free_sched_domains(doms, i);
return NULL;
}
}
return doms;
}
void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
{
unsigned int i;
for (i = 0; i < ndoms; i++)
free_cpumask_var(doms[i]);
kfree(doms);
}
/*
* Set up scheduler domains and groups. Callers must hold the hotplug lock.
* For now this just excludes isolated cpus, but could be used to
* exclude other special cases in the future.
*/
static int init_sched_domains(const struct cpumask *cpu_map)
{
int err;
arch_update_cpu_topology();
ndoms_cur = 1;
doms_cur = alloc_sched_domains(ndoms_cur);
if (!doms_cur)
doms_cur = &fallback_doms;
cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
err = build_sched_domains(doms_cur[0], NULL);
register_sched_domain_sysctl();
return err;
}
/*
* Detach sched domains from a group of cpus specified in cpu_map
* These cpus will now be attached to the NULL domain
*/
static void detach_destroy_domains(const struct cpumask *cpu_map)
{
int i;
rcu_read_lock();
for_each_cpu(i, cpu_map)
cpu_attach_domain(NULL, &def_root_domain, i);
rcu_read_unlock();
}
/* handle null as "default" */
static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
struct sched_domain_attr *new, int idx_new)
{
struct sched_domain_attr tmp;
/* fast path */
if (!new && !cur)
return 1;
tmp = SD_ATTR_INIT;
return !memcmp(cur ? (cur + idx_cur) : &tmp,
new ? (new + idx_new) : &tmp,
sizeof(struct sched_domain_attr));
}
/*
* Partition sched domains as specified by the 'ndoms_new'
* cpumasks in the array doms_new[] of cpumasks. This compares
* doms_new[] to the current sched domain partitioning, doms_cur[].
* It destroys each deleted domain and builds each new domain.
*
* 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
* The masks don't intersect (don't overlap.) We should setup one
* sched domain for each mask. CPUs not in any of the cpumasks will
* not be load balanced. If the same cpumask appears both in the
* current 'doms_cur' domains and in the new 'doms_new', we can leave
* it as it is.
*
* The passed in 'doms_new' should be allocated using
* alloc_sched_domains. This routine takes ownership of it and will
* free_sched_domains it when done with it. If the caller failed the
* alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
* and partition_sched_domains() will fallback to the single partition
* 'fallback_doms', it also forces the domains to be rebuilt.
*
* If doms_new == NULL it will be replaced with cpu_online_mask.
* ndoms_new == 0 is a special case for destroying existing domains,
* and it will not create the default domain.
*
* Call with hotplug lock held
*/
void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
struct sched_domain_attr *dattr_new)
{
int i, j, n;
int new_topology;
mutex_lock(&sched_domains_mutex);
/* always unregister in case we don't destroy any domains */
unregister_sched_domain_sysctl();
/* Let architecture update cpu core mappings. */
new_topology = arch_update_cpu_topology();
n = doms_new ? ndoms_new : 0;
/* Destroy deleted domains */
for (i = 0; i < ndoms_cur; i++) {
for (j = 0; j < n && !new_topology; j++) {
if (cpumask_equal(doms_cur[i], doms_new[j])
&& dattrs_equal(dattr_cur, i, dattr_new, j))
goto match1;
}
/* no match - a current sched domain not in new doms_new[] */
detach_destroy_domains(doms_cur[i]);
match1:
;
}
n = ndoms_cur;
if (doms_new == NULL) {
n = 0;
doms_new = &fallback_doms;
cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
WARN_ON_ONCE(dattr_new);
}
/* Build new domains */
for (i = 0; i < ndoms_new; i++) {
for (j = 0; j < n && !new_topology; j++) {
if (cpumask_equal(doms_new[i], doms_cur[j])
&& dattrs_equal(dattr_new, i, dattr_cur, j))
goto match2;
}
/* no match - add a new doms_new */
build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
match2:
;
}
/* Remember the new sched domains */
if (doms_cur != &fallback_doms)
free_sched_domains(doms_cur, ndoms_cur);
kfree(dattr_cur); /* kfree(NULL) is safe */
doms_cur = doms_new;
dattr_cur = dattr_new;
ndoms_cur = ndoms_new;
register_sched_domain_sysctl();
mutex_unlock(&sched_domains_mutex);
}
static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */
/*
* Update cpusets according to cpu_active mask. If cpusets are
* disabled, cpuset_update_active_cpus() becomes a simple wrapper
* around partition_sched_domains().
*
* If we come here as part of a suspend/resume, don't touch cpusets because we
* want to restore it back to its original state upon resume anyway.
*/
static void cpuset_cpu_active(void)
{
if (cpuhp_tasks_frozen) {
/*
* num_cpus_frozen tracks how many CPUs are involved in suspend
* resume sequence. As long as this is not the last online
* operation in the resume sequence, just build a single sched
* domain, ignoring cpusets.
*/
num_cpus_frozen--;
if (likely(num_cpus_frozen)) {
partition_sched_domains(1, NULL, NULL);
return;
}
/*
* This is the last CPU online operation. So fall through and
* restore the original sched domains by considering the
* cpuset configurations.
*/
}
cpuset_update_active_cpus(true);
}
static int cpuset_cpu_inactive(unsigned int cpu)
{
unsigned long flags;
struct dl_bw *dl_b;
bool overflow;
int cpus;
if (!cpuhp_tasks_frozen) {
rcu_read_lock_sched();
dl_b = dl_bw_of(cpu);
raw_spin_lock_irqsave(&dl_b->lock, flags);
cpus = dl_bw_cpus(cpu);
overflow = __dl_overflow(dl_b, cpus, 0, 0);
raw_spin_unlock_irqrestore(&dl_b->lock, flags);
rcu_read_unlock_sched();
if (overflow)
return -EBUSY;
cpuset_update_active_cpus(false);
} else {
num_cpus_frozen++;
partition_sched_domains(1, NULL, NULL);
}
return 0;
}
int sched_cpu_activate(unsigned int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long flags;
set_cpu_active(cpu, true);
if (sched_smp_initialized) {
sched_domains_numa_masks_set(cpu);
cpuset_cpu_active();
}
/*
* Put the rq online, if not already. This happens:
*
* 1) In the early boot process, because we build the real domains
* after all cpus have been brought up.
*
* 2) At runtime, if cpuset_cpu_active() fails to rebuild the
* domains.
*/
raw_spin_lock_irqsave(&rq->lock, flags);
if (rq->rd) {
BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
set_rq_online(rq);
}
raw_spin_unlock_irqrestore(&rq->lock, flags);
update_max_interval();
return 0;
}
int sched_cpu_deactivate(unsigned int cpu)
{
int ret;
set_cpu_active(cpu, false);
/*
* We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
* users of this state to go away such that all new such users will
* observe it.
*
* For CONFIG_PREEMPT we have preemptible RCU and its sync_rcu() might
* not imply sync_sched(), so wait for both.
*
* Do sync before park smpboot threads to take care the rcu boost case.
*/
if (IS_ENABLED(CONFIG_PREEMPT))
synchronize_rcu_mult(call_rcu, call_rcu_sched);
else
synchronize_rcu();
if (!sched_smp_initialized)
return 0;
ret = cpuset_cpu_inactive(cpu);
if (ret) {
set_cpu_active(cpu, true);
return ret;
}
sched_domains_numa_masks_clear(cpu);
return 0;
}
static void sched_rq_cpu_starting(unsigned int cpu)
{
struct rq *rq = cpu_rq(cpu);
rq->calc_load_update = calc_load_update;
account_reset_rq(rq);
update_max_interval();
}
int sched_cpu_starting(unsigned int cpu)
{
set_cpu_rq_start_time(cpu);
sched_rq_cpu_starting(cpu);
return 0;
}
#ifdef CONFIG_HOTPLUG_CPU
int sched_cpu_dying(unsigned int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long flags;
/* Handle pending wakeups and then migrate everything off */
sched_ttwu_pending();
raw_spin_lock_irqsave(&rq->lock, flags);
if (rq->rd) {
BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
set_rq_offline(rq);
}
migrate_tasks(rq);
BUG_ON(rq->nr_running != 1);
raw_spin_unlock_irqrestore(&rq->lock, flags);
calc_load_migrate(rq);
update_max_interval();
nohz_balance_exit_idle(cpu);
hrtick_clear(rq);
return 0;
}
#endif
void __init sched_init_smp(void)
{
cpumask_var_t non_isolated_cpus;
alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
sched_init_numa();
/*
* There's no userspace yet to cause hotplug operations; hence all the
* cpu masks are stable and all blatant races in the below code cannot
* happen.
*/
mutex_lock(&sched_domains_mutex);
init_sched_domains(cpu_active_mask);
cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
if (cpumask_empty(non_isolated_cpus))
cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
mutex_unlock(&sched_domains_mutex);
/* Move init over to a non-isolated CPU */
if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
BUG();
sched_init_granularity();
free_cpumask_var(non_isolated_cpus);
init_sched_rt_class();
init_sched_dl_class();
sched_smp_initialized = true;
}
static int __init migration_init(void)
{
sched_rq_cpu_starting(smp_processor_id());
return 0;
}
early_initcall(migration_init);
#else
void __init sched_init_smp(void)
{
sched_init_granularity();
}
#endif /* CONFIG_SMP */
int in_sched_functions(unsigned long addr)
{
return in_lock_functions(addr) ||
(addr >= (unsigned long)__sched_text_start
&& addr < (unsigned long)__sched_text_end);
}
#ifdef CONFIG_CGROUP_SCHED
/*
* Default task group.
* Every task in system belongs to this group at bootup.
*/
struct task_group root_task_group;
LIST_HEAD(task_groups);
/* Cacheline aligned slab cache for task_group */
static struct kmem_cache *task_group_cache __read_mostly;
#endif
DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
void __init sched_init(void)
{
int i, j;
unsigned long alloc_size = 0, ptr;
#ifdef CONFIG_FAIR_GROUP_SCHED
alloc_size += 2 * nr_cpu_ids * sizeof(void **);
#endif
#ifdef CONFIG_RT_GROUP_SCHED
alloc_size += 2 * nr_cpu_ids * sizeof(void **);
#endif
if (alloc_size) {
ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
#ifdef CONFIG_FAIR_GROUP_SCHED
root_task_group.se = (struct sched_entity **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
root_task_group.cfs_rq = (struct cfs_rq **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
#endif /* CONFIG_FAIR_GROUP_SCHED */
#ifdef CONFIG_RT_GROUP_SCHED
root_task_group.rt_se = (struct sched_rt_entity **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
root_task_group.rt_rq = (struct rt_rq **)ptr;
ptr += nr_cpu_ids * sizeof(void **);
#endif /* CONFIG_RT_GROUP_SCHED */
}
#ifdef CONFIG_CPUMASK_OFFSTACK
for_each_possible_cpu(i) {
per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
cpumask_size(), GFP_KERNEL, cpu_to_node(i));
}
#endif /* CONFIG_CPUMASK_OFFSTACK */
init_rt_bandwidth(&def_rt_bandwidth,
global_rt_period(), global_rt_runtime());
init_dl_bandwidth(&def_dl_bandwidth,
global_rt_period(), global_rt_runtime());
#ifdef CONFIG_SMP
init_defrootdomain();
#endif
#ifdef CONFIG_RT_GROUP_SCHED
init_rt_bandwidth(&root_task_group.rt_bandwidth,
global_rt_period(), global_rt_runtime());
#endif /* CONFIG_RT_GROUP_SCHED */
#ifdef CONFIG_CGROUP_SCHED
task_group_cache = KMEM_CACHE(task_group, 0);
list_add(&root_task_group.list, &task_groups);
INIT_LIST_HEAD(&root_task_group.children);
INIT_LIST_HEAD(&root_task_group.siblings);
autogroup_init(&init_task);
#endif /* CONFIG_CGROUP_SCHED */
for_each_possible_cpu(i) {
struct rq *rq;
rq = cpu_rq(i);
raw_spin_lock_init(&rq->lock);
rq->nr_running = 0;
rq->calc_load_active = 0;
rq->calc_load_update = jiffies + LOAD_FREQ;
init_cfs_rq(&rq->cfs);
init_rt_rq(&rq->rt);
init_dl_rq(&rq->dl);
#ifdef CONFIG_FAIR_GROUP_SCHED
root_task_group.shares = ROOT_TASK_GROUP_LOAD;
INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
/*
* How much cpu bandwidth does root_task_group get?
*
* In case of task-groups formed thr' the cgroup filesystem, it
* gets 100% of the cpu resources in the system. This overall
* system cpu resource is divided among the tasks of
* root_task_group and its child task-groups in a fair manner,
* based on each entity's (task or task-group's) weight
* (se->load.weight).
*
* In other words, if root_task_group has 10 tasks of weight
* 1024) and two child groups A0 and A1 (of weight 1024 each),
* then A0's share of the cpu resource is:
*
* A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
*
* We achieve this by letting root_task_group's tasks sit
* directly in rq->cfs (i.e root_task_group->se[] = NULL).
*/
init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
#endif /* CONFIG_FAIR_GROUP_SCHED */
rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
#ifdef CONFIG_RT_GROUP_SCHED
init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
#endif
for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
rq->cpu_load[j] = 0;
#ifdef CONFIG_SMP
rq->sd = NULL;
rq->rd = NULL;
rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
rq->balance_callback = NULL;
rq->active_balance = 0;
rq->next_balance = jiffies;
rq->push_cpu = 0;
rq->cpu = i;
rq->online = 0;
rq->idle_stamp = 0;
rq->avg_idle = 2*sysctl_sched_migration_cost;
rq->max_idle_balance_cost = sysctl_sched_migration_cost;
INIT_LIST_HEAD(&rq->cfs_tasks);
rq_attach_root(rq, &def_root_domain);
#ifdef CONFIG_NO_HZ_COMMON
rq->last_load_update_tick = jiffies;
rq->nohz_flags = 0;
#endif
#ifdef CONFIG_NO_HZ_FULL
rq->last_sched_tick = 0;
#endif
#endif /* CONFIG_SMP */
init_rq_hrtick(rq);
atomic_set(&rq->nr_iowait, 0);
}
set_load_weight(&init_task);
#ifdef CONFIG_PREEMPT_NOTIFIERS
INIT_HLIST_HEAD(&init_task.preempt_notifiers);
#endif
/*
* The boot idle thread does lazy MMU switching as well:
*/
atomic_inc(&init_mm.mm_count);
enter_lazy_tlb(&init_mm, current);
/*
* During early bootup we pretend to be a normal task:
*/
current->sched_class = &fair_sched_class;
/*
* Make us the idle thread. Technically, schedule() should not be
* called from this thread, however somewhere below it might be,
* but because we are the idle thread, we just pick up running again
* when this runqueue becomes "idle".
*/
init_idle(current, smp_processor_id());
calc_load_update = jiffies + LOAD_FREQ;
#ifdef CONFIG_SMP
zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
/* May be allocated at isolcpus cmdline parse time */
if (cpu_isolated_map == NULL)
zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
idle_thread_set_boot_cpu();
set_cpu_rq_start_time(smp_processor_id());
#endif
init_sched_fair_class();
init_schedstats();
scheduler_running = 1;
}
#ifdef CONFIG_DEBUG_ATOMIC_SLEEP
static inline int preempt_count_equals(int preempt_offset)
{
int nested = preempt_count() + rcu_preempt_depth();
return (nested == preempt_offset);
}
void __might_sleep(const char *file, int line, int preempt_offset)
{
/*
* Blocking primitives will set (and therefore destroy) current->state,
* since we will exit with TASK_RUNNING make sure we enter with it,
* otherwise we will destroy state.
*/
WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
"do not call blocking ops when !TASK_RUNNING; "
"state=%lx set at [<%p>] %pS\n",
current->state,
(void *)current->task_state_change,
(void *)current->task_state_change);
___might_sleep(file, line, preempt_offset);
}
EXPORT_SYMBOL(__might_sleep);
void ___might_sleep(const char *file, int line, int preempt_offset)
{
static unsigned long prev_jiffy; /* ratelimiting */
rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
!is_idle_task(current)) ||
system_state != SYSTEM_RUNNING || oops_in_progress)
return;
if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
return;
prev_jiffy = jiffies;
printk(KERN_ERR
"BUG: sleeping function called from invalid context at %s:%d\n",
file, line);
printk(KERN_ERR
"in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
in_atomic(), irqs_disabled(),
current->pid, current->comm);
if (task_stack_end_corrupted(current))
printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
debug_show_held_locks(current);
if (irqs_disabled())
print_irqtrace_events(current);
#ifdef CONFIG_DEBUG_PREEMPT
if (!preempt_count_equals(preempt_offset)) {
pr_err("Preemption disabled at:");
print_ip_sym(current->preempt_disable_ip);
pr_cont("\n");
}
#endif
dump_stack();
}
EXPORT_SYMBOL(___might_sleep);
#endif
#ifdef CONFIG_MAGIC_SYSRQ
void normalize_rt_tasks(void)
{
struct task_struct *g, *p;
struct sched_attr attr = {
.sched_policy = SCHED_NORMAL,
};
read_lock(&tasklist_lock);
for_each_process_thread(g, p) {
/*
* Only normalize user tasks:
*/
if (p->flags & PF_KTHREAD)
continue;
p->se.exec_start = 0;
#ifdef CONFIG_SCHEDSTATS
p->se.statistics.wait_start = 0;
p->se.statistics.sleep_start = 0;
p->se.statistics.block_start = 0;
#endif
if (!dl_task(p) && !rt_task(p)) {
/*
* Renice negative nice level userspace
* tasks back to 0:
*/
if (task_nice(p) < 0)
set_user_nice(p, 0);
continue;
}
__sched_setscheduler(p, &attr, false, false);
}
read_unlock(&tasklist_lock);
}
#endif /* CONFIG_MAGIC_SYSRQ */
#if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
/*
* These functions are only useful for the IA64 MCA handling, or kdb.
*
* They can only be called when the whole system has been
* stopped - every CPU needs to be quiescent, and no scheduling
* activity can take place. Using them for anything else would
* be a serious bug, and as a result, they aren't even visible
* under any other configuration.
*/
/**
* curr_task - return the current task for a given cpu.
* @cpu: the processor in question.
*
* ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
*
* Return: The current task for @cpu.
*/
struct task_struct *curr_task(int cpu)
{
return cpu_curr(cpu);
}
#endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
#ifdef CONFIG_IA64
/**
* set_curr_task - set the current task for a given cpu.
* @cpu: the processor in question.
* @p: the task pointer to set.
*
* Description: This function must only be used when non-maskable interrupts
* are serviced on a separate stack. It allows the architecture to switch the
* notion of the current task on a cpu in a non-blocking manner. This function
* must be called with all CPU's synchronized, and interrupts disabled, the
* and caller must save the original value of the current task (see
* curr_task() above) and restore that value before reenabling interrupts and
* re-starting the system.
*
* ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
*/
void set_curr_task(int cpu, struct task_struct *p)
{
cpu_curr(cpu) = p;
}
#endif
#ifdef CONFIG_CGROUP_SCHED
/* task_group_lock serializes the addition/removal of task groups */
static DEFINE_SPINLOCK(task_group_lock);
static void sched_free_group(struct task_group *tg)
{
free_fair_sched_group(tg);
free_rt_sched_group(tg);
autogroup_free(tg);
kmem_cache_free(task_group_cache, tg);
}
/* allocate runqueue etc for a new task group */
struct task_group *sched_create_group(struct task_group *parent)
{
struct task_group *tg;
tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
if (!tg)
return ERR_PTR(-ENOMEM);
if (!alloc_fair_sched_group(tg, parent))
goto err;
if (!alloc_rt_sched_group(tg, parent))
goto err;
return tg;
err:
sched_free_group(tg);
return ERR_PTR(-ENOMEM);
}
void sched_online_group(struct task_group *tg, struct task_group *parent)
{
unsigned long flags;
spin_lock_irqsave(&task_group_lock, flags);
list_add_rcu(&tg->list, &task_groups);
WARN_ON(!parent); /* root should already exist */
tg->parent = parent;
INIT_LIST_HEAD(&tg->children);
list_add_rcu(&tg->siblings, &parent->children);
spin_unlock_irqrestore(&task_group_lock, flags);
}
/* rcu callback to free various structures associated with a task group */
static void sched_free_group_rcu(struct rcu_head *rhp)
{
/* now it should be safe to free those cfs_rqs */
sched_free_group(container_of(rhp, struct task_group, rcu));
}
void sched_destroy_group(struct task_group *tg)
{
/* wait for possible concurrent references to cfs_rqs complete */
call_rcu(&tg->rcu, sched_free_group_rcu);
}
void sched_offline_group(struct task_group *tg)
{
unsigned long flags;
/* end participation in shares distribution */
unregister_fair_sched_group(tg);
spin_lock_irqsave(&task_group_lock, flags);
list_del_rcu(&tg->list);
list_del_rcu(&tg->siblings);
spin_unlock_irqrestore(&task_group_lock, flags);
}
/* change task's runqueue when it moves between groups.
* The caller of this function should have put the task in its new group
* by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
* reflect its new group.
*/
void sched_move_task(struct task_struct *tsk)
{
struct task_group *tg;
int queued, running;
struct rq_flags rf;
struct rq *rq;
rq = task_rq_lock(tsk, &rf);
running = task_current(rq, tsk);
queued = task_on_rq_queued(tsk);
if (queued)
dequeue_task(rq, tsk, DEQUEUE_SAVE | DEQUEUE_MOVE);
if (unlikely(running))
put_prev_task(rq, tsk);
/*
* All callers are synchronized by task_rq_lock(); we do not use RCU
* which is pointless here. Thus, we pass "true" to task_css_check()
* to prevent lockdep warnings.
*/
tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
struct task_group, css);
tg = autogroup_task_group(tsk, tg);
tsk->sched_task_group = tg;
#ifdef CONFIG_FAIR_GROUP_SCHED
if (tsk->sched_class->task_move_group)
tsk->sched_class->task_move_group(tsk);
else
#endif
set_task_rq(tsk, task_cpu(tsk));
if (unlikely(running))
tsk->sched_class->set_curr_task(rq);
if (queued)
enqueue_task(rq, tsk, ENQUEUE_RESTORE | ENQUEUE_MOVE);
task_rq_unlock(rq, tsk, &rf);
}
#endif /* CONFIG_CGROUP_SCHED */
#ifdef CONFIG_RT_GROUP_SCHED
/*
* Ensure that the real time constraints are schedulable.
*/
static DEFINE_MUTEX(rt_constraints_mutex);
/* Must be called with tasklist_lock held */
static inline int tg_has_rt_tasks(struct task_group *tg)
{
struct task_struct *g, *p;
/*
* Autogroups do not have RT tasks; see autogroup_create().
*/
if (task_group_is_autogroup(tg))
return 0;
for_each_process_thread(g, p) {
if (rt_task(p) && task_group(p) == tg)
return 1;
}
return 0;
}
struct rt_schedulable_data {
struct task_group *tg;
u64 rt_period;
u64 rt_runtime;
};
static int tg_rt_schedulable(struct task_group *tg, void *data)
{
struct rt_schedulable_data *d = data;
struct task_group *child;
unsigned long total, sum = 0;
u64 period, runtime;
period = ktime_to_ns(tg->rt_bandwidth.rt_period);
runtime = tg->rt_bandwidth.rt_runtime;
if (tg == d->tg) {
period = d->rt_period;
runtime = d->rt_runtime;
}
/*
* Cannot have more runtime than the period.
*/
if (runtime > period && runtime != RUNTIME_INF)
return -EINVAL;
/*
* Ensure we don't starve existing RT tasks.
*/
if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
return -EBUSY;
total = to_ratio(period, runtime);
/*
* Nobody can have more than the global setting allows.
*/
if (total > to_ratio(global_rt_period(), global_rt_runtime()))
return -EINVAL;
/*
* The sum of our children's runtime should not exceed our own.
*/
list_for_each_entry_rcu(child, &tg->children, siblings) {
period = ktime_to_ns(child->rt_bandwidth.rt_period);
runtime = child->rt_bandwidth.rt_runtime;
if (child == d->tg) {
period = d->rt_period;
runtime = d->rt_runtime;
}
sum += to_ratio(period, runtime);
}
if (sum > total)
return -EINVAL;
return 0;
}
static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
{
int ret;
struct rt_schedulable_data data = {
.tg = tg,
.rt_period = period,
.rt_runtime = runtime,
};
rcu_read_lock();
ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
rcu_read_unlock();
return ret;
}
static int tg_set_rt_bandwidth(struct task_group *tg,
u64 rt_period, u64 rt_runtime)
{
int i, err = 0;
/*
* Disallowing the root group RT runtime is BAD, it would disallow the
* kernel creating (and or operating) RT threads.
*/
if (tg == &root_task_group && rt_runtime == 0)
return -EINVAL;
/* No period doesn't make any sense. */
if (rt_period == 0)
return -EINVAL;
mutex_lock(&rt_constraints_mutex);
read_lock(&tasklist_lock);
err = __rt_schedulable(tg, rt_period, rt_runtime);
if (err)
goto unlock;
raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
tg->rt_bandwidth.rt_runtime = rt_runtime;
for_each_possible_cpu(i) {
struct rt_rq *rt_rq = tg->rt_rq[i];
raw_spin_lock(&rt_rq->rt_runtime_lock);
rt_rq->rt_runtime = rt_runtime;
raw_spin_unlock(&rt_rq->rt_runtime_lock);
}
raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
unlock:
read_unlock(&tasklist_lock);
mutex_unlock(&rt_constraints_mutex);
return err;
}
static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
{
u64 rt_runtime, rt_period;
rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
if (rt_runtime_us < 0)
rt_runtime = RUNTIME_INF;
return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
}
static long sched_group_rt_runtime(struct task_group *tg)
{
u64 rt_runtime_us;
if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
return -1;
rt_runtime_us = tg->rt_bandwidth.rt_runtime;
do_div(rt_runtime_us, NSEC_PER_USEC);
return rt_runtime_us;
}
static int sched_group_set_rt_period(struct task_group *tg, u64 rt_period_us)
{
u64 rt_runtime, rt_period;
rt_period = rt_period_us * NSEC_PER_USEC;
rt_runtime = tg->rt_bandwidth.rt_runtime;
return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
}
static long sched_group_rt_period(struct task_group *tg)
{
u64 rt_period_us;
rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
do_div(rt_period_us, NSEC_PER_USEC);
return rt_period_us;
}
#endif /* CONFIG_RT_GROUP_SCHED */
#ifdef CONFIG_RT_GROUP_SCHED
static int sched_rt_global_constraints(void)
{
int ret = 0;
mutex_lock(&rt_constraints_mutex);
read_lock(&tasklist_lock);
ret = __rt_schedulable(NULL, 0, 0);
read_unlock(&tasklist_lock);
mutex_unlock(&rt_constraints_mutex);
return ret;
}
static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
{
/* Don't accept realtime tasks when there is no way for them to run */
if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
return 0;
return 1;
}
#else /* !CONFIG_RT_GROUP_SCHED */
static int sched_rt_global_constraints(void)
{
unsigned long flags;
int i;
raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
for_each_possible_cpu(i) {
struct rt_rq *rt_rq = &cpu_rq(i)->rt;
raw_spin_lock(&rt_rq->rt_runtime_lock);
rt_rq->rt_runtime = global_rt_runtime();
raw_spin_unlock(&rt_rq->rt_runtime_lock);
}
raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
return 0;
}
#endif /* CONFIG_RT_GROUP_SCHED */
static int sched_dl_global_validate(void)
{
u64 runtime = global_rt_runtime();
u64 period = global_rt_period();
u64 new_bw = to_ratio(period, runtime);
struct dl_bw *dl_b;
int cpu, ret = 0;
unsigned long flags;
/*
* Here we want to check the bandwidth not being set to some
* value smaller than the currently allocated bandwidth in
* any of the root_domains.
*
* FIXME: Cycling on all the CPUs is overdoing, but simpler than
* cycling on root_domains... Discussion on different/better
* solutions is welcome!
*/
for_each_possible_cpu(cpu) {
rcu_read_lock_sched();
dl_b = dl_bw_of(cpu);
raw_spin_lock_irqsave(&dl_b->lock, flags);
if (new_bw < dl_b->total_bw)
ret = -EBUSY;
raw_spin_unlock_irqrestore(&dl_b->lock, flags);
rcu_read_unlock_sched();
if (ret)
break;
}
return ret;
}
static void sched_dl_do_global(void)
{
u64 new_bw = -1;
struct dl_bw *dl_b;
int cpu;
unsigned long flags;
def_dl_bandwidth.dl_period = global_rt_period();
def_dl_bandwidth.dl_runtime = global_rt_runtime();
if (global_rt_runtime() != RUNTIME_INF)
new_bw = to_ratio(global_rt_period(), global_rt_runtime());
/*
* FIXME: As above...
*/
for_each_possible_cpu(cpu) {
rcu_read_lock_sched();
dl_b = dl_bw_of(cpu);
raw_spin_lock_irqsave(&dl_b->lock, flags);
dl_b->bw = new_bw;
raw_spin_unlock_irqrestore(&dl_b->lock, flags);
rcu_read_unlock_sched();
}
}
static int sched_rt_global_validate(void)
{
if (sysctl_sched_rt_period <= 0)
return -EINVAL;
if ((sysctl_sched_rt_runtime != RUNTIME_INF) &&
(sysctl_sched_rt_runtime > sysctl_sched_rt_period))
return -EINVAL;
return 0;
}
static void sched_rt_do_global(void)
{
def_rt_bandwidth.rt_runtime = global_rt_runtime();
def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period());
}
int sched_rt_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int old_period, old_runtime;
static DEFINE_MUTEX(mutex);
int ret;
mutex_lock(&mutex);
old_period = sysctl_sched_rt_period;
old_runtime = sysctl_sched_rt_runtime;
ret = proc_dointvec(table, write, buffer, lenp, ppos);
if (!ret && write) {
ret = sched_rt_global_validate();
if (ret)
goto undo;
ret = sched_dl_global_validate();
if (ret)
goto undo;
ret = sched_rt_global_constraints();
if (ret)
goto undo;
sched_rt_do_global();
sched_dl_do_global();
}
if (0) {
undo:
sysctl_sched_rt_period = old_period;
sysctl_sched_rt_runtime = old_runtime;
}
mutex_unlock(&mutex);
return ret;
}
int sched_rr_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret;
static DEFINE_MUTEX(mutex);
mutex_lock(&mutex);
ret = proc_dointvec(table, write, buffer, lenp, ppos);
/* make sure that internally we keep jiffies */
/* also, writing zero resets timeslice to default */
if (!ret && write) {
sched_rr_timeslice = sched_rr_timeslice <= 0 ?
RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
}
mutex_unlock(&mutex);
return ret;
}
#ifdef CONFIG_CGROUP_SCHED
static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
{
return css ? container_of(css, struct task_group, css) : NULL;
}
static struct cgroup_subsys_state *
cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
{
struct task_group *parent = css_tg(parent_css);
struct task_group *tg;
if (!parent) {
/* This is early initialization for the top cgroup */
return &root_task_group.css;
}
tg = sched_create_group(parent);
if (IS_ERR(tg))
return ERR_PTR(-ENOMEM);
sched_online_group(tg, parent);
return &tg->css;
}
static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
{
struct task_group *tg = css_tg(css);
sched_offline_group(tg);
}
static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
{
struct task_group *tg = css_tg(css);
/*
* Relies on the RCU grace period between css_released() and this.
*/
sched_free_group(tg);
}
static void cpu_cgroup_fork(struct task_struct *task)
{
sched_move_task(task);
}
static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
{
struct task_struct *task;
struct cgroup_subsys_state *css;
cgroup_taskset_for_each(task, css, tset) {
#ifdef CONFIG_RT_GROUP_SCHED
if (!sched_rt_can_attach(css_tg(css), task))
return -EINVAL;
#else
/* We don't support RT-tasks being in separate groups */
if (task->sched_class != &fair_sched_class)
return -EINVAL;
#endif
}
return 0;
}
static void cpu_cgroup_attach(struct cgroup_taskset *tset)
{
struct task_struct *task;
struct cgroup_subsys_state *css;
cgroup_taskset_for_each(task, css, tset)
sched_move_task(task);
}
#ifdef CONFIG_FAIR_GROUP_SCHED
static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
struct cftype *cftype, u64 shareval)
{
return sched_group_set_shares(css_tg(css), scale_load(shareval));
}
static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
struct cftype *cft)
{
struct task_group *tg = css_tg(css);
return (u64) scale_load_down(tg->shares);
}
#ifdef CONFIG_CFS_BANDWIDTH
static DEFINE_MUTEX(cfs_constraints_mutex);
const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
{
int i, ret = 0, runtime_enabled, runtime_was_enabled;
struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
if (tg == &root_task_group)
return -EINVAL;
/*
* Ensure we have at some amount of bandwidth every period. This is
* to prevent reaching a state of large arrears when throttled via
* entity_tick() resulting in prolonged exit starvation.
*/
if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
return -EINVAL;
/*
* Likewise, bound things on the otherside by preventing insane quota
* periods. This also allows us to normalize in computing quota
* feasibility.
*/
if (period > max_cfs_quota_period)
return -EINVAL;
/*
* Prevent race between setting of cfs_rq->runtime_enabled and
* unthrottle_offline_cfs_rqs().
*/
get_online_cpus();
mutex_lock(&cfs_constraints_mutex);
ret = __cfs_schedulable(tg, period, quota);
if (ret)
goto out_unlock;
runtime_enabled = quota != RUNTIME_INF;
runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
/*
* If we need to toggle cfs_bandwidth_used, off->on must occur
* before making related changes, and on->off must occur afterwards
*/
if (runtime_enabled && !runtime_was_enabled)
cfs_bandwidth_usage_inc();
raw_spin_lock_irq(&cfs_b->lock);
cfs_b->period = ns_to_ktime(period);
cfs_b->quota = quota;
__refill_cfs_bandwidth_runtime(cfs_b);
/* restart the period timer (if active) to handle new period expiry */
if (runtime_enabled)
start_cfs_bandwidth(cfs_b);
raw_spin_unlock_irq(&cfs_b->lock);
for_each_online_cpu(i) {
struct cfs_rq *cfs_rq = tg->cfs_rq[i];
struct rq *rq = cfs_rq->rq;
raw_spin_lock_irq(&rq->lock);
cfs_rq->runtime_enabled = runtime_enabled;
cfs_rq->runtime_remaining = 0;
if (cfs_rq->throttled)
unthrottle_cfs_rq(cfs_rq);
raw_spin_unlock_irq(&rq->lock);
}
if (runtime_was_enabled && !runtime_enabled)
cfs_bandwidth_usage_dec();
out_unlock:
mutex_unlock(&cfs_constraints_mutex);
put_online_cpus();
return ret;
}
int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
{
u64 quota, period;
period = ktime_to_ns(tg->cfs_bandwidth.period);
if (cfs_quota_us < 0)
quota = RUNTIME_INF;
else
quota = (u64)cfs_quota_us * NSEC_PER_USEC;
return tg_set_cfs_bandwidth(tg, period, quota);
}
long tg_get_cfs_quota(struct task_group *tg)
{
u64 quota_us;
if (tg->cfs_bandwidth.quota == RUNTIME_INF)
return -1;
quota_us = tg->cfs_bandwidth.quota;
do_div(quota_us, NSEC_PER_USEC);
return quota_us;
}
int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
{
u64 quota, period;
period = (u64)cfs_period_us * NSEC_PER_USEC;
quota = tg->cfs_bandwidth.quota;
return tg_set_cfs_bandwidth(tg, period, quota);
}
long tg_get_cfs_period(struct task_group *tg)
{
u64 cfs_period_us;
cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
do_div(cfs_period_us, NSEC_PER_USEC);
return cfs_period_us;
}
static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
struct cftype *cft)
{
return tg_get_cfs_quota(css_tg(css));
}
static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
struct cftype *cftype, s64 cfs_quota_us)
{
return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
}
static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
struct cftype *cft)
{
return tg_get_cfs_period(css_tg(css));
}
static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
struct cftype *cftype, u64 cfs_period_us)
{
return tg_set_cfs_period(css_tg(css), cfs_period_us);
}
struct cfs_schedulable_data {
struct task_group *tg;
u64 period, quota;
};
/*
* normalize group quota/period to be quota/max_period
* note: units are usecs
*/
static u64 normalize_cfs_quota(struct task_group *tg,
struct cfs_schedulable_data *d)
{
u64 quota, period;
if (tg == d->tg) {
period = d->period;
quota = d->quota;
} else {
period = tg_get_cfs_period(tg);
quota = tg_get_cfs_quota(tg);
}
/* note: these should typically be equivalent */
if (quota == RUNTIME_INF || quota == -1)
return RUNTIME_INF;
return to_ratio(period, quota);
}
static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
{
struct cfs_schedulable_data *d = data;
struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
s64 quota = 0, parent_quota = -1;
if (!tg->parent) {
quota = RUNTIME_INF;
} else {
struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
quota = normalize_cfs_quota(tg, d);
parent_quota = parent_b->hierarchical_quota;
/*
* ensure max(child_quota) <= parent_quota, inherit when no
* limit is set
*/
if (quota == RUNTIME_INF)
quota = parent_quota;
else if (parent_quota != RUNTIME_INF && quota > parent_quota)
return -EINVAL;
}
cfs_b->hierarchical_quota = quota;
return 0;
}
static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
{
int ret;
struct cfs_schedulable_data data = {
.tg = tg,
.period = period,
.quota = quota,
};
if (quota != RUNTIME_INF) {
do_div(data.period, NSEC_PER_USEC);
do_div(data.quota, NSEC_PER_USEC);
}
rcu_read_lock();
ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
rcu_read_unlock();
return ret;
}
static int cpu_stats_show(struct seq_file *sf, void *v)
{
struct task_group *tg = css_tg(seq_css(sf));
struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
return 0;
}
#endif /* CONFIG_CFS_BANDWIDTH */
#endif /* CONFIG_FAIR_GROUP_SCHED */
#ifdef CONFIG_RT_GROUP_SCHED
static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
struct cftype *cft, s64 val)
{
return sched_group_set_rt_runtime(css_tg(css), val);
}
static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
struct cftype *cft)
{
return sched_group_rt_runtime(css_tg(css));
}
static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
struct cftype *cftype, u64 rt_period_us)
{
return sched_group_set_rt_period(css_tg(css), rt_period_us);
}
static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
struct cftype *cft)
{
return sched_group_rt_period(css_tg(css));
}
#endif /* CONFIG_RT_GROUP_SCHED */
static struct cftype cpu_files[] = {
#ifdef CONFIG_FAIR_GROUP_SCHED
{
.name = "shares",
.read_u64 = cpu_shares_read_u64,
.write_u64 = cpu_shares_write_u64,
},
#endif
#ifdef CONFIG_CFS_BANDWIDTH
{
.name = "cfs_quota_us",
.read_s64 = cpu_cfs_quota_read_s64,
.write_s64 = cpu_cfs_quota_write_s64,
},
{
.name = "cfs_period_us",
.read_u64 = cpu_cfs_period_read_u64,
.write_u64 = cpu_cfs_period_write_u64,
},
{
.name = "stat",
.seq_show = cpu_stats_show,
},
#endif
#ifdef CONFIG_RT_GROUP_SCHED
{
.name = "rt_runtime_us",
.read_s64 = cpu_rt_runtime_read,
.write_s64 = cpu_rt_runtime_write,
},
{
.name = "rt_period_us",
.read_u64 = cpu_rt_period_read_uint,
.write_u64 = cpu_rt_period_write_uint,
},
#endif
{ } /* terminate */
};
struct cgroup_subsys cpu_cgrp_subsys = {
.css_alloc = cpu_cgroup_css_alloc,
.css_released = cpu_cgroup_css_released,
.css_free = cpu_cgroup_css_free,
.fork = cpu_cgroup_fork,
.can_attach = cpu_cgroup_can_attach,
.attach = cpu_cgroup_attach,
.legacy_cftypes = cpu_files,
.early_init = true,
};
#endif /* CONFIG_CGROUP_SCHED */
void dump_cpu_task(int cpu)
{
pr_info("Task dump for CPU %d:\n", cpu);
sched_show_task(cpu_curr(cpu));
}
/*
* Nice levels are multiplicative, with a gentle 10% change for every
* nice level changed. I.e. when a CPU-bound task goes from nice 0 to
* nice 1, it will get ~10% less CPU time than another CPU-bound task
* that remained on nice 0.
*
* The "10% effect" is relative and cumulative: from _any_ nice level,
* if you go up 1 level, it's -10% CPU usage, if you go down 1 level
* it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
* If a task goes up by ~10% and another task goes down by ~10% then
* the relative distance between them is ~25%.)
*/
const int sched_prio_to_weight[40] = {
/* -20 */ 88761, 71755, 56483, 46273, 36291,
/* -15 */ 29154, 23254, 18705, 14949, 11916,
/* -10 */ 9548, 7620, 6100, 4904, 3906,
/* -5 */ 3121, 2501, 1991, 1586, 1277,
/* 0 */ 1024, 820, 655, 526, 423,
/* 5 */ 335, 272, 215, 172, 137,
/* 10 */ 110, 87, 70, 56, 45,
/* 15 */ 36, 29, 23, 18, 15,
};
/*
* Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
*
* In cases where the weight does not change often, we can use the
* precalculated inverse to speed up arithmetics by turning divisions
* into multiplications:
*/
const u32 sched_prio_to_wmult[40] = {
/* -20 */ 48388, 59856, 76040, 92818, 118348,
/* -15 */ 147320, 184698, 229616, 287308, 360437,
/* -10 */ 449829, 563644, 704093, 875809, 1099582,
/* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
/* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
/* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
/* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
/* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4907_2 |
crossvul-cpp_data_bad_3116_0 | /*
* atusb.c - Driver for the ATUSB IEEE 802.15.4 dongle
*
* Written 2013 by Werner Almesberger <werner@almesberger.net>
*
* Copyright (c) 2015 - 2016 Stefan Schmidt <stefan@datenfreihafen.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2
*
* Based on at86rf230.c and spi_atusb.c.
* at86rf230.c is
* Copyright (C) 2009 Siemens AG
* Written by: Dmitry Eremin-Solenikov <dmitry.baryshkov@siemens.com>
*
* spi_atusb.c is
* Copyright (c) 2011 Richard Sharpe <realrichardsharpe@gmail.com>
* Copyright (c) 2011 Stefan Schmidt <stefan@datenfreihafen.org>
* Copyright (c) 2011 Werner Almesberger <werner@almesberger.net>
*
* USB initialization is
* Copyright (c) 2013 Alexander Aring <alex.aring@gmail.com>
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/jiffies.h>
#include <linux/usb.h>
#include <linux/skbuff.h>
#include <net/cfg802154.h>
#include <net/mac802154.h>
#include "at86rf230.h"
#include "atusb.h"
#define ATUSB_JEDEC_ATMEL 0x1f /* JEDEC manufacturer ID */
#define ATUSB_NUM_RX_URBS 4 /* allow for a bit of local latency */
#define ATUSB_ALLOC_DELAY_MS 100 /* delay after failed allocation */
#define ATUSB_TX_TIMEOUT_MS 200 /* on the air timeout */
struct atusb {
struct ieee802154_hw *hw;
struct usb_device *usb_dev;
int shutdown; /* non-zero if shutting down */
int err; /* set by first error */
/* RX variables */
struct delayed_work work; /* memory allocations */
struct usb_anchor idle_urbs; /* URBs waiting to be submitted */
struct usb_anchor rx_urbs; /* URBs waiting for reception */
/* TX variables */
struct usb_ctrlrequest tx_dr;
struct urb *tx_urb;
struct sk_buff *tx_skb;
uint8_t tx_ack_seq; /* current TX ACK sequence number */
/* Firmware variable */
unsigned char fw_ver_maj; /* Firmware major version number */
unsigned char fw_ver_min; /* Firmware minor version number */
unsigned char fw_hw_type; /* Firmware hardware type */
};
/* ----- USB commands without data ----------------------------------------- */
/* To reduce the number of error checks in the code, we record the first error
* in atusb->err and reject all subsequent requests until the error is cleared.
*/
static int atusb_control_msg(struct atusb *atusb, unsigned int pipe,
__u8 request, __u8 requesttype,
__u16 value, __u16 index,
void *data, __u16 size, int timeout)
{
struct usb_device *usb_dev = atusb->usb_dev;
int ret;
if (atusb->err)
return atusb->err;
ret = usb_control_msg(usb_dev, pipe, request, requesttype,
value, index, data, size, timeout);
if (ret < 0) {
atusb->err = ret;
dev_err(&usb_dev->dev,
"atusb_control_msg: req 0x%02x val 0x%x idx 0x%x, error %d\n",
request, value, index, ret);
}
return ret;
}
static int atusb_command(struct atusb *atusb, uint8_t cmd, uint8_t arg)
{
struct usb_device *usb_dev = atusb->usb_dev;
dev_dbg(&usb_dev->dev, "atusb_command: cmd = 0x%x\n", cmd);
return atusb_control_msg(atusb, usb_sndctrlpipe(usb_dev, 0),
cmd, ATUSB_REQ_TO_DEV, arg, 0, NULL, 0, 1000);
}
static int atusb_write_reg(struct atusb *atusb, uint8_t reg, uint8_t value)
{
struct usb_device *usb_dev = atusb->usb_dev;
dev_dbg(&usb_dev->dev, "atusb_write_reg: 0x%02x <- 0x%02x\n",
reg, value);
return atusb_control_msg(atusb, usb_sndctrlpipe(usb_dev, 0),
ATUSB_REG_WRITE, ATUSB_REQ_TO_DEV,
value, reg, NULL, 0, 1000);
}
static int atusb_read_reg(struct atusb *atusb, uint8_t reg)
{
struct usb_device *usb_dev = atusb->usb_dev;
int ret;
uint8_t value;
dev_dbg(&usb_dev->dev, "atusb: reg = 0x%x\n", reg);
ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0),
ATUSB_REG_READ, ATUSB_REQ_FROM_DEV,
0, reg, &value, 1, 1000);
return ret >= 0 ? value : ret;
}
static int atusb_write_subreg(struct atusb *atusb, uint8_t reg, uint8_t mask,
uint8_t shift, uint8_t value)
{
struct usb_device *usb_dev = atusb->usb_dev;
uint8_t orig, tmp;
int ret = 0;
dev_dbg(&usb_dev->dev, "atusb_write_subreg: 0x%02x <- 0x%02x\n",
reg, value);
orig = atusb_read_reg(atusb, reg);
/* Write the value only into that part of the register which is allowed
* by the mask. All other bits stay as before.
*/
tmp = orig & ~mask;
tmp |= (value << shift) & mask;
if (tmp != orig)
ret = atusb_write_reg(atusb, reg, tmp);
return ret;
}
static int atusb_get_and_clear_error(struct atusb *atusb)
{
int err = atusb->err;
atusb->err = 0;
return err;
}
/* ----- skb allocation ---------------------------------------------------- */
#define MAX_PSDU 127
#define MAX_RX_XFER (1 + MAX_PSDU + 2 + 1) /* PHR+PSDU+CRC+LQI */
#define SKB_ATUSB(skb) (*(struct atusb **)(skb)->cb)
static void atusb_in(struct urb *urb);
static int atusb_submit_rx_urb(struct atusb *atusb, struct urb *urb)
{
struct usb_device *usb_dev = atusb->usb_dev;
struct sk_buff *skb = urb->context;
int ret;
if (!skb) {
skb = alloc_skb(MAX_RX_XFER, GFP_KERNEL);
if (!skb) {
dev_warn_ratelimited(&usb_dev->dev,
"atusb_in: can't allocate skb\n");
return -ENOMEM;
}
skb_put(skb, MAX_RX_XFER);
SKB_ATUSB(skb) = atusb;
}
usb_fill_bulk_urb(urb, usb_dev, usb_rcvbulkpipe(usb_dev, 1),
skb->data, MAX_RX_XFER, atusb_in, skb);
usb_anchor_urb(urb, &atusb->rx_urbs);
ret = usb_submit_urb(urb, GFP_KERNEL);
if (ret) {
usb_unanchor_urb(urb);
kfree_skb(skb);
urb->context = NULL;
}
return ret;
}
static void atusb_work_urbs(struct work_struct *work)
{
struct atusb *atusb =
container_of(to_delayed_work(work), struct atusb, work);
struct usb_device *usb_dev = atusb->usb_dev;
struct urb *urb;
int ret;
if (atusb->shutdown)
return;
do {
urb = usb_get_from_anchor(&atusb->idle_urbs);
if (!urb)
return;
ret = atusb_submit_rx_urb(atusb, urb);
} while (!ret);
usb_anchor_urb(urb, &atusb->idle_urbs);
dev_warn_ratelimited(&usb_dev->dev,
"atusb_in: can't allocate/submit URB (%d)\n", ret);
schedule_delayed_work(&atusb->work,
msecs_to_jiffies(ATUSB_ALLOC_DELAY_MS) + 1);
}
/* ----- Asynchronous USB -------------------------------------------------- */
static void atusb_tx_done(struct atusb *atusb, uint8_t seq)
{
struct usb_device *usb_dev = atusb->usb_dev;
uint8_t expect = atusb->tx_ack_seq;
dev_dbg(&usb_dev->dev, "atusb_tx_done (0x%02x/0x%02x)\n", seq, expect);
if (seq == expect) {
/* TODO check for ifs handling in firmware */
ieee802154_xmit_complete(atusb->hw, atusb->tx_skb, false);
} else {
/* TODO I experience this case when atusb has a tx complete
* irq before probing, we should fix the firmware it's an
* unlikely case now that seq == expect is then true, but can
* happen and fail with a tx_skb = NULL;
*/
ieee802154_wake_queue(atusb->hw);
if (atusb->tx_skb)
dev_kfree_skb_irq(atusb->tx_skb);
}
}
static void atusb_in_good(struct urb *urb)
{
struct usb_device *usb_dev = urb->dev;
struct sk_buff *skb = urb->context;
struct atusb *atusb = SKB_ATUSB(skb);
uint8_t len, lqi;
if (!urb->actual_length) {
dev_dbg(&usb_dev->dev, "atusb_in: zero-sized URB ?\n");
return;
}
len = *skb->data;
if (urb->actual_length == 1) {
atusb_tx_done(atusb, len);
return;
}
if (len + 1 > urb->actual_length - 1) {
dev_dbg(&usb_dev->dev, "atusb_in: frame len %d+1 > URB %u-1\n",
len, urb->actual_length);
return;
}
if (!ieee802154_is_valid_psdu_len(len)) {
dev_dbg(&usb_dev->dev, "atusb_in: frame corrupted\n");
return;
}
lqi = skb->data[len + 1];
dev_dbg(&usb_dev->dev, "atusb_in: rx len %d lqi 0x%02x\n", len, lqi);
skb_pull(skb, 1); /* remove PHR */
skb_trim(skb, len); /* get payload only */
ieee802154_rx_irqsafe(atusb->hw, skb, lqi);
urb->context = NULL; /* skb is gone */
}
static void atusb_in(struct urb *urb)
{
struct usb_device *usb_dev = urb->dev;
struct sk_buff *skb = urb->context;
struct atusb *atusb = SKB_ATUSB(skb);
dev_dbg(&usb_dev->dev, "atusb_in: status %d len %d\n",
urb->status, urb->actual_length);
if (urb->status) {
if (urb->status == -ENOENT) { /* being killed */
kfree_skb(skb);
urb->context = NULL;
return;
}
dev_dbg(&usb_dev->dev, "atusb_in: URB error %d\n", urb->status);
} else {
atusb_in_good(urb);
}
usb_anchor_urb(urb, &atusb->idle_urbs);
if (!atusb->shutdown)
schedule_delayed_work(&atusb->work, 0);
}
/* ----- URB allocation/deallocation --------------------------------------- */
static void atusb_free_urbs(struct atusb *atusb)
{
struct urb *urb;
while (1) {
urb = usb_get_from_anchor(&atusb->idle_urbs);
if (!urb)
break;
kfree_skb(urb->context);
usb_free_urb(urb);
}
}
static int atusb_alloc_urbs(struct atusb *atusb, int n)
{
struct urb *urb;
while (n) {
urb = usb_alloc_urb(0, GFP_KERNEL);
if (!urb) {
atusb_free_urbs(atusb);
return -ENOMEM;
}
usb_anchor_urb(urb, &atusb->idle_urbs);
n--;
}
return 0;
}
/* ----- IEEE 802.15.4 interface operations -------------------------------- */
static void atusb_xmit_complete(struct urb *urb)
{
dev_dbg(&urb->dev->dev, "atusb_xmit urb completed");
}
static int atusb_xmit(struct ieee802154_hw *hw, struct sk_buff *skb)
{
struct atusb *atusb = hw->priv;
struct usb_device *usb_dev = atusb->usb_dev;
int ret;
dev_dbg(&usb_dev->dev, "atusb_xmit (%d)\n", skb->len);
atusb->tx_skb = skb;
atusb->tx_ack_seq++;
atusb->tx_dr.wIndex = cpu_to_le16(atusb->tx_ack_seq);
atusb->tx_dr.wLength = cpu_to_le16(skb->len);
usb_fill_control_urb(atusb->tx_urb, usb_dev,
usb_sndctrlpipe(usb_dev, 0),
(unsigned char *)&atusb->tx_dr, skb->data,
skb->len, atusb_xmit_complete, NULL);
ret = usb_submit_urb(atusb->tx_urb, GFP_ATOMIC);
dev_dbg(&usb_dev->dev, "atusb_xmit done (%d)\n", ret);
return ret;
}
static int atusb_channel(struct ieee802154_hw *hw, u8 page, u8 channel)
{
struct atusb *atusb = hw->priv;
int ret;
ret = atusb_write_subreg(atusb, SR_CHANNEL, channel);
if (ret < 0)
return ret;
msleep(1); /* @@@ ugly synchronization */
return 0;
}
static int atusb_ed(struct ieee802154_hw *hw, u8 *level)
{
BUG_ON(!level);
*level = 0xbe;
return 0;
}
static int atusb_set_hw_addr_filt(struct ieee802154_hw *hw,
struct ieee802154_hw_addr_filt *filt,
unsigned long changed)
{
struct atusb *atusb = hw->priv;
struct device *dev = &atusb->usb_dev->dev;
if (changed & IEEE802154_AFILT_SADDR_CHANGED) {
u16 addr = le16_to_cpu(filt->short_addr);
dev_vdbg(dev, "atusb_set_hw_addr_filt called for saddr\n");
atusb_write_reg(atusb, RG_SHORT_ADDR_0, addr);
atusb_write_reg(atusb, RG_SHORT_ADDR_1, addr >> 8);
}
if (changed & IEEE802154_AFILT_PANID_CHANGED) {
u16 pan = le16_to_cpu(filt->pan_id);
dev_vdbg(dev, "atusb_set_hw_addr_filt called for pan id\n");
atusb_write_reg(atusb, RG_PAN_ID_0, pan);
atusb_write_reg(atusb, RG_PAN_ID_1, pan >> 8);
}
if (changed & IEEE802154_AFILT_IEEEADDR_CHANGED) {
u8 i, addr[IEEE802154_EXTENDED_ADDR_LEN];
memcpy(addr, &filt->ieee_addr, IEEE802154_EXTENDED_ADDR_LEN);
dev_vdbg(dev, "atusb_set_hw_addr_filt called for IEEE addr\n");
for (i = 0; i < 8; i++)
atusb_write_reg(atusb, RG_IEEE_ADDR_0 + i, addr[i]);
}
if (changed & IEEE802154_AFILT_PANC_CHANGED) {
dev_vdbg(dev,
"atusb_set_hw_addr_filt called for panc change\n");
if (filt->pan_coord)
atusb_write_subreg(atusb, SR_AACK_I_AM_COORD, 1);
else
atusb_write_subreg(atusb, SR_AACK_I_AM_COORD, 0);
}
return atusb_get_and_clear_error(atusb);
}
static int atusb_start(struct ieee802154_hw *hw)
{
struct atusb *atusb = hw->priv;
struct usb_device *usb_dev = atusb->usb_dev;
int ret;
dev_dbg(&usb_dev->dev, "atusb_start\n");
schedule_delayed_work(&atusb->work, 0);
atusb_command(atusb, ATUSB_RX_MODE, 1);
ret = atusb_get_and_clear_error(atusb);
if (ret < 0)
usb_kill_anchored_urbs(&atusb->idle_urbs);
return ret;
}
static void atusb_stop(struct ieee802154_hw *hw)
{
struct atusb *atusb = hw->priv;
struct usb_device *usb_dev = atusb->usb_dev;
dev_dbg(&usb_dev->dev, "atusb_stop\n");
usb_kill_anchored_urbs(&atusb->idle_urbs);
atusb_command(atusb, ATUSB_RX_MODE, 0);
atusb_get_and_clear_error(atusb);
}
#define ATUSB_MAX_TX_POWERS 0xF
static const s32 atusb_powers[ATUSB_MAX_TX_POWERS + 1] = {
300, 280, 230, 180, 130, 70, 0, -100, -200, -300, -400, -500, -700,
-900, -1200, -1700,
};
static int
atusb_set_txpower(struct ieee802154_hw *hw, s32 mbm)
{
struct atusb *atusb = hw->priv;
u32 i;
for (i = 0; i < hw->phy->supported.tx_powers_size; i++) {
if (hw->phy->supported.tx_powers[i] == mbm)
return atusb_write_subreg(atusb, SR_TX_PWR_23X, i);
}
return -EINVAL;
}
#define ATUSB_MAX_ED_LEVELS 0xF
static const s32 atusb_ed_levels[ATUSB_MAX_ED_LEVELS + 1] = {
-9100, -8900, -8700, -8500, -8300, -8100, -7900, -7700, -7500, -7300,
-7100, -6900, -6700, -6500, -6300, -6100,
};
static int
atusb_set_cca_mode(struct ieee802154_hw *hw, const struct wpan_phy_cca *cca)
{
struct atusb *atusb = hw->priv;
u8 val;
/* mapping 802.15.4 to driver spec */
switch (cca->mode) {
case NL802154_CCA_ENERGY:
val = 1;
break;
case NL802154_CCA_CARRIER:
val = 2;
break;
case NL802154_CCA_ENERGY_CARRIER:
switch (cca->opt) {
case NL802154_CCA_OPT_ENERGY_CARRIER_AND:
val = 3;
break;
case NL802154_CCA_OPT_ENERGY_CARRIER_OR:
val = 0;
break;
default:
return -EINVAL;
}
break;
default:
return -EINVAL;
}
return atusb_write_subreg(atusb, SR_CCA_MODE, val);
}
static int
atusb_set_cca_ed_level(struct ieee802154_hw *hw, s32 mbm)
{
struct atusb *atusb = hw->priv;
u32 i;
for (i = 0; i < hw->phy->supported.cca_ed_levels_size; i++) {
if (hw->phy->supported.cca_ed_levels[i] == mbm)
return atusb_write_subreg(atusb, SR_CCA_ED_THRES, i);
}
return -EINVAL;
}
static int
atusb_set_csma_params(struct ieee802154_hw *hw, u8 min_be, u8 max_be, u8 retries)
{
struct atusb *atusb = hw->priv;
int ret;
ret = atusb_write_subreg(atusb, SR_MIN_BE, min_be);
if (ret)
return ret;
ret = atusb_write_subreg(atusb, SR_MAX_BE, max_be);
if (ret)
return ret;
return atusb_write_subreg(atusb, SR_MAX_CSMA_RETRIES, retries);
}
static int
atusb_set_frame_retries(struct ieee802154_hw *hw, s8 retries)
{
struct atusb *atusb = hw->priv;
struct device *dev = &atusb->usb_dev->dev;
if (atusb->fw_ver_maj == 0 && atusb->fw_ver_min < 3) {
dev_info(dev, "Automatic frame retransmission is only available from "
"firmware version 0.3. Please update if you want this feature.");
return -EINVAL;
}
return atusb_write_subreg(atusb, SR_MAX_FRAME_RETRIES, retries);
}
static int
atusb_set_promiscuous_mode(struct ieee802154_hw *hw, const bool on)
{
struct atusb *atusb = hw->priv;
int ret;
if (on) {
ret = atusb_write_subreg(atusb, SR_AACK_DIS_ACK, 1);
if (ret < 0)
return ret;
ret = atusb_write_subreg(atusb, SR_AACK_PROM_MODE, 1);
if (ret < 0)
return ret;
} else {
ret = atusb_write_subreg(atusb, SR_AACK_PROM_MODE, 0);
if (ret < 0)
return ret;
ret = atusb_write_subreg(atusb, SR_AACK_DIS_ACK, 0);
if (ret < 0)
return ret;
}
return 0;
}
static const struct ieee802154_ops atusb_ops = {
.owner = THIS_MODULE,
.xmit_async = atusb_xmit,
.ed = atusb_ed,
.set_channel = atusb_channel,
.start = atusb_start,
.stop = atusb_stop,
.set_hw_addr_filt = atusb_set_hw_addr_filt,
.set_txpower = atusb_set_txpower,
.set_cca_mode = atusb_set_cca_mode,
.set_cca_ed_level = atusb_set_cca_ed_level,
.set_csma_params = atusb_set_csma_params,
.set_frame_retries = atusb_set_frame_retries,
.set_promiscuous_mode = atusb_set_promiscuous_mode,
};
/* ----- Firmware and chip version information ----------------------------- */
static int atusb_get_and_show_revision(struct atusb *atusb)
{
struct usb_device *usb_dev = atusb->usb_dev;
unsigned char buffer[3];
int ret;
/* Get a couple of the ATMega Firmware values */
ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0),
ATUSB_ID, ATUSB_REQ_FROM_DEV, 0, 0,
buffer, 3, 1000);
if (ret >= 0) {
atusb->fw_ver_maj = buffer[0];
atusb->fw_ver_min = buffer[1];
atusb->fw_hw_type = buffer[2];
dev_info(&usb_dev->dev,
"Firmware: major: %u, minor: %u, hardware type: %u\n",
atusb->fw_ver_maj, atusb->fw_ver_min, atusb->fw_hw_type);
}
if (atusb->fw_ver_maj == 0 && atusb->fw_ver_min < 2) {
dev_info(&usb_dev->dev,
"Firmware version (%u.%u) predates our first public release.",
atusb->fw_ver_maj, atusb->fw_ver_min);
dev_info(&usb_dev->dev, "Please update to version 0.2 or newer");
}
return ret;
}
static int atusb_get_and_show_build(struct atusb *atusb)
{
struct usb_device *usb_dev = atusb->usb_dev;
char build[ATUSB_BUILD_SIZE + 1];
int ret;
ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0),
ATUSB_BUILD, ATUSB_REQ_FROM_DEV, 0, 0,
build, ATUSB_BUILD_SIZE, 1000);
if (ret >= 0) {
build[ret] = 0;
dev_info(&usb_dev->dev, "Firmware: build %s\n", build);
}
return ret;
}
static int atusb_get_and_show_chip(struct atusb *atusb)
{
struct usb_device *usb_dev = atusb->usb_dev;
uint8_t man_id_0, man_id_1, part_num, version_num;
const char *chip;
man_id_0 = atusb_read_reg(atusb, RG_MAN_ID_0);
man_id_1 = atusb_read_reg(atusb, RG_MAN_ID_1);
part_num = atusb_read_reg(atusb, RG_PART_NUM);
version_num = atusb_read_reg(atusb, RG_VERSION_NUM);
if (atusb->err)
return atusb->err;
if ((man_id_1 << 8 | man_id_0) != ATUSB_JEDEC_ATMEL) {
dev_err(&usb_dev->dev,
"non-Atmel transceiver xxxx%02x%02x\n",
man_id_1, man_id_0);
goto fail;
}
switch (part_num) {
case 2:
chip = "AT86RF230";
break;
case 3:
chip = "AT86RF231";
break;
default:
dev_err(&usb_dev->dev,
"unexpected transceiver, part 0x%02x version 0x%02x\n",
part_num, version_num);
goto fail;
}
dev_info(&usb_dev->dev, "ATUSB: %s version %d\n", chip, version_num);
return 0;
fail:
atusb->err = -ENODEV;
return -ENODEV;
}
static int atusb_set_extended_addr(struct atusb *atusb)
{
struct usb_device *usb_dev = atusb->usb_dev;
unsigned char buffer[IEEE802154_EXTENDED_ADDR_LEN];
__le64 extended_addr;
u64 addr;
int ret;
/* Firmware versions before 0.3 do not support the EUI64_READ command.
* Just use a random address and be done */
if (atusb->fw_ver_maj == 0 && atusb->fw_ver_min < 3) {
ieee802154_random_extended_addr(&atusb->hw->phy->perm_extended_addr);
return 0;
}
/* Firmware is new enough so we fetch the address from EEPROM */
ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0),
ATUSB_EUI64_READ, ATUSB_REQ_FROM_DEV, 0, 0,
buffer, IEEE802154_EXTENDED_ADDR_LEN, 1000);
if (ret < 0)
dev_err(&usb_dev->dev, "failed to fetch extended address\n");
memcpy(&extended_addr, buffer, IEEE802154_EXTENDED_ADDR_LEN);
/* Check if read address is not empty and the unicast bit is set correctly */
if (!ieee802154_is_valid_extended_unicast_addr(extended_addr)) {
dev_info(&usb_dev->dev, "no permanent extended address found, random address set\n");
ieee802154_random_extended_addr(&atusb->hw->phy->perm_extended_addr);
} else {
atusb->hw->phy->perm_extended_addr = extended_addr;
addr = swab64((__force u64)atusb->hw->phy->perm_extended_addr);
dev_info(&usb_dev->dev, "Read permanent extended address %8phC from device\n",
&addr);
}
return ret;
}
/* ----- Setup ------------------------------------------------------------- */
static int atusb_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
struct usb_device *usb_dev = interface_to_usbdev(interface);
struct ieee802154_hw *hw;
struct atusb *atusb = NULL;
int ret = -ENOMEM;
hw = ieee802154_alloc_hw(sizeof(struct atusb), &atusb_ops);
if (!hw)
return -ENOMEM;
atusb = hw->priv;
atusb->hw = hw;
atusb->usb_dev = usb_get_dev(usb_dev);
usb_set_intfdata(interface, atusb);
atusb->shutdown = 0;
atusb->err = 0;
INIT_DELAYED_WORK(&atusb->work, atusb_work_urbs);
init_usb_anchor(&atusb->idle_urbs);
init_usb_anchor(&atusb->rx_urbs);
if (atusb_alloc_urbs(atusb, ATUSB_NUM_RX_URBS))
goto fail;
atusb->tx_dr.bRequestType = ATUSB_REQ_TO_DEV;
atusb->tx_dr.bRequest = ATUSB_TX;
atusb->tx_dr.wValue = cpu_to_le16(0);
atusb->tx_urb = usb_alloc_urb(0, GFP_ATOMIC);
if (!atusb->tx_urb)
goto fail;
hw->parent = &usb_dev->dev;
hw->flags = IEEE802154_HW_TX_OMIT_CKSUM | IEEE802154_HW_AFILT |
IEEE802154_HW_PROMISCUOUS | IEEE802154_HW_CSMA_PARAMS |
IEEE802154_HW_FRAME_RETRIES;
hw->phy->flags = WPAN_PHY_FLAG_TXPOWER | WPAN_PHY_FLAG_CCA_ED_LEVEL |
WPAN_PHY_FLAG_CCA_MODE;
hw->phy->supported.cca_modes = BIT(NL802154_CCA_ENERGY) |
BIT(NL802154_CCA_CARRIER) | BIT(NL802154_CCA_ENERGY_CARRIER);
hw->phy->supported.cca_opts = BIT(NL802154_CCA_OPT_ENERGY_CARRIER_AND) |
BIT(NL802154_CCA_OPT_ENERGY_CARRIER_OR);
hw->phy->supported.cca_ed_levels = atusb_ed_levels;
hw->phy->supported.cca_ed_levels_size = ARRAY_SIZE(atusb_ed_levels);
hw->phy->cca.mode = NL802154_CCA_ENERGY;
hw->phy->current_page = 0;
hw->phy->current_channel = 11; /* reset default */
hw->phy->supported.channels[0] = 0x7FFF800;
hw->phy->supported.tx_powers = atusb_powers;
hw->phy->supported.tx_powers_size = ARRAY_SIZE(atusb_powers);
hw->phy->transmit_power = hw->phy->supported.tx_powers[0];
hw->phy->cca_ed_level = hw->phy->supported.cca_ed_levels[7];
atusb_command(atusb, ATUSB_RF_RESET, 0);
atusb_get_and_show_chip(atusb);
atusb_get_and_show_revision(atusb);
atusb_get_and_show_build(atusb);
atusb_set_extended_addr(atusb);
ret = atusb_get_and_clear_error(atusb);
if (ret) {
dev_err(&atusb->usb_dev->dev,
"%s: initialization failed, error = %d\n",
__func__, ret);
goto fail;
}
ret = ieee802154_register_hw(hw);
if (ret)
goto fail;
/* If we just powered on, we're now in P_ON and need to enter TRX_OFF
* explicitly. Any resets after that will send us straight to TRX_OFF,
* making the command below redundant.
*/
atusb_write_reg(atusb, RG_TRX_STATE, STATE_FORCE_TRX_OFF);
msleep(1); /* reset => TRX_OFF, tTR13 = 37 us */
#if 0
/* Calculating the maximum time available to empty the frame buffer
* on reception:
*
* According to [1], the inter-frame gap is
* R * 20 * 16 us + 128 us
* where R is a random number from 0 to 7. Furthermore, we have 20 bit
* times (80 us at 250 kbps) of SHR of the next frame before the
* transceiver begins storing data in the frame buffer.
*
* This yields a minimum time of 208 us between the last data of a
* frame and the first data of the next frame. This time is further
* reduced by interrupt latency in the atusb firmware.
*
* atusb currently needs about 500 us to retrieve a maximum-sized
* frame. We therefore have to allow reception of a new frame to begin
* while we retrieve the previous frame.
*
* [1] "JN-AN-1035 Calculating data rates in an IEEE 802.15.4-based
* network", Jennic 2006.
* http://www.jennic.com/download_file.php?supportFile=JN-AN-1035%20Calculating%20802-15-4%20Data%20Rates-1v0.pdf
*/
atusb_write_subreg(atusb, SR_RX_SAFE_MODE, 1);
#endif
atusb_write_reg(atusb, RG_IRQ_MASK, 0xff);
ret = atusb_get_and_clear_error(atusb);
if (!ret)
return 0;
dev_err(&atusb->usb_dev->dev,
"%s: setup failed, error = %d\n",
__func__, ret);
ieee802154_unregister_hw(hw);
fail:
atusb_free_urbs(atusb);
usb_kill_urb(atusb->tx_urb);
usb_free_urb(atusb->tx_urb);
usb_put_dev(usb_dev);
ieee802154_free_hw(hw);
return ret;
}
static void atusb_disconnect(struct usb_interface *interface)
{
struct atusb *atusb = usb_get_intfdata(interface);
dev_dbg(&atusb->usb_dev->dev, "atusb_disconnect\n");
atusb->shutdown = 1;
cancel_delayed_work_sync(&atusb->work);
usb_kill_anchored_urbs(&atusb->rx_urbs);
atusb_free_urbs(atusb);
usb_kill_urb(atusb->tx_urb);
usb_free_urb(atusb->tx_urb);
ieee802154_unregister_hw(atusb->hw);
ieee802154_free_hw(atusb->hw);
usb_set_intfdata(interface, NULL);
usb_put_dev(atusb->usb_dev);
pr_debug("atusb_disconnect done\n");
}
/* The devices we work with */
static const struct usb_device_id atusb_device_table[] = {
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE |
USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = ATUSB_VENDOR_ID,
.idProduct = ATUSB_PRODUCT_ID,
.bInterfaceClass = USB_CLASS_VENDOR_SPEC
},
/* end with null element */
{}
};
MODULE_DEVICE_TABLE(usb, atusb_device_table);
static struct usb_driver atusb_driver = {
.name = "atusb",
.probe = atusb_probe,
.disconnect = atusb_disconnect,
.id_table = atusb_device_table,
};
module_usb_driver(atusb_driver);
MODULE_AUTHOR("Alexander Aring <alex.aring@gmail.com>");
MODULE_AUTHOR("Richard Sharpe <realrichardsharpe@gmail.com>");
MODULE_AUTHOR("Stefan Schmidt <stefan@datenfreihafen.org>");
MODULE_AUTHOR("Werner Almesberger <werner@almesberger.net>");
MODULE_DESCRIPTION("ATUSB IEEE 802.15.4 Driver");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3116_0 |
crossvul-cpp_data_bad_896_1 | /*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_MQTT
#include <string.h>
#include "mg_internal.h"
#include "mg_mqtt.h"
static uint16_t getu16(const char *p) {
const uint8_t *up = (const uint8_t *) p;
return (up[0] << 8) + up[1];
}
static const char *scanto(const char *p, struct mg_str *s) {
s->len = getu16(p);
s->p = p + 2;
return s->p + s->len;
}
MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) {
uint8_t header;
size_t len = 0, len_len = 0;
const char *p, *end;
unsigned char lc = 0;
int cmd;
if (io->len < 2) return MG_MQTT_ERROR_INCOMPLETE_MSG;
header = io->buf[0];
cmd = header >> 4;
/* decode mqtt variable length */
len = len_len = 0;
p = io->buf + 1;
while ((size_t)(p - io->buf) < io->len) {
lc = *((const unsigned char *) p++);
len += (lc & 0x7f) << 7 * len_len;
len_len++;
if (!(lc & 0x80)) break;
if (len_len > 4) return MG_MQTT_ERROR_MALFORMED_MSG;
}
end = p + len;
if (lc & 0x80 || len > (io->len - (p - io->buf))) {
return MG_MQTT_ERROR_INCOMPLETE_MSG;
}
mm->cmd = cmd;
mm->qos = MG_MQTT_GET_QOS(header);
switch (cmd) {
case MG_MQTT_CMD_CONNECT: {
p = scanto(p, &mm->protocol_name);
if (p > end - 4) return MG_MQTT_ERROR_MALFORMED_MSG;
mm->protocol_version = *(uint8_t *) p++;
mm->connect_flags = *(uint8_t *) p++;
mm->keep_alive_timer = getu16(p);
p += 2;
if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
p = scanto(p, &mm->client_id);
if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
if (mm->connect_flags & MG_MQTT_HAS_WILL) {
if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
p = scanto(p, &mm->will_topic);
}
if (mm->connect_flags & MG_MQTT_HAS_WILL) {
if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
p = scanto(p, &mm->will_message);
}
if (mm->connect_flags & MG_MQTT_HAS_USER_NAME) {
if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
p = scanto(p, &mm->user_name);
}
if (mm->connect_flags & MG_MQTT_HAS_PASSWORD) {
if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
p = scanto(p, &mm->password);
}
if (p != end) return MG_MQTT_ERROR_MALFORMED_MSG;
LOG(LL_DEBUG,
("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] "
"will_msg [%.*s] user_name [%.*s] password [%.*s]",
(int) len, (int) mm->connect_flags, (int) mm->keep_alive_timer,
(int) mm->protocol_name.len, mm->protocol_name.p,
(int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len,
mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p,
(int) mm->user_name.len, mm->user_name.p, (int) mm->password.len,
mm->password.p));
break;
}
case MG_MQTT_CMD_CONNACK:
if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
mm->connack_ret_code = p[1];
break;
case MG_MQTT_CMD_PUBACK:
case MG_MQTT_CMD_PUBREC:
case MG_MQTT_CMD_PUBREL:
case MG_MQTT_CMD_PUBCOMP:
case MG_MQTT_CMD_SUBACK:
mm->message_id = getu16(p);
break;
case MG_MQTT_CMD_PUBLISH: {
p = scanto(p, &mm->topic);
if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
if (mm->qos > 0) {
if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
mm->message_id = getu16(p);
p += 2;
}
mm->payload.p = p;
mm->payload.len = end - p;
break;
}
case MG_MQTT_CMD_SUBSCRIBE:
if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
mm->message_id = getu16(p);
p += 2;
/*
* topic expressions are left in the payload and can be parsed with
* `mg_mqtt_next_subscribe_topic`
*/
mm->payload.p = p;
mm->payload.len = end - p;
break;
default:
/* Unhandled command */
break;
}
mm->len = end - io->buf;
return mm->len;
}
static void mqtt_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct mbuf *io = &nc->recv_mbuf;
struct mg_mqtt_message mm;
memset(&mm, 0, sizeof(mm));
nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
switch (ev) {
case MG_EV_ACCEPT:
if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc);
break;
case MG_EV_RECV: {
/* There can be multiple messages in the buffer, process them all. */
while (1) {
int len = parse_mqtt(io, &mm);
if (len < 0) {
if (len == MG_MQTT_ERROR_MALFORMED_MSG) {
/* Protocol error. */
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
} else if (len == MG_MQTT_ERROR_INCOMPLETE_MSG) {
/* Not fully buffered, let's check if we have a chance to get more
* data later */
if (nc->recv_mbuf_limit > 0 &&
nc->recv_mbuf.len >= nc->recv_mbuf_limit) {
LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit "
"%lu bytes, and not drained, closing",
nc, (unsigned long) nc->recv_mbuf.len,
(unsigned long) nc->recv_mbuf_limit));
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
} else {
/* Should never be here */
LOG(LL_ERROR, ("%p invalid len: %d, closing", nc, len));
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
break;
}
nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm MG_UD_ARG(user_data));
mbuf_remove(io, len);
}
break;
}
case MG_EV_POLL: {
struct mg_mqtt_proto_data *pd =
(struct mg_mqtt_proto_data *) nc->proto_data;
double now = mg_time();
if (pd->keep_alive > 0 && pd->last_control_time > 0 &&
(now - pd->last_control_time) > pd->keep_alive) {
LOG(LL_DEBUG, ("Send PINGREQ"));
mg_mqtt_ping(nc);
}
break;
}
}
}
static void mg_mqtt_proto_data_destructor(void *proto_data) {
MG_FREE(proto_data);
}
static struct mg_str mg_mqtt_next_topic_component(struct mg_str *topic) {
struct mg_str res = *topic;
const char *c = mg_strchr(*topic, '/');
if (c != NULL) {
res.len = (c - topic->p);
topic->len -= (res.len + 1);
topic->p += (res.len + 1);
} else {
topic->len = 0;
}
return res;
}
/* Refernce: https://mosquitto.org/man/mqtt-7.html */
int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic) {
struct mg_str ec, tc;
if (exp.len == 0) return 0;
while (1) {
ec = mg_mqtt_next_topic_component(&exp);
tc = mg_mqtt_next_topic_component(&topic);
if (ec.len == 0) {
if (tc.len != 0) return 0;
if (exp.len == 0) break;
continue;
}
if (mg_vcmp(&ec, "+") == 0) {
if (tc.len == 0 && topic.len == 0) return 0;
continue;
}
if (mg_vcmp(&ec, "#") == 0) {
/* Must be the last component in the expression or it's invalid. */
return (exp.len == 0);
}
if (mg_strcmp(ec, tc) != 0) {
return 0;
}
}
return (tc.len == 0 && topic.len == 0);
}
int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic) {
return mg_mqtt_match_topic_expression(mg_mk_str(exp), topic);
}
void mg_set_protocol_mqtt(struct mg_connection *nc) {
nc->proto_handler = mqtt_handler;
nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data));
nc->proto_data_destructor = mg_mqtt_proto_data_destructor;
}
static void mg_send_mqtt_header(struct mg_connection *nc, uint8_t cmd,
uint8_t flags, size_t len) {
struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
uint8_t buf[1 + sizeof(size_t)];
uint8_t *vlen = &buf[1];
buf[0] = (cmd << 4) | flags;
/* mqtt variable length encoding */
do {
*vlen = len % 0x80;
len /= 0x80;
if (len > 0) *vlen |= 0x80;
vlen++;
} while (len > 0);
mg_send(nc, buf, vlen - buf);
pd->last_control_time = mg_time();
}
void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) {
static struct mg_send_mqtt_handshake_opts opts;
mg_send_mqtt_handshake_opt(nc, client_id, opts);
}
void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
struct mg_send_mqtt_handshake_opts opts) {
struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
uint16_t id_len = 0, wt_len = 0, wm_len = 0, user_len = 0, pw_len = 0;
uint16_t netbytes;
size_t total_len;
if (client_id != NULL) {
id_len = strlen(client_id);
}
total_len = 7 + 1 + 2 + 2 + id_len;
if (opts.user_name != NULL) {
opts.flags |= MG_MQTT_HAS_USER_NAME;
}
if (opts.password != NULL) {
opts.flags |= MG_MQTT_HAS_PASSWORD;
}
if (opts.will_topic != NULL && opts.will_message != NULL) {
wt_len = strlen(opts.will_topic);
wm_len = strlen(opts.will_message);
opts.flags |= MG_MQTT_HAS_WILL;
}
if (opts.keep_alive == 0) {
opts.keep_alive = 60;
}
if (opts.flags & MG_MQTT_HAS_WILL) {
total_len += 2 + wt_len + 2 + wm_len;
}
if (opts.flags & MG_MQTT_HAS_USER_NAME) {
user_len = strlen(opts.user_name);
total_len += 2 + user_len;
}
if (opts.flags & MG_MQTT_HAS_PASSWORD) {
pw_len = strlen(opts.password);
total_len += 2 + pw_len;
}
mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNECT, 0, total_len);
mg_send(nc, "\00\04MQTT\04", 7);
mg_send(nc, &opts.flags, 1);
netbytes = htons(opts.keep_alive);
mg_send(nc, &netbytes, 2);
netbytes = htons(id_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, client_id, id_len);
if (opts.flags & MG_MQTT_HAS_WILL) {
netbytes = htons(wt_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, opts.will_topic, wt_len);
netbytes = htons(wm_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, opts.will_message, wm_len);
}
if (opts.flags & MG_MQTT_HAS_USER_NAME) {
netbytes = htons(user_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, opts.user_name, user_len);
}
if (opts.flags & MG_MQTT_HAS_PASSWORD) {
netbytes = htons(pw_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, opts.password, pw_len);
}
if (pd != NULL) {
pd->keep_alive = opts.keep_alive;
}
}
void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
uint16_t message_id, int flags, const void *data,
size_t len) {
uint16_t netbytes;
uint16_t topic_len = strlen(topic);
size_t total_len = 2 + topic_len + len;
if (MG_MQTT_GET_QOS(flags) > 0) {
total_len += 2;
}
mg_send_mqtt_header(nc, MG_MQTT_CMD_PUBLISH, flags, total_len);
netbytes = htons(topic_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, topic, topic_len);
if (MG_MQTT_GET_QOS(flags) > 0) {
netbytes = htons(message_id);
mg_send(nc, &netbytes, 2);
}
mg_send(nc, data, len);
}
void mg_mqtt_subscribe(struct mg_connection *nc,
const struct mg_mqtt_topic_expression *topics,
size_t topics_len, uint16_t message_id) {
uint16_t netbytes;
size_t i;
uint16_t topic_len;
size_t total_len = 2;
for (i = 0; i < topics_len; i++) {
total_len += 2 + strlen(topics[i].topic) + 1;
}
mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1), total_len);
netbytes = htons(message_id);
mg_send(nc, (char *) &netbytes, 2);
for (i = 0; i < topics_len; i++) {
topic_len = strlen(topics[i].topic);
netbytes = htons(topic_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, topics[i].topic, topic_len);
mg_send(nc, &topics[i].qos, 1);
}
}
int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
struct mg_str *topic, uint8_t *qos, int pos) {
unsigned char *buf = (unsigned char *) msg->payload.p + pos;
int new_pos;
if ((size_t) pos >= msg->payload.len) return -1;
topic->len = buf[0] << 8 | buf[1];
topic->p = (char *) buf + 2;
new_pos = pos + 2 + topic->len + 1;
if ((size_t) new_pos > msg->payload.len) return -1;
*qos = buf[2 + topic->len];
return new_pos;
}
void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
size_t topics_len, uint16_t message_id) {
uint16_t netbytes;
size_t i;
uint16_t topic_len;
size_t total_len = 2;
for (i = 0; i < topics_len; i++) {
total_len += 2 + strlen(topics[i]);
}
mg_send_mqtt_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1), total_len);
netbytes = htons(message_id);
mg_send(nc, (char *) &netbytes, 2);
for (i = 0; i < topics_len; i++) {
topic_len = strlen(topics[i]);
netbytes = htons(topic_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, topics[i], topic_len);
}
}
void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) {
uint8_t unused = 0;
mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNACK, 0, 2);
mg_send(nc, &unused, 1);
mg_send(nc, &return_code, 1);
}
/*
* Sends a command which contains only a `message_id` and a QoS level of 1.
*
* Helper function.
*/
static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd,
uint16_t message_id) {
uint16_t netbytes;
uint8_t flags = (cmd == MG_MQTT_CMD_PUBREL ? 2 : 0);
mg_send_mqtt_header(nc, cmd, flags, 2 /* len */);
netbytes = htons(message_id);
mg_send(nc, &netbytes, 2);
}
void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id);
}
void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id);
}
void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id);
}
void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id);
}
void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
uint16_t message_id) {
size_t i;
uint16_t netbytes;
mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len);
netbytes = htons(message_id);
mg_send(nc, &netbytes, 2);
for (i = 0; i < qoss_len; i++) {
mg_send(nc, &qoss[i], 1);
}
}
void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id);
}
void mg_mqtt_ping(struct mg_connection *nc) {
mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0);
}
void mg_mqtt_pong(struct mg_connection *nc) {
mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0);
}
void mg_mqtt_disconnect(struct mg_connection *nc) {
mg_send_mqtt_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0);
}
#endif /* MG_ENABLE_MQTT */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_896_1 |
crossvul-cpp_data_good_5355_0 | /*
* Copyright (c) 2010 Broadcom Corporation
*
* Permission to use, copy, modify, and/or 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.
*/
/* Toplevel file. Relies on dhd_linux.c to send commands to the dongle. */
#include <linux/kernel.h>
#include <linux/etherdevice.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <net/cfg80211.h>
#include <net/netlink.h>
#include <brcmu_utils.h>
#include <defs.h>
#include <brcmu_wifi.h>
#include "core.h"
#include "debug.h"
#include "tracepoint.h"
#include "fwil_types.h"
#include "p2p.h"
#include "btcoex.h"
#include "cfg80211.h"
#include "feature.h"
#include "fwil.h"
#include "proto.h"
#include "vendor.h"
#include "bus.h"
#include "common.h"
#define BRCMF_SCAN_IE_LEN_MAX 2048
#define BRCMF_PNO_VERSION 2
#define BRCMF_PNO_TIME 30
#define BRCMF_PNO_REPEAT 4
#define BRCMF_PNO_FREQ_EXPO_MAX 3
#define BRCMF_PNO_MAX_PFN_COUNT 16
#define BRCMF_PNO_ENABLE_ADAPTSCAN_BIT 6
#define BRCMF_PNO_HIDDEN_BIT 2
#define BRCMF_PNO_WPA_AUTH_ANY 0xFFFFFFFF
#define BRCMF_PNO_SCAN_COMPLETE 1
#define BRCMF_PNO_SCAN_INCOMPLETE 0
#define WPA_OUI "\x00\x50\xF2" /* WPA OUI */
#define WPA_OUI_TYPE 1
#define RSN_OUI "\x00\x0F\xAC" /* RSN OUI */
#define WME_OUI_TYPE 2
#define WPS_OUI_TYPE 4
#define VS_IE_FIXED_HDR_LEN 6
#define WPA_IE_VERSION_LEN 2
#define WPA_IE_MIN_OUI_LEN 4
#define WPA_IE_SUITE_COUNT_LEN 2
#define WPA_CIPHER_NONE 0 /* None */
#define WPA_CIPHER_WEP_40 1 /* WEP (40-bit) */
#define WPA_CIPHER_TKIP 2 /* TKIP: default for WPA */
#define WPA_CIPHER_AES_CCM 4 /* AES (CCM) */
#define WPA_CIPHER_WEP_104 5 /* WEP (104-bit) */
#define RSN_AKM_NONE 0 /* None (IBSS) */
#define RSN_AKM_UNSPECIFIED 1 /* Over 802.1x */
#define RSN_AKM_PSK 2 /* Pre-shared Key */
#define RSN_AKM_SHA256_1X 5 /* SHA256, 802.1X */
#define RSN_AKM_SHA256_PSK 6 /* SHA256, Pre-shared Key */
#define RSN_CAP_LEN 2 /* Length of RSN capabilities */
#define RSN_CAP_PTK_REPLAY_CNTR_MASK (BIT(2) | BIT(3))
#define RSN_CAP_MFPR_MASK BIT(6)
#define RSN_CAP_MFPC_MASK BIT(7)
#define RSN_PMKID_COUNT_LEN 2
#define VNDR_IE_CMD_LEN 4 /* length of the set command
* string :"add", "del" (+ NUL)
*/
#define VNDR_IE_COUNT_OFFSET 4
#define VNDR_IE_PKTFLAG_OFFSET 8
#define VNDR_IE_VSIE_OFFSET 12
#define VNDR_IE_HDR_SIZE 12
#define VNDR_IE_PARSE_LIMIT 5
#define DOT11_MGMT_HDR_LEN 24 /* d11 management header len */
#define DOT11_BCN_PRB_FIXED_LEN 12 /* beacon/probe fixed length */
#define BRCMF_SCAN_JOIN_ACTIVE_DWELL_TIME_MS 320
#define BRCMF_SCAN_JOIN_PASSIVE_DWELL_TIME_MS 400
#define BRCMF_SCAN_JOIN_PROBE_INTERVAL_MS 20
#define BRCMF_SCAN_CHANNEL_TIME 40
#define BRCMF_SCAN_UNASSOC_TIME 40
#define BRCMF_SCAN_PASSIVE_TIME 120
#define BRCMF_ND_INFO_TIMEOUT msecs_to_jiffies(2000)
#define BRCMF_ASSOC_PARAMS_FIXED_SIZE \
(sizeof(struct brcmf_assoc_params_le) - sizeof(u16))
static bool check_vif_up(struct brcmf_cfg80211_vif *vif)
{
if (!test_bit(BRCMF_VIF_STATUS_READY, &vif->sme_state)) {
brcmf_dbg(INFO, "device is not ready : status (%lu)\n",
vif->sme_state);
return false;
}
return true;
}
#define RATE_TO_BASE100KBPS(rate) (((rate) * 10) / 2)
#define RATETAB_ENT(_rateid, _flags) \
{ \
.bitrate = RATE_TO_BASE100KBPS(_rateid), \
.hw_value = (_rateid), \
.flags = (_flags), \
}
static struct ieee80211_rate __wl_rates[] = {
RATETAB_ENT(BRCM_RATE_1M, 0),
RATETAB_ENT(BRCM_RATE_2M, IEEE80211_RATE_SHORT_PREAMBLE),
RATETAB_ENT(BRCM_RATE_5M5, IEEE80211_RATE_SHORT_PREAMBLE),
RATETAB_ENT(BRCM_RATE_11M, IEEE80211_RATE_SHORT_PREAMBLE),
RATETAB_ENT(BRCM_RATE_6M, 0),
RATETAB_ENT(BRCM_RATE_9M, 0),
RATETAB_ENT(BRCM_RATE_12M, 0),
RATETAB_ENT(BRCM_RATE_18M, 0),
RATETAB_ENT(BRCM_RATE_24M, 0),
RATETAB_ENT(BRCM_RATE_36M, 0),
RATETAB_ENT(BRCM_RATE_48M, 0),
RATETAB_ENT(BRCM_RATE_54M, 0),
};
#define wl_g_rates (__wl_rates + 0)
#define wl_g_rates_size ARRAY_SIZE(__wl_rates)
#define wl_a_rates (__wl_rates + 4)
#define wl_a_rates_size (wl_g_rates_size - 4)
#define CHAN2G(_channel, _freq) { \
.band = NL80211_BAND_2GHZ, \
.center_freq = (_freq), \
.hw_value = (_channel), \
.flags = IEEE80211_CHAN_DISABLED, \
.max_antenna_gain = 0, \
.max_power = 30, \
}
#define CHAN5G(_channel) { \
.band = NL80211_BAND_5GHZ, \
.center_freq = 5000 + (5 * (_channel)), \
.hw_value = (_channel), \
.flags = IEEE80211_CHAN_DISABLED, \
.max_antenna_gain = 0, \
.max_power = 30, \
}
static struct ieee80211_channel __wl_2ghz_channels[] = {
CHAN2G(1, 2412), CHAN2G(2, 2417), CHAN2G(3, 2422), CHAN2G(4, 2427),
CHAN2G(5, 2432), CHAN2G(6, 2437), CHAN2G(7, 2442), CHAN2G(8, 2447),
CHAN2G(9, 2452), CHAN2G(10, 2457), CHAN2G(11, 2462), CHAN2G(12, 2467),
CHAN2G(13, 2472), CHAN2G(14, 2484)
};
static struct ieee80211_channel __wl_5ghz_channels[] = {
CHAN5G(34), CHAN5G(36), CHAN5G(38), CHAN5G(40), CHAN5G(42),
CHAN5G(44), CHAN5G(46), CHAN5G(48), CHAN5G(52), CHAN5G(56),
CHAN5G(60), CHAN5G(64), CHAN5G(100), CHAN5G(104), CHAN5G(108),
CHAN5G(112), CHAN5G(116), CHAN5G(120), CHAN5G(124), CHAN5G(128),
CHAN5G(132), CHAN5G(136), CHAN5G(140), CHAN5G(144), CHAN5G(149),
CHAN5G(153), CHAN5G(157), CHAN5G(161), CHAN5G(165)
};
/* Band templates duplicated per wiphy. The channel info
* above is added to the band during setup.
*/
static const struct ieee80211_supported_band __wl_band_2ghz = {
.band = NL80211_BAND_2GHZ,
.bitrates = wl_g_rates,
.n_bitrates = wl_g_rates_size,
};
static const struct ieee80211_supported_band __wl_band_5ghz = {
.band = NL80211_BAND_5GHZ,
.bitrates = wl_a_rates,
.n_bitrates = wl_a_rates_size,
};
/* This is to override regulatory domains defined in cfg80211 module (reg.c)
* By default world regulatory domain defined in reg.c puts the flags
* NL80211_RRF_NO_IR for 5GHz channels (for * 36..48 and 149..165).
* With respect to these flags, wpa_supplicant doesn't * start p2p
* operations on 5GHz channels. All the changes in world regulatory
* domain are to be done here.
*/
static const struct ieee80211_regdomain brcmf_regdom = {
.n_reg_rules = 4,
.alpha2 = "99",
.reg_rules = {
/* IEEE 802.11b/g, channels 1..11 */
REG_RULE(2412-10, 2472+10, 40, 6, 20, 0),
/* If any */
/* IEEE 802.11 channel 14 - Only JP enables
* this and for 802.11b only
*/
REG_RULE(2484-10, 2484+10, 20, 6, 20, 0),
/* IEEE 802.11a, channel 36..64 */
REG_RULE(5150-10, 5350+10, 80, 6, 20, 0),
/* IEEE 802.11a, channel 100..165 */
REG_RULE(5470-10, 5850+10, 80, 6, 20, 0), }
};
/* Note: brcmf_cipher_suites is an array of int defining which cipher suites
* are supported. A pointer to this array and the number of entries is passed
* on to upper layers. AES_CMAC defines whether or not the driver supports MFP.
* So the cipher suite AES_CMAC has to be the last one in the array, and when
* device does not support MFP then the number of suites will be decreased by 1
*/
static const u32 brcmf_cipher_suites[] = {
WLAN_CIPHER_SUITE_WEP40,
WLAN_CIPHER_SUITE_WEP104,
WLAN_CIPHER_SUITE_TKIP,
WLAN_CIPHER_SUITE_CCMP,
/* Keep as last entry: */
WLAN_CIPHER_SUITE_AES_CMAC
};
/* Vendor specific ie. id = 221, oui and type defines exact ie */
struct brcmf_vs_tlv {
u8 id;
u8 len;
u8 oui[3];
u8 oui_type;
};
struct parsed_vndr_ie_info {
u8 *ie_ptr;
u32 ie_len; /* total length including id & length field */
struct brcmf_vs_tlv vndrie;
};
struct parsed_vndr_ies {
u32 count;
struct parsed_vndr_ie_info ie_info[VNDR_IE_PARSE_LIMIT];
};
static u8 nl80211_band_to_fwil(enum nl80211_band band)
{
switch (band) {
case NL80211_BAND_2GHZ:
return WLC_BAND_2G;
case NL80211_BAND_5GHZ:
return WLC_BAND_5G;
default:
WARN_ON(1);
break;
}
return 0;
}
static u16 chandef_to_chanspec(struct brcmu_d11inf *d11inf,
struct cfg80211_chan_def *ch)
{
struct brcmu_chan ch_inf;
s32 primary_offset;
brcmf_dbg(TRACE, "chandef: control %d center %d width %d\n",
ch->chan->center_freq, ch->center_freq1, ch->width);
ch_inf.chnum = ieee80211_frequency_to_channel(ch->center_freq1);
primary_offset = ch->chan->center_freq - ch->center_freq1;
switch (ch->width) {
case NL80211_CHAN_WIDTH_20:
case NL80211_CHAN_WIDTH_20_NOHT:
ch_inf.bw = BRCMU_CHAN_BW_20;
WARN_ON(primary_offset != 0);
break;
case NL80211_CHAN_WIDTH_40:
ch_inf.bw = BRCMU_CHAN_BW_40;
if (primary_offset > 0)
ch_inf.sb = BRCMU_CHAN_SB_U;
else
ch_inf.sb = BRCMU_CHAN_SB_L;
break;
case NL80211_CHAN_WIDTH_80:
ch_inf.bw = BRCMU_CHAN_BW_80;
if (primary_offset == -30)
ch_inf.sb = BRCMU_CHAN_SB_LL;
else if (primary_offset == -10)
ch_inf.sb = BRCMU_CHAN_SB_LU;
else if (primary_offset == 10)
ch_inf.sb = BRCMU_CHAN_SB_UL;
else
ch_inf.sb = BRCMU_CHAN_SB_UU;
break;
case NL80211_CHAN_WIDTH_80P80:
case NL80211_CHAN_WIDTH_160:
case NL80211_CHAN_WIDTH_5:
case NL80211_CHAN_WIDTH_10:
default:
WARN_ON_ONCE(1);
}
switch (ch->chan->band) {
case NL80211_BAND_2GHZ:
ch_inf.band = BRCMU_CHAN_BAND_2G;
break;
case NL80211_BAND_5GHZ:
ch_inf.band = BRCMU_CHAN_BAND_5G;
break;
case NL80211_BAND_60GHZ:
default:
WARN_ON_ONCE(1);
}
d11inf->encchspec(&ch_inf);
return ch_inf.chspec;
}
u16 channel_to_chanspec(struct brcmu_d11inf *d11inf,
struct ieee80211_channel *ch)
{
struct brcmu_chan ch_inf;
ch_inf.chnum = ieee80211_frequency_to_channel(ch->center_freq);
ch_inf.bw = BRCMU_CHAN_BW_20;
d11inf->encchspec(&ch_inf);
return ch_inf.chspec;
}
/* Traverse a string of 1-byte tag/1-byte length/variable-length value
* triples, returning a pointer to the substring whose first element
* matches tag
*/
const struct brcmf_tlv *
brcmf_parse_tlvs(const void *buf, int buflen, uint key)
{
const struct brcmf_tlv *elt = buf;
int totlen = buflen;
/* find tagged parameter */
while (totlen >= TLV_HDR_LEN) {
int len = elt->len;
/* validate remaining totlen */
if ((elt->id == key) && (totlen >= (len + TLV_HDR_LEN)))
return elt;
elt = (struct brcmf_tlv *)((u8 *)elt + (len + TLV_HDR_LEN));
totlen -= (len + TLV_HDR_LEN);
}
return NULL;
}
/* Is any of the tlvs the expected entry? If
* not update the tlvs buffer pointer/length.
*/
static bool
brcmf_tlv_has_ie(const u8 *ie, const u8 **tlvs, u32 *tlvs_len,
const u8 *oui, u32 oui_len, u8 type)
{
/* If the contents match the OUI and the type */
if (ie[TLV_LEN_OFF] >= oui_len + 1 &&
!memcmp(&ie[TLV_BODY_OFF], oui, oui_len) &&
type == ie[TLV_BODY_OFF + oui_len]) {
return true;
}
if (tlvs == NULL)
return false;
/* point to the next ie */
ie += ie[TLV_LEN_OFF] + TLV_HDR_LEN;
/* calculate the length of the rest of the buffer */
*tlvs_len -= (int)(ie - *tlvs);
/* update the pointer to the start of the buffer */
*tlvs = ie;
return false;
}
static struct brcmf_vs_tlv *
brcmf_find_wpaie(const u8 *parse, u32 len)
{
const struct brcmf_tlv *ie;
while ((ie = brcmf_parse_tlvs(parse, len, WLAN_EID_VENDOR_SPECIFIC))) {
if (brcmf_tlv_has_ie((const u8 *)ie, &parse, &len,
WPA_OUI, TLV_OUI_LEN, WPA_OUI_TYPE))
return (struct brcmf_vs_tlv *)ie;
}
return NULL;
}
static struct brcmf_vs_tlv *
brcmf_find_wpsie(const u8 *parse, u32 len)
{
const struct brcmf_tlv *ie;
while ((ie = brcmf_parse_tlvs(parse, len, WLAN_EID_VENDOR_SPECIFIC))) {
if (brcmf_tlv_has_ie((u8 *)ie, &parse, &len,
WPA_OUI, TLV_OUI_LEN, WPS_OUI_TYPE))
return (struct brcmf_vs_tlv *)ie;
}
return NULL;
}
static int brcmf_vif_change_validate(struct brcmf_cfg80211_info *cfg,
struct brcmf_cfg80211_vif *vif,
enum nl80211_iftype new_type)
{
int iftype_num[NUM_NL80211_IFTYPES];
struct brcmf_cfg80211_vif *pos;
bool check_combos = false;
int ret = 0;
memset(&iftype_num[0], 0, sizeof(iftype_num));
list_for_each_entry(pos, &cfg->vif_list, list)
if (pos == vif) {
iftype_num[new_type]++;
} else {
/* concurrent interfaces so need check combinations */
check_combos = true;
iftype_num[pos->wdev.iftype]++;
}
if (check_combos)
ret = cfg80211_check_combinations(cfg->wiphy, 1, 0, iftype_num);
return ret;
}
static int brcmf_vif_add_validate(struct brcmf_cfg80211_info *cfg,
enum nl80211_iftype new_type)
{
int iftype_num[NUM_NL80211_IFTYPES];
struct brcmf_cfg80211_vif *pos;
memset(&iftype_num[0], 0, sizeof(iftype_num));
list_for_each_entry(pos, &cfg->vif_list, list)
iftype_num[pos->wdev.iftype]++;
iftype_num[new_type]++;
return cfg80211_check_combinations(cfg->wiphy, 1, 0, iftype_num);
}
static void convert_key_from_CPU(struct brcmf_wsec_key *key,
struct brcmf_wsec_key_le *key_le)
{
key_le->index = cpu_to_le32(key->index);
key_le->len = cpu_to_le32(key->len);
key_le->algo = cpu_to_le32(key->algo);
key_le->flags = cpu_to_le32(key->flags);
key_le->rxiv.hi = cpu_to_le32(key->rxiv.hi);
key_le->rxiv.lo = cpu_to_le16(key->rxiv.lo);
key_le->iv_initialized = cpu_to_le32(key->iv_initialized);
memcpy(key_le->data, key->data, sizeof(key->data));
memcpy(key_le->ea, key->ea, sizeof(key->ea));
}
static int
send_key_to_dongle(struct brcmf_if *ifp, struct brcmf_wsec_key *key)
{
int err;
struct brcmf_wsec_key_le key_le;
convert_key_from_CPU(key, &key_le);
brcmf_netdev_wait_pend8021x(ifp);
err = brcmf_fil_bsscfg_data_set(ifp, "wsec_key", &key_le,
sizeof(key_le));
if (err)
brcmf_err("wsec_key error (%d)\n", err);
return err;
}
static s32
brcmf_configure_arp_nd_offload(struct brcmf_if *ifp, bool enable)
{
s32 err;
u32 mode;
if (enable)
mode = BRCMF_ARP_OL_AGENT | BRCMF_ARP_OL_PEER_AUTO_REPLY;
else
mode = 0;
/* Try to set and enable ARP offload feature, this may fail, then it */
/* is simply not supported and err 0 will be returned */
err = brcmf_fil_iovar_int_set(ifp, "arp_ol", mode);
if (err) {
brcmf_dbg(TRACE, "failed to set ARP offload mode to 0x%x, err = %d\n",
mode, err);
err = 0;
} else {
err = brcmf_fil_iovar_int_set(ifp, "arpoe", enable);
if (err) {
brcmf_dbg(TRACE, "failed to configure (%d) ARP offload err = %d\n",
enable, err);
err = 0;
} else
brcmf_dbg(TRACE, "successfully configured (%d) ARP offload to 0x%x\n",
enable, mode);
}
err = brcmf_fil_iovar_int_set(ifp, "ndoe", enable);
if (err) {
brcmf_dbg(TRACE, "failed to configure (%d) ND offload err = %d\n",
enable, err);
err = 0;
} else
brcmf_dbg(TRACE, "successfully configured (%d) ND offload to 0x%x\n",
enable, mode);
return err;
}
static void
brcmf_cfg80211_update_proto_addr_mode(struct wireless_dev *wdev)
{
struct brcmf_cfg80211_vif *vif;
struct brcmf_if *ifp;
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
ifp = vif->ifp;
if ((wdev->iftype == NL80211_IFTYPE_ADHOC) ||
(wdev->iftype == NL80211_IFTYPE_AP) ||
(wdev->iftype == NL80211_IFTYPE_P2P_GO))
brcmf_proto_configure_addr_mode(ifp->drvr, ifp->ifidx,
ADDR_DIRECT);
else
brcmf_proto_configure_addr_mode(ifp->drvr, ifp->ifidx,
ADDR_INDIRECT);
}
static int brcmf_get_first_free_bsscfgidx(struct brcmf_pub *drvr)
{
int bsscfgidx;
for (bsscfgidx = 0; bsscfgidx < BRCMF_MAX_IFS; bsscfgidx++) {
/* bsscfgidx 1 is reserved for legacy P2P */
if (bsscfgidx == 1)
continue;
if (!drvr->iflist[bsscfgidx])
return bsscfgidx;
}
return -ENOMEM;
}
static int brcmf_cfg80211_request_ap_if(struct brcmf_if *ifp)
{
struct brcmf_mbss_ssid_le mbss_ssid_le;
int bsscfgidx;
int err;
memset(&mbss_ssid_le, 0, sizeof(mbss_ssid_le));
bsscfgidx = brcmf_get_first_free_bsscfgidx(ifp->drvr);
if (bsscfgidx < 0)
return bsscfgidx;
mbss_ssid_le.bsscfgidx = cpu_to_le32(bsscfgidx);
mbss_ssid_le.SSID_len = cpu_to_le32(5);
sprintf(mbss_ssid_le.SSID, "ssid%d" , bsscfgidx);
err = brcmf_fil_bsscfg_data_set(ifp, "bsscfg:ssid", &mbss_ssid_le,
sizeof(mbss_ssid_le));
if (err < 0)
brcmf_err("setting ssid failed %d\n", err);
return err;
}
/**
* brcmf_ap_add_vif() - create a new AP virtual interface for multiple BSS
*
* @wiphy: wiphy device of new interface.
* @name: name of the new interface.
* @flags: not used.
* @params: contains mac address for AP device.
*/
static
struct wireless_dev *brcmf_ap_add_vif(struct wiphy *wiphy, const char *name,
u32 *flags, struct vif_params *params)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
struct brcmf_cfg80211_vif *vif;
int err;
if (brcmf_cfg80211_vif_event_armed(cfg))
return ERR_PTR(-EBUSY);
brcmf_dbg(INFO, "Adding vif \"%s\"\n", name);
vif = brcmf_alloc_vif(cfg, NL80211_IFTYPE_AP);
if (IS_ERR(vif))
return (struct wireless_dev *)vif;
brcmf_cfg80211_arm_vif_event(cfg, vif);
err = brcmf_cfg80211_request_ap_if(ifp);
if (err) {
brcmf_cfg80211_arm_vif_event(cfg, NULL);
goto fail;
}
/* wait for firmware event */
err = brcmf_cfg80211_wait_vif_event(cfg, BRCMF_E_IF_ADD,
BRCMF_VIF_EVENT_TIMEOUT);
brcmf_cfg80211_arm_vif_event(cfg, NULL);
if (!err) {
brcmf_err("timeout occurred\n");
err = -EIO;
goto fail;
}
/* interface created in firmware */
ifp = vif->ifp;
if (!ifp) {
brcmf_err("no if pointer provided\n");
err = -ENOENT;
goto fail;
}
strncpy(ifp->ndev->name, name, sizeof(ifp->ndev->name) - 1);
err = brcmf_net_attach(ifp, true);
if (err) {
brcmf_err("Registering netdevice failed\n");
goto fail;
}
return &ifp->vif->wdev;
fail:
brcmf_free_vif(vif);
return ERR_PTR(err);
}
static bool brcmf_is_apmode(struct brcmf_cfg80211_vif *vif)
{
enum nl80211_iftype iftype;
iftype = vif->wdev.iftype;
return iftype == NL80211_IFTYPE_AP || iftype == NL80211_IFTYPE_P2P_GO;
}
static bool brcmf_is_ibssmode(struct brcmf_cfg80211_vif *vif)
{
return vif->wdev.iftype == NL80211_IFTYPE_ADHOC;
}
static struct wireless_dev *brcmf_cfg80211_add_iface(struct wiphy *wiphy,
const char *name,
unsigned char name_assign_type,
enum nl80211_iftype type,
u32 *flags,
struct vif_params *params)
{
struct wireless_dev *wdev;
int err;
brcmf_dbg(TRACE, "enter: %s type %d\n", name, type);
err = brcmf_vif_add_validate(wiphy_to_cfg(wiphy), type);
if (err) {
brcmf_err("iface validation failed: err=%d\n", err);
return ERR_PTR(err);
}
switch (type) {
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_WDS:
case NL80211_IFTYPE_MONITOR:
case NL80211_IFTYPE_MESH_POINT:
return ERR_PTR(-EOPNOTSUPP);
case NL80211_IFTYPE_AP:
wdev = brcmf_ap_add_vif(wiphy, name, flags, params);
break;
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_P2P_GO:
case NL80211_IFTYPE_P2P_DEVICE:
wdev = brcmf_p2p_add_vif(wiphy, name, name_assign_type, type, flags, params);
break;
case NL80211_IFTYPE_UNSPECIFIED:
default:
return ERR_PTR(-EINVAL);
}
if (IS_ERR(wdev))
brcmf_err("add iface %s type %d failed: err=%d\n",
name, type, (int)PTR_ERR(wdev));
else
brcmf_cfg80211_update_proto_addr_mode(wdev);
return wdev;
}
static void brcmf_scan_config_mpc(struct brcmf_if *ifp, int mpc)
{
if (brcmf_feat_is_quirk_enabled(ifp, BRCMF_FEAT_QUIRK_NEED_MPC))
brcmf_set_mpc(ifp, mpc);
}
void brcmf_set_mpc(struct brcmf_if *ifp, int mpc)
{
s32 err = 0;
if (check_vif_up(ifp->vif)) {
err = brcmf_fil_iovar_int_set(ifp, "mpc", mpc);
if (err) {
brcmf_err("fail to set mpc\n");
return;
}
brcmf_dbg(INFO, "MPC : %d\n", mpc);
}
}
s32 brcmf_notify_escan_complete(struct brcmf_cfg80211_info *cfg,
struct brcmf_if *ifp, bool aborted,
bool fw_abort)
{
struct brcmf_scan_params_le params_le;
struct cfg80211_scan_request *scan_request;
s32 err = 0;
brcmf_dbg(SCAN, "Enter\n");
/* clear scan request, because the FW abort can cause a second call */
/* to this functon and might cause a double cfg80211_scan_done */
scan_request = cfg->scan_request;
cfg->scan_request = NULL;
if (timer_pending(&cfg->escan_timeout))
del_timer_sync(&cfg->escan_timeout);
if (fw_abort) {
/* Do a scan abort to stop the driver's scan engine */
brcmf_dbg(SCAN, "ABORT scan in firmware\n");
memset(¶ms_le, 0, sizeof(params_le));
eth_broadcast_addr(params_le.bssid);
params_le.bss_type = DOT11_BSSTYPE_ANY;
params_le.scan_type = 0;
params_le.channel_num = cpu_to_le32(1);
params_le.nprobes = cpu_to_le32(1);
params_le.active_time = cpu_to_le32(-1);
params_le.passive_time = cpu_to_le32(-1);
params_le.home_time = cpu_to_le32(-1);
/* Scan is aborted by setting channel_list[0] to -1 */
params_le.channel_list[0] = cpu_to_le16(-1);
/* E-Scan (or anyother type) can be aborted by SCAN */
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SCAN,
¶ms_le, sizeof(params_le));
if (err)
brcmf_err("Scan abort failed\n");
}
brcmf_scan_config_mpc(ifp, 1);
/*
* e-scan can be initiated by scheduled scan
* which takes precedence.
*/
if (cfg->sched_escan) {
brcmf_dbg(SCAN, "scheduled scan completed\n");
cfg->sched_escan = false;
if (!aborted)
cfg80211_sched_scan_results(cfg_to_wiphy(cfg));
} else if (scan_request) {
struct cfg80211_scan_info info = {
.aborted = aborted,
};
brcmf_dbg(SCAN, "ESCAN Completed scan: %s\n",
aborted ? "Aborted" : "Done");
cfg80211_scan_done(scan_request, &info);
}
if (!test_and_clear_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status))
brcmf_dbg(SCAN, "Scan complete, probably P2P scan\n");
return err;
}
static int brcmf_cfg80211_del_ap_iface(struct wiphy *wiphy,
struct wireless_dev *wdev)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct net_device *ndev = wdev->netdev;
struct brcmf_if *ifp = netdev_priv(ndev);
int ret;
int err;
brcmf_cfg80211_arm_vif_event(cfg, ifp->vif);
err = brcmf_fil_bsscfg_data_set(ifp, "interface_remove", NULL, 0);
if (err) {
brcmf_err("interface_remove failed %d\n", err);
goto err_unarm;
}
/* wait for firmware event */
ret = brcmf_cfg80211_wait_vif_event(cfg, BRCMF_E_IF_DEL,
BRCMF_VIF_EVENT_TIMEOUT);
if (!ret) {
brcmf_err("timeout occurred\n");
err = -EIO;
goto err_unarm;
}
brcmf_remove_interface(ifp, true);
err_unarm:
brcmf_cfg80211_arm_vif_event(cfg, NULL);
return err;
}
static
int brcmf_cfg80211_del_iface(struct wiphy *wiphy, struct wireless_dev *wdev)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct net_device *ndev = wdev->netdev;
if (ndev && ndev == cfg_to_ndev(cfg))
return -ENOTSUPP;
/* vif event pending in firmware */
if (brcmf_cfg80211_vif_event_armed(cfg))
return -EBUSY;
if (ndev) {
if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status) &&
cfg->escan_info.ifp == netdev_priv(ndev))
brcmf_notify_escan_complete(cfg, netdev_priv(ndev),
true, true);
brcmf_fil_iovar_int_set(netdev_priv(ndev), "mpc", 1);
}
switch (wdev->iftype) {
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_WDS:
case NL80211_IFTYPE_MONITOR:
case NL80211_IFTYPE_MESH_POINT:
return -EOPNOTSUPP;
case NL80211_IFTYPE_AP:
return brcmf_cfg80211_del_ap_iface(wiphy, wdev);
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_P2P_GO:
case NL80211_IFTYPE_P2P_DEVICE:
return brcmf_p2p_del_vif(wiphy, wdev);
case NL80211_IFTYPE_UNSPECIFIED:
default:
return -EINVAL;
}
return -EOPNOTSUPP;
}
static s32
brcmf_cfg80211_change_iface(struct wiphy *wiphy, struct net_device *ndev,
enum nl80211_iftype type, u32 *flags,
struct vif_params *params)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_vif *vif = ifp->vif;
s32 infra = 0;
s32 ap = 0;
s32 err = 0;
brcmf_dbg(TRACE, "Enter, bsscfgidx=%d, type=%d\n", ifp->bsscfgidx,
type);
/* WAR: There are a number of p2p interface related problems which
* need to be handled initially (before doing the validate).
* wpa_supplicant tends to do iface changes on p2p device/client/go
* which are not always possible/allowed. However we need to return
* OK otherwise the wpa_supplicant wont start. The situation differs
* on configuration and setup (p2pon=1 module param). The first check
* is to see if the request is a change to station for p2p iface.
*/
if ((type == NL80211_IFTYPE_STATION) &&
((vif->wdev.iftype == NL80211_IFTYPE_P2P_CLIENT) ||
(vif->wdev.iftype == NL80211_IFTYPE_P2P_GO) ||
(vif->wdev.iftype == NL80211_IFTYPE_P2P_DEVICE))) {
brcmf_dbg(TRACE, "Ignoring cmd for p2p if\n");
/* Now depending on whether module param p2pon=1 was used the
* response needs to be either 0 or EOPNOTSUPP. The reason is
* that if p2pon=1 is used, but a newer supplicant is used then
* we should return an error, as this combination wont work.
* In other situations 0 is returned and supplicant will start
* normally. It will give a trace in cfg80211, but it is the
* only way to get it working. Unfortunately this will result
* in situation where we wont support new supplicant in
* combination with module param p2pon=1, but that is the way
* it is. If the user tries this then unloading of driver might
* fail/lock.
*/
if (cfg->p2p.p2pdev_dynamically)
return -EOPNOTSUPP;
else
return 0;
}
err = brcmf_vif_change_validate(wiphy_to_cfg(wiphy), vif, type);
if (err) {
brcmf_err("iface validation failed: err=%d\n", err);
return err;
}
switch (type) {
case NL80211_IFTYPE_MONITOR:
case NL80211_IFTYPE_WDS:
brcmf_err("type (%d) : currently we do not support this type\n",
type);
return -EOPNOTSUPP;
case NL80211_IFTYPE_ADHOC:
infra = 0;
break;
case NL80211_IFTYPE_STATION:
infra = 1;
break;
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_P2P_GO:
ap = 1;
break;
default:
err = -EINVAL;
goto done;
}
if (ap) {
if (type == NL80211_IFTYPE_P2P_GO) {
brcmf_dbg(INFO, "IF Type = P2P GO\n");
err = brcmf_p2p_ifchange(cfg, BRCMF_FIL_P2P_IF_GO);
}
if (!err) {
brcmf_dbg(INFO, "IF Type = AP\n");
}
} else {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_INFRA, infra);
if (err) {
brcmf_err("WLC_SET_INFRA error (%d)\n", err);
err = -EAGAIN;
goto done;
}
brcmf_dbg(INFO, "IF Type = %s\n", brcmf_is_ibssmode(vif) ?
"Adhoc" : "Infra");
}
ndev->ieee80211_ptr->iftype = type;
brcmf_cfg80211_update_proto_addr_mode(&vif->wdev);
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static void brcmf_escan_prep(struct brcmf_cfg80211_info *cfg,
struct brcmf_scan_params_le *params_le,
struct cfg80211_scan_request *request)
{
u32 n_ssids;
u32 n_channels;
s32 i;
s32 offset;
u16 chanspec;
char *ptr;
struct brcmf_ssid_le ssid_le;
eth_broadcast_addr(params_le->bssid);
params_le->bss_type = DOT11_BSSTYPE_ANY;
params_le->scan_type = 0;
params_le->channel_num = 0;
params_le->nprobes = cpu_to_le32(-1);
params_le->active_time = cpu_to_le32(-1);
params_le->passive_time = cpu_to_le32(-1);
params_le->home_time = cpu_to_le32(-1);
memset(¶ms_le->ssid_le, 0, sizeof(params_le->ssid_le));
/* if request is null exit so it will be all channel broadcast scan */
if (!request)
return;
n_ssids = request->n_ssids;
n_channels = request->n_channels;
/* Copy channel array if applicable */
brcmf_dbg(SCAN, "### List of channelspecs to scan ### %d\n",
n_channels);
if (n_channels > 0) {
for (i = 0; i < n_channels; i++) {
chanspec = channel_to_chanspec(&cfg->d11inf,
request->channels[i]);
brcmf_dbg(SCAN, "Chan : %d, Channel spec: %x\n",
request->channels[i]->hw_value, chanspec);
params_le->channel_list[i] = cpu_to_le16(chanspec);
}
} else {
brcmf_dbg(SCAN, "Scanning all channels\n");
}
/* Copy ssid array if applicable */
brcmf_dbg(SCAN, "### List of SSIDs to scan ### %d\n", n_ssids);
if (n_ssids > 0) {
offset = offsetof(struct brcmf_scan_params_le, channel_list) +
n_channels * sizeof(u16);
offset = roundup(offset, sizeof(u32));
ptr = (char *)params_le + offset;
for (i = 0; i < n_ssids; i++) {
memset(&ssid_le, 0, sizeof(ssid_le));
ssid_le.SSID_len =
cpu_to_le32(request->ssids[i].ssid_len);
memcpy(ssid_le.SSID, request->ssids[i].ssid,
request->ssids[i].ssid_len);
if (!ssid_le.SSID_len)
brcmf_dbg(SCAN, "%d: Broadcast scan\n", i);
else
brcmf_dbg(SCAN, "%d: scan for %s size =%d\n",
i, ssid_le.SSID, ssid_le.SSID_len);
memcpy(ptr, &ssid_le, sizeof(ssid_le));
ptr += sizeof(ssid_le);
}
} else {
brcmf_dbg(SCAN, "Broadcast scan %p\n", request->ssids);
if ((request->ssids) && request->ssids->ssid_len) {
brcmf_dbg(SCAN, "SSID %s len=%d\n",
params_le->ssid_le.SSID,
request->ssids->ssid_len);
params_le->ssid_le.SSID_len =
cpu_to_le32(request->ssids->ssid_len);
memcpy(¶ms_le->ssid_le.SSID, request->ssids->ssid,
request->ssids->ssid_len);
}
}
/* Adding mask to channel numbers */
params_le->channel_num =
cpu_to_le32((n_ssids << BRCMF_SCAN_PARAMS_NSSID_SHIFT) |
(n_channels & BRCMF_SCAN_PARAMS_COUNT_MASK));
}
static s32
brcmf_run_escan(struct brcmf_cfg80211_info *cfg, struct brcmf_if *ifp,
struct cfg80211_scan_request *request)
{
s32 params_size = BRCMF_SCAN_PARAMS_FIXED_SIZE +
offsetof(struct brcmf_escan_params_le, params_le);
struct brcmf_escan_params_le *params;
s32 err = 0;
brcmf_dbg(SCAN, "E-SCAN START\n");
if (request != NULL) {
/* Allocate space for populating ssids in struct */
params_size += sizeof(u32) * ((request->n_channels + 1) / 2);
/* Allocate space for populating ssids in struct */
params_size += sizeof(struct brcmf_ssid_le) * request->n_ssids;
}
params = kzalloc(params_size, GFP_KERNEL);
if (!params) {
err = -ENOMEM;
goto exit;
}
BUG_ON(params_size + sizeof("escan") >= BRCMF_DCMD_MEDLEN);
brcmf_escan_prep(cfg, ¶ms->params_le, request);
params->version = cpu_to_le32(BRCMF_ESCAN_REQ_VERSION);
params->action = cpu_to_le16(WL_ESCAN_ACTION_START);
params->sync_id = cpu_to_le16(0x1234);
err = brcmf_fil_iovar_data_set(ifp, "escan", params, params_size);
if (err) {
if (err == -EBUSY)
brcmf_dbg(INFO, "system busy : escan canceled\n");
else
brcmf_err("error (%d)\n", err);
}
kfree(params);
exit:
return err;
}
static s32
brcmf_do_escan(struct brcmf_cfg80211_info *cfg, struct wiphy *wiphy,
struct brcmf_if *ifp, struct cfg80211_scan_request *request)
{
s32 err;
u32 passive_scan;
struct brcmf_scan_results *results;
struct escan_info *escan = &cfg->escan_info;
brcmf_dbg(SCAN, "Enter\n");
escan->ifp = ifp;
escan->wiphy = wiphy;
escan->escan_state = WL_ESCAN_STATE_SCANNING;
passive_scan = cfg->active_scan ? 0 : 1;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PASSIVE_SCAN,
passive_scan);
if (err) {
brcmf_err("error (%d)\n", err);
return err;
}
brcmf_scan_config_mpc(ifp, 0);
results = (struct brcmf_scan_results *)cfg->escan_info.escan_buf;
results->version = 0;
results->count = 0;
results->buflen = WL_ESCAN_RESULTS_FIXED_SIZE;
err = escan->run(cfg, ifp, request);
if (err)
brcmf_scan_config_mpc(ifp, 1);
return err;
}
static s32
brcmf_cfg80211_escan(struct wiphy *wiphy, struct brcmf_cfg80211_vif *vif,
struct cfg80211_scan_request *request,
struct cfg80211_ssid *this_ssid)
{
struct brcmf_if *ifp = vif->ifp;
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct cfg80211_ssid *ssids;
u32 passive_scan;
bool escan_req;
bool spec_scan;
s32 err;
struct brcmf_ssid_le ssid_le;
u32 SSID_len;
brcmf_dbg(SCAN, "START ESCAN\n");
if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status)) {
brcmf_err("Scanning already: status (%lu)\n", cfg->scan_status);
return -EAGAIN;
}
if (test_bit(BRCMF_SCAN_STATUS_ABORT, &cfg->scan_status)) {
brcmf_err("Scanning being aborted: status (%lu)\n",
cfg->scan_status);
return -EAGAIN;
}
if (test_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status)) {
brcmf_err("Scanning suppressed: status (%lu)\n",
cfg->scan_status);
return -EAGAIN;
}
if (test_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state)) {
brcmf_err("Connecting: status (%lu)\n", ifp->vif->sme_state);
return -EAGAIN;
}
/* If scan req comes for p2p0, send it over primary I/F */
if (vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif)
vif = cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif;
escan_req = false;
if (request) {
/* scan bss */
ssids = request->ssids;
escan_req = true;
} else {
/* scan in ibss */
/* we don't do escan in ibss */
ssids = this_ssid;
}
cfg->scan_request = request;
set_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status);
if (escan_req) {
cfg->escan_info.run = brcmf_run_escan;
err = brcmf_p2p_scan_prep(wiphy, request, vif);
if (err)
goto scan_out;
err = brcmf_do_escan(cfg, wiphy, vif->ifp, request);
if (err)
goto scan_out;
} else {
brcmf_dbg(SCAN, "ssid \"%s\", ssid_len (%d)\n",
ssids->ssid, ssids->ssid_len);
memset(&ssid_le, 0, sizeof(ssid_le));
SSID_len = min_t(u8, sizeof(ssid_le.SSID), ssids->ssid_len);
ssid_le.SSID_len = cpu_to_le32(0);
spec_scan = false;
if (SSID_len) {
memcpy(ssid_le.SSID, ssids->ssid, SSID_len);
ssid_le.SSID_len = cpu_to_le32(SSID_len);
spec_scan = true;
} else
brcmf_dbg(SCAN, "Broadcast scan\n");
passive_scan = cfg->active_scan ? 0 : 1;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PASSIVE_SCAN,
passive_scan);
if (err) {
brcmf_err("WLC_SET_PASSIVE_SCAN error (%d)\n", err);
goto scan_out;
}
brcmf_scan_config_mpc(ifp, 0);
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SCAN, &ssid_le,
sizeof(ssid_le));
if (err) {
if (err == -EBUSY)
brcmf_dbg(INFO, "BUSY: scan for \"%s\" canceled\n",
ssid_le.SSID);
else
brcmf_err("WLC_SCAN error (%d)\n", err);
brcmf_scan_config_mpc(ifp, 1);
goto scan_out;
}
}
/* Arm scan timeout timer */
mod_timer(&cfg->escan_timeout, jiffies +
BRCMF_ESCAN_TIMER_INTERVAL_MS * HZ / 1000);
return 0;
scan_out:
clear_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status);
cfg->scan_request = NULL;
return err;
}
static s32
brcmf_cfg80211_scan(struct wiphy *wiphy, struct cfg80211_scan_request *request)
{
struct brcmf_cfg80211_vif *vif;
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
vif = container_of(request->wdev, struct brcmf_cfg80211_vif, wdev);
if (!check_vif_up(vif))
return -EIO;
err = brcmf_cfg80211_escan(wiphy, vif, request, NULL);
if (err)
brcmf_err("scan error (%d)\n", err);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32 brcmf_set_rts(struct net_device *ndev, u32 rts_threshold)
{
s32 err = 0;
err = brcmf_fil_iovar_int_set(netdev_priv(ndev), "rtsthresh",
rts_threshold);
if (err)
brcmf_err("Error (%d)\n", err);
return err;
}
static s32 brcmf_set_frag(struct net_device *ndev, u32 frag_threshold)
{
s32 err = 0;
err = brcmf_fil_iovar_int_set(netdev_priv(ndev), "fragthresh",
frag_threshold);
if (err)
brcmf_err("Error (%d)\n", err);
return err;
}
static s32 brcmf_set_retry(struct net_device *ndev, u32 retry, bool l)
{
s32 err = 0;
u32 cmd = (l ? BRCMF_C_SET_LRL : BRCMF_C_SET_SRL);
err = brcmf_fil_cmd_int_set(netdev_priv(ndev), cmd, retry);
if (err) {
brcmf_err("cmd (%d) , error (%d)\n", cmd, err);
return err;
}
return err;
}
static s32 brcmf_cfg80211_set_wiphy_params(struct wiphy *wiphy, u32 changed)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
if (changed & WIPHY_PARAM_RTS_THRESHOLD &&
(cfg->conf->rts_threshold != wiphy->rts_threshold)) {
cfg->conf->rts_threshold = wiphy->rts_threshold;
err = brcmf_set_rts(ndev, cfg->conf->rts_threshold);
if (!err)
goto done;
}
if (changed & WIPHY_PARAM_FRAG_THRESHOLD &&
(cfg->conf->frag_threshold != wiphy->frag_threshold)) {
cfg->conf->frag_threshold = wiphy->frag_threshold;
err = brcmf_set_frag(ndev, cfg->conf->frag_threshold);
if (!err)
goto done;
}
if (changed & WIPHY_PARAM_RETRY_LONG
&& (cfg->conf->retry_long != wiphy->retry_long)) {
cfg->conf->retry_long = wiphy->retry_long;
err = brcmf_set_retry(ndev, cfg->conf->retry_long, true);
if (!err)
goto done;
}
if (changed & WIPHY_PARAM_RETRY_SHORT
&& (cfg->conf->retry_short != wiphy->retry_short)) {
cfg->conf->retry_short = wiphy->retry_short;
err = brcmf_set_retry(ndev, cfg->conf->retry_short, false);
if (!err)
goto done;
}
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static void brcmf_init_prof(struct brcmf_cfg80211_profile *prof)
{
memset(prof, 0, sizeof(*prof));
}
static u16 brcmf_map_fw_linkdown_reason(const struct brcmf_event_msg *e)
{
u16 reason;
switch (e->event_code) {
case BRCMF_E_DEAUTH:
case BRCMF_E_DEAUTH_IND:
case BRCMF_E_DISASSOC_IND:
reason = e->reason;
break;
case BRCMF_E_LINK:
default:
reason = 0;
break;
}
return reason;
}
static void brcmf_link_down(struct brcmf_cfg80211_vif *vif, u16 reason)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(vif->wdev.wiphy);
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
if (test_and_clear_bit(BRCMF_VIF_STATUS_CONNECTED, &vif->sme_state)) {
brcmf_dbg(INFO, "Call WLC_DISASSOC to stop excess roaming\n ");
err = brcmf_fil_cmd_data_set(vif->ifp,
BRCMF_C_DISASSOC, NULL, 0);
if (err) {
brcmf_err("WLC_DISASSOC failed (%d)\n", err);
}
if ((vif->wdev.iftype == NL80211_IFTYPE_STATION) ||
(vif->wdev.iftype == NL80211_IFTYPE_P2P_CLIENT))
cfg80211_disconnected(vif->wdev.netdev, reason, NULL, 0,
true, GFP_KERNEL);
}
clear_bit(BRCMF_VIF_STATUS_CONNECTING, &vif->sme_state);
clear_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status);
brcmf_btcoex_set_mode(vif, BRCMF_BTCOEX_ENABLED, 0);
brcmf_dbg(TRACE, "Exit\n");
}
static s32
brcmf_cfg80211_join_ibss(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_ibss_params *params)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct brcmf_join_params join_params;
size_t join_params_size = 0;
s32 err = 0;
s32 wsec = 0;
s32 bcnprd;
u16 chanspec;
u32 ssid_len;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
if (params->ssid)
brcmf_dbg(CONN, "SSID: %s\n", params->ssid);
else {
brcmf_dbg(CONN, "SSID: NULL, Not supported\n");
return -EOPNOTSUPP;
}
set_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
if (params->bssid)
brcmf_dbg(CONN, "BSSID: %pM\n", params->bssid);
else
brcmf_dbg(CONN, "No BSSID specified\n");
if (params->chandef.chan)
brcmf_dbg(CONN, "channel: %d\n",
params->chandef.chan->center_freq);
else
brcmf_dbg(CONN, "no channel specified\n");
if (params->channel_fixed)
brcmf_dbg(CONN, "fixed channel required\n");
else
brcmf_dbg(CONN, "no fixed channel required\n");
if (params->ie && params->ie_len)
brcmf_dbg(CONN, "ie len: %d\n", params->ie_len);
else
brcmf_dbg(CONN, "no ie specified\n");
if (params->beacon_interval)
brcmf_dbg(CONN, "beacon interval: %d\n",
params->beacon_interval);
else
brcmf_dbg(CONN, "no beacon interval specified\n");
if (params->basic_rates)
brcmf_dbg(CONN, "basic rates: %08X\n", params->basic_rates);
else
brcmf_dbg(CONN, "no basic rates specified\n");
if (params->privacy)
brcmf_dbg(CONN, "privacy required\n");
else
brcmf_dbg(CONN, "no privacy required\n");
/* Configure Privacy for starter */
if (params->privacy)
wsec |= WEP_ENABLED;
err = brcmf_fil_iovar_int_set(ifp, "wsec", wsec);
if (err) {
brcmf_err("wsec failed (%d)\n", err);
goto done;
}
/* Configure Beacon Interval for starter */
if (params->beacon_interval)
bcnprd = params->beacon_interval;
else
bcnprd = 100;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_BCNPRD, bcnprd);
if (err) {
brcmf_err("WLC_SET_BCNPRD failed (%d)\n", err);
goto done;
}
/* Configure required join parameter */
memset(&join_params, 0, sizeof(struct brcmf_join_params));
/* SSID */
ssid_len = min_t(u32, params->ssid_len, IEEE80211_MAX_SSID_LEN);
memcpy(join_params.ssid_le.SSID, params->ssid, ssid_len);
join_params.ssid_le.SSID_len = cpu_to_le32(ssid_len);
join_params_size = sizeof(join_params.ssid_le);
/* BSSID */
if (params->bssid) {
memcpy(join_params.params_le.bssid, params->bssid, ETH_ALEN);
join_params_size += BRCMF_ASSOC_PARAMS_FIXED_SIZE;
memcpy(profile->bssid, params->bssid, ETH_ALEN);
} else {
eth_broadcast_addr(join_params.params_le.bssid);
eth_zero_addr(profile->bssid);
}
/* Channel */
if (params->chandef.chan) {
u32 target_channel;
cfg->channel =
ieee80211_frequency_to_channel(
params->chandef.chan->center_freq);
if (params->channel_fixed) {
/* adding chanspec */
chanspec = chandef_to_chanspec(&cfg->d11inf,
¶ms->chandef);
join_params.params_le.chanspec_list[0] =
cpu_to_le16(chanspec);
join_params.params_le.chanspec_num = cpu_to_le32(1);
join_params_size += sizeof(join_params.params_le);
}
/* set channel for starter */
target_channel = cfg->channel;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_CHANNEL,
target_channel);
if (err) {
brcmf_err("WLC_SET_CHANNEL failed (%d)\n", err);
goto done;
}
} else
cfg->channel = 0;
cfg->ibss_starter = false;
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,
&join_params, join_params_size);
if (err) {
brcmf_err("WLC_SET_SSID failed (%d)\n", err);
goto done;
}
done:
if (err)
clear_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_leave_ibss(struct wiphy *wiphy, struct net_device *ndev)
{
struct brcmf_if *ifp = netdev_priv(ndev);
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif)) {
/* When driver is being unloaded, it can end up here. If an
* error is returned then later on a debug trace in the wireless
* core module will be printed. To avoid this 0 is returned.
*/
return 0;
}
brcmf_link_down(ifp->vif, WLAN_REASON_DEAUTH_LEAVING);
brcmf_net_setcarrier(ifp, false);
brcmf_dbg(TRACE, "Exit\n");
return 0;
}
static s32 brcmf_set_wpa_version(struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_profile *profile = ndev_to_prof(ndev);
struct brcmf_cfg80211_security *sec;
s32 val = 0;
s32 err = 0;
if (sme->crypto.wpa_versions & NL80211_WPA_VERSION_1)
val = WPA_AUTH_PSK | WPA_AUTH_UNSPECIFIED;
else if (sme->crypto.wpa_versions & NL80211_WPA_VERSION_2)
val = WPA2_AUTH_PSK | WPA2_AUTH_UNSPECIFIED;
else
val = WPA_AUTH_DISABLED;
brcmf_dbg(CONN, "setting wpa_auth to 0x%0x\n", val);
err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "wpa_auth", val);
if (err) {
brcmf_err("set wpa_auth failed (%d)\n", err);
return err;
}
sec = &profile->sec;
sec->wpa_versions = sme->crypto.wpa_versions;
return err;
}
static s32 brcmf_set_auth_type(struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_profile *profile = ndev_to_prof(ndev);
struct brcmf_cfg80211_security *sec;
s32 val = 0;
s32 err = 0;
switch (sme->auth_type) {
case NL80211_AUTHTYPE_OPEN_SYSTEM:
val = 0;
brcmf_dbg(CONN, "open system\n");
break;
case NL80211_AUTHTYPE_SHARED_KEY:
val = 1;
brcmf_dbg(CONN, "shared key\n");
break;
case NL80211_AUTHTYPE_AUTOMATIC:
val = 2;
brcmf_dbg(CONN, "automatic\n");
break;
case NL80211_AUTHTYPE_NETWORK_EAP:
brcmf_dbg(CONN, "network eap\n");
default:
val = 2;
brcmf_err("invalid auth type (%d)\n", sme->auth_type);
break;
}
err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "auth", val);
if (err) {
brcmf_err("set auth failed (%d)\n", err);
return err;
}
sec = &profile->sec;
sec->auth_type = sme->auth_type;
return err;
}
static s32
brcmf_set_wsec_mode(struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_profile *profile = ndev_to_prof(ndev);
struct brcmf_cfg80211_security *sec;
s32 pval = 0;
s32 gval = 0;
s32 wsec;
s32 err = 0;
if (sme->crypto.n_ciphers_pairwise) {
switch (sme->crypto.ciphers_pairwise[0]) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
pval = WEP_ENABLED;
break;
case WLAN_CIPHER_SUITE_TKIP:
pval = TKIP_ENABLED;
break;
case WLAN_CIPHER_SUITE_CCMP:
pval = AES_ENABLED;
break;
case WLAN_CIPHER_SUITE_AES_CMAC:
pval = AES_ENABLED;
break;
default:
brcmf_err("invalid cipher pairwise (%d)\n",
sme->crypto.ciphers_pairwise[0]);
return -EINVAL;
}
}
if (sme->crypto.cipher_group) {
switch (sme->crypto.cipher_group) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
gval = WEP_ENABLED;
break;
case WLAN_CIPHER_SUITE_TKIP:
gval = TKIP_ENABLED;
break;
case WLAN_CIPHER_SUITE_CCMP:
gval = AES_ENABLED;
break;
case WLAN_CIPHER_SUITE_AES_CMAC:
gval = AES_ENABLED;
break;
default:
brcmf_err("invalid cipher group (%d)\n",
sme->crypto.cipher_group);
return -EINVAL;
}
}
brcmf_dbg(CONN, "pval (%d) gval (%d)\n", pval, gval);
/* In case of privacy, but no security and WPS then simulate */
/* setting AES. WPS-2.0 allows no security */
if (brcmf_find_wpsie(sme->ie, sme->ie_len) && !pval && !gval &&
sme->privacy)
pval = AES_ENABLED;
wsec = pval | gval;
err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "wsec", wsec);
if (err) {
brcmf_err("error (%d)\n", err);
return err;
}
sec = &profile->sec;
sec->cipher_pairwise = sme->crypto.ciphers_pairwise[0];
sec->cipher_group = sme->crypto.cipher_group;
return err;
}
static s32
brcmf_set_key_mgmt(struct net_device *ndev, struct cfg80211_connect_params *sme)
{
struct brcmf_if *ifp = netdev_priv(ndev);
s32 val;
s32 err;
const struct brcmf_tlv *rsn_ie;
const u8 *ie;
u32 ie_len;
u32 offset;
u16 rsn_cap;
u32 mfp;
u16 count;
if (!sme->crypto.n_akm_suites)
return 0;
err = brcmf_fil_bsscfg_int_get(netdev_priv(ndev), "wpa_auth", &val);
if (err) {
brcmf_err("could not get wpa_auth (%d)\n", err);
return err;
}
if (val & (WPA_AUTH_PSK | WPA_AUTH_UNSPECIFIED)) {
switch (sme->crypto.akm_suites[0]) {
case WLAN_AKM_SUITE_8021X:
val = WPA_AUTH_UNSPECIFIED;
break;
case WLAN_AKM_SUITE_PSK:
val = WPA_AUTH_PSK;
break;
default:
brcmf_err("invalid cipher group (%d)\n",
sme->crypto.cipher_group);
return -EINVAL;
}
} else if (val & (WPA2_AUTH_PSK | WPA2_AUTH_UNSPECIFIED)) {
switch (sme->crypto.akm_suites[0]) {
case WLAN_AKM_SUITE_8021X:
val = WPA2_AUTH_UNSPECIFIED;
break;
case WLAN_AKM_SUITE_8021X_SHA256:
val = WPA2_AUTH_1X_SHA256;
break;
case WLAN_AKM_SUITE_PSK_SHA256:
val = WPA2_AUTH_PSK_SHA256;
break;
case WLAN_AKM_SUITE_PSK:
val = WPA2_AUTH_PSK;
break;
default:
brcmf_err("invalid cipher group (%d)\n",
sme->crypto.cipher_group);
return -EINVAL;
}
}
if (!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP))
goto skip_mfp_config;
/* The MFP mode (1 or 2) needs to be determined, parse IEs. The
* IE will not be verified, just a quick search for MFP config
*/
rsn_ie = brcmf_parse_tlvs((const u8 *)sme->ie, sme->ie_len,
WLAN_EID_RSN);
if (!rsn_ie)
goto skip_mfp_config;
ie = (const u8 *)rsn_ie;
ie_len = rsn_ie->len + TLV_HDR_LEN;
/* Skip unicast suite */
offset = TLV_HDR_LEN + WPA_IE_VERSION_LEN + WPA_IE_MIN_OUI_LEN;
if (offset + WPA_IE_SUITE_COUNT_LEN >= ie_len)
goto skip_mfp_config;
/* Skip multicast suite */
count = ie[offset] + (ie[offset + 1] << 8);
offset += WPA_IE_SUITE_COUNT_LEN + (count * WPA_IE_MIN_OUI_LEN);
if (offset + WPA_IE_SUITE_COUNT_LEN >= ie_len)
goto skip_mfp_config;
/* Skip auth key management suite(s) */
count = ie[offset] + (ie[offset + 1] << 8);
offset += WPA_IE_SUITE_COUNT_LEN + (count * WPA_IE_MIN_OUI_LEN);
if (offset + WPA_IE_SUITE_COUNT_LEN > ie_len)
goto skip_mfp_config;
/* Ready to read capabilities */
mfp = BRCMF_MFP_NONE;
rsn_cap = ie[offset] + (ie[offset + 1] << 8);
if (rsn_cap & RSN_CAP_MFPR_MASK)
mfp = BRCMF_MFP_REQUIRED;
else if (rsn_cap & RSN_CAP_MFPC_MASK)
mfp = BRCMF_MFP_CAPABLE;
brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "mfp", mfp);
skip_mfp_config:
brcmf_dbg(CONN, "setting wpa_auth to %d\n", val);
err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "wpa_auth", val);
if (err) {
brcmf_err("could not set wpa_auth (%d)\n", err);
return err;
}
return err;
}
static s32
brcmf_set_sharedkey(struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_profile *profile = ndev_to_prof(ndev);
struct brcmf_cfg80211_security *sec;
struct brcmf_wsec_key key;
s32 val;
s32 err = 0;
brcmf_dbg(CONN, "key len (%d)\n", sme->key_len);
if (sme->key_len == 0)
return 0;
sec = &profile->sec;
brcmf_dbg(CONN, "wpa_versions 0x%x cipher_pairwise 0x%x\n",
sec->wpa_versions, sec->cipher_pairwise);
if (sec->wpa_versions & (NL80211_WPA_VERSION_1 | NL80211_WPA_VERSION_2))
return 0;
if (!(sec->cipher_pairwise &
(WLAN_CIPHER_SUITE_WEP40 | WLAN_CIPHER_SUITE_WEP104)))
return 0;
memset(&key, 0, sizeof(key));
key.len = (u32) sme->key_len;
key.index = (u32) sme->key_idx;
if (key.len > sizeof(key.data)) {
brcmf_err("Too long key length (%u)\n", key.len);
return -EINVAL;
}
memcpy(key.data, sme->key, key.len);
key.flags = BRCMF_PRIMARY_KEY;
switch (sec->cipher_pairwise) {
case WLAN_CIPHER_SUITE_WEP40:
key.algo = CRYPTO_ALGO_WEP1;
break;
case WLAN_CIPHER_SUITE_WEP104:
key.algo = CRYPTO_ALGO_WEP128;
break;
default:
brcmf_err("Invalid algorithm (%d)\n",
sme->crypto.ciphers_pairwise[0]);
return -EINVAL;
}
/* Set the new key/index */
brcmf_dbg(CONN, "key length (%d) key index (%d) algo (%d)\n",
key.len, key.index, key.algo);
brcmf_dbg(CONN, "key \"%s\"\n", key.data);
err = send_key_to_dongle(netdev_priv(ndev), &key);
if (err)
return err;
if (sec->auth_type == NL80211_AUTHTYPE_SHARED_KEY) {
brcmf_dbg(CONN, "set auth_type to shared key\n");
val = WL_AUTH_SHARED_KEY; /* shared key */
err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "auth", val);
if (err)
brcmf_err("set auth failed (%d)\n", err);
}
return err;
}
static
enum nl80211_auth_type brcmf_war_auth_type(struct brcmf_if *ifp,
enum nl80211_auth_type type)
{
if (type == NL80211_AUTHTYPE_AUTOMATIC &&
brcmf_feat_is_quirk_enabled(ifp, BRCMF_FEAT_QUIRK_AUTO_AUTH)) {
brcmf_dbg(CONN, "WAR: use OPEN instead of AUTO\n");
type = NL80211_AUTHTYPE_OPEN_SYSTEM;
}
return type;
}
static void brcmf_set_join_pref(struct brcmf_if *ifp,
struct cfg80211_bss_selection *bss_select)
{
struct brcmf_join_pref_params join_pref_params[2];
enum nl80211_band band;
int err, i = 0;
join_pref_params[i].len = 2;
join_pref_params[i].rssi_gain = 0;
if (bss_select->behaviour != NL80211_BSS_SELECT_ATTR_BAND_PREF)
brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_ASSOC_PREFER, WLC_BAND_AUTO);
switch (bss_select->behaviour) {
case __NL80211_BSS_SELECT_ATTR_INVALID:
brcmf_c_set_joinpref_default(ifp);
return;
case NL80211_BSS_SELECT_ATTR_BAND_PREF:
join_pref_params[i].type = BRCMF_JOIN_PREF_BAND;
band = bss_select->param.band_pref;
join_pref_params[i].band = nl80211_band_to_fwil(band);
i++;
break;
case NL80211_BSS_SELECT_ATTR_RSSI_ADJUST:
join_pref_params[i].type = BRCMF_JOIN_PREF_RSSI_DELTA;
band = bss_select->param.adjust.band;
join_pref_params[i].band = nl80211_band_to_fwil(band);
join_pref_params[i].rssi_gain = bss_select->param.adjust.delta;
i++;
break;
case NL80211_BSS_SELECT_ATTR_RSSI:
default:
break;
}
join_pref_params[i].type = BRCMF_JOIN_PREF_RSSI;
join_pref_params[i].len = 2;
join_pref_params[i].rssi_gain = 0;
join_pref_params[i].band = 0;
err = brcmf_fil_iovar_data_set(ifp, "join_pref", join_pref_params,
sizeof(join_pref_params));
if (err)
brcmf_err("Set join_pref error (%d)\n", err);
}
static s32
brcmf_cfg80211_connect(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct ieee80211_channel *chan = sme->channel;
struct brcmf_join_params join_params;
size_t join_params_size;
const struct brcmf_tlv *rsn_ie;
const struct brcmf_vs_tlv *wpa_ie;
const void *ie;
u32 ie_len;
struct brcmf_ext_join_params_le *ext_join_params;
u16 chanspec;
s32 err = 0;
u32 ssid_len;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
if (!sme->ssid) {
brcmf_err("Invalid ssid\n");
return -EOPNOTSUPP;
}
if (ifp->vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif) {
/* A normal (non P2P) connection request setup. */
ie = NULL;
ie_len = 0;
/* find the WPA_IE */
wpa_ie = brcmf_find_wpaie((u8 *)sme->ie, sme->ie_len);
if (wpa_ie) {
ie = wpa_ie;
ie_len = wpa_ie->len + TLV_HDR_LEN;
} else {
/* find the RSN_IE */
rsn_ie = brcmf_parse_tlvs((const u8 *)sme->ie,
sme->ie_len,
WLAN_EID_RSN);
if (rsn_ie) {
ie = rsn_ie;
ie_len = rsn_ie->len + TLV_HDR_LEN;
}
}
brcmf_fil_iovar_data_set(ifp, "wpaie", ie, ie_len);
}
err = brcmf_vif_set_mgmt_ie(ifp->vif, BRCMF_VNDR_IE_ASSOCREQ_FLAG,
sme->ie, sme->ie_len);
if (err)
brcmf_err("Set Assoc REQ IE Failed\n");
else
brcmf_dbg(TRACE, "Applied Vndr IEs for Assoc request\n");
set_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
if (chan) {
cfg->channel =
ieee80211_frequency_to_channel(chan->center_freq);
chanspec = channel_to_chanspec(&cfg->d11inf, chan);
brcmf_dbg(CONN, "channel=%d, center_req=%d, chanspec=0x%04x\n",
cfg->channel, chan->center_freq, chanspec);
} else {
cfg->channel = 0;
chanspec = 0;
}
brcmf_dbg(INFO, "ie (%p), ie_len (%zd)\n", sme->ie, sme->ie_len);
err = brcmf_set_wpa_version(ndev, sme);
if (err) {
brcmf_err("wl_set_wpa_version failed (%d)\n", err);
goto done;
}
sme->auth_type = brcmf_war_auth_type(ifp, sme->auth_type);
err = brcmf_set_auth_type(ndev, sme);
if (err) {
brcmf_err("wl_set_auth_type failed (%d)\n", err);
goto done;
}
err = brcmf_set_wsec_mode(ndev, sme);
if (err) {
brcmf_err("wl_set_set_cipher failed (%d)\n", err);
goto done;
}
err = brcmf_set_key_mgmt(ndev, sme);
if (err) {
brcmf_err("wl_set_key_mgmt failed (%d)\n", err);
goto done;
}
err = brcmf_set_sharedkey(ndev, sme);
if (err) {
brcmf_err("brcmf_set_sharedkey failed (%d)\n", err);
goto done;
}
/* Join with specific BSSID and cached SSID
* If SSID is zero join based on BSSID only
*/
join_params_size = offsetof(struct brcmf_ext_join_params_le, assoc_le) +
offsetof(struct brcmf_assoc_params_le, chanspec_list);
if (cfg->channel)
join_params_size += sizeof(u16);
ext_join_params = kzalloc(join_params_size, GFP_KERNEL);
if (ext_join_params == NULL) {
err = -ENOMEM;
goto done;
}
ssid_len = min_t(u32, sme->ssid_len, IEEE80211_MAX_SSID_LEN);
ext_join_params->ssid_le.SSID_len = cpu_to_le32(ssid_len);
memcpy(&ext_join_params->ssid_le.SSID, sme->ssid, ssid_len);
if (ssid_len < IEEE80211_MAX_SSID_LEN)
brcmf_dbg(CONN, "SSID \"%s\", len (%d)\n",
ext_join_params->ssid_le.SSID, ssid_len);
/* Set up join scan parameters */
ext_join_params->scan_le.scan_type = -1;
ext_join_params->scan_le.home_time = cpu_to_le32(-1);
if (sme->bssid)
memcpy(&ext_join_params->assoc_le.bssid, sme->bssid, ETH_ALEN);
else
eth_broadcast_addr(ext_join_params->assoc_le.bssid);
if (cfg->channel) {
ext_join_params->assoc_le.chanspec_num = cpu_to_le32(1);
ext_join_params->assoc_le.chanspec_list[0] =
cpu_to_le16(chanspec);
/* Increase dwell time to receive probe response or detect
* beacon from target AP at a noisy air only during connect
* command.
*/
ext_join_params->scan_le.active_time =
cpu_to_le32(BRCMF_SCAN_JOIN_ACTIVE_DWELL_TIME_MS);
ext_join_params->scan_le.passive_time =
cpu_to_le32(BRCMF_SCAN_JOIN_PASSIVE_DWELL_TIME_MS);
/* To sync with presence period of VSDB GO send probe request
* more frequently. Probe request will be stopped when it gets
* probe response from target AP/GO.
*/
ext_join_params->scan_le.nprobes =
cpu_to_le32(BRCMF_SCAN_JOIN_ACTIVE_DWELL_TIME_MS /
BRCMF_SCAN_JOIN_PROBE_INTERVAL_MS);
} else {
ext_join_params->scan_le.active_time = cpu_to_le32(-1);
ext_join_params->scan_le.passive_time = cpu_to_le32(-1);
ext_join_params->scan_le.nprobes = cpu_to_le32(-1);
}
brcmf_set_join_pref(ifp, &sme->bss_select);
err = brcmf_fil_bsscfg_data_set(ifp, "join", ext_join_params,
join_params_size);
kfree(ext_join_params);
if (!err)
/* This is it. join command worked, we are done */
goto done;
/* join command failed, fallback to set ssid */
memset(&join_params, 0, sizeof(join_params));
join_params_size = sizeof(join_params.ssid_le);
memcpy(&join_params.ssid_le.SSID, sme->ssid, ssid_len);
join_params.ssid_le.SSID_len = cpu_to_le32(ssid_len);
if (sme->bssid)
memcpy(join_params.params_le.bssid, sme->bssid, ETH_ALEN);
else
eth_broadcast_addr(join_params.params_le.bssid);
if (cfg->channel) {
join_params.params_le.chanspec_list[0] = cpu_to_le16(chanspec);
join_params.params_le.chanspec_num = cpu_to_le32(1);
join_params_size += sizeof(join_params.params_le);
}
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,
&join_params, join_params_size);
if (err)
brcmf_err("BRCMF_C_SET_SSID failed (%d)\n", err);
done:
if (err)
clear_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_disconnect(struct wiphy *wiphy, struct net_device *ndev,
u16 reason_code)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct brcmf_scb_val_le scbval;
s32 err = 0;
brcmf_dbg(TRACE, "Enter. Reason code = %d\n", reason_code);
if (!check_vif_up(ifp->vif))
return -EIO;
clear_bit(BRCMF_VIF_STATUS_CONNECTED, &ifp->vif->sme_state);
clear_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
cfg80211_disconnected(ndev, reason_code, NULL, 0, true, GFP_KERNEL);
memcpy(&scbval.ea, &profile->bssid, ETH_ALEN);
scbval.val = cpu_to_le32(reason_code);
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_DISASSOC,
&scbval, sizeof(scbval));
if (err)
brcmf_err("error (%d)\n", err);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_set_tx_power(struct wiphy *wiphy, struct wireless_dev *wdev,
enum nl80211_tx_power_setting type, s32 mbm)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
s32 disable;
u32 qdbm = 127;
brcmf_dbg(TRACE, "Enter %d %d\n", type, mbm);
if (!check_vif_up(ifp->vif))
return -EIO;
switch (type) {
case NL80211_TX_POWER_AUTOMATIC:
break;
case NL80211_TX_POWER_LIMITED:
case NL80211_TX_POWER_FIXED:
if (mbm < 0) {
brcmf_err("TX_POWER_FIXED - dbm is negative\n");
err = -EINVAL;
goto done;
}
qdbm = MBM_TO_DBM(4 * mbm);
if (qdbm > 127)
qdbm = 127;
qdbm |= WL_TXPWR_OVERRIDE;
break;
default:
brcmf_err("Unsupported type %d\n", type);
err = -EINVAL;
goto done;
}
/* Make sure radio is off or on as far as software is concerned */
disable = WL_RADIO_SW_DISABLE << 16;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_RADIO, disable);
if (err)
brcmf_err("WLC_SET_RADIO error (%d)\n", err);
err = brcmf_fil_iovar_int_set(ifp, "qtxpower", qdbm);
if (err)
brcmf_err("qtxpower error (%d)\n", err);
done:
brcmf_dbg(TRACE, "Exit %d (qdbm)\n", qdbm & ~WL_TXPWR_OVERRIDE);
return err;
}
static s32
brcmf_cfg80211_get_tx_power(struct wiphy *wiphy, struct wireless_dev *wdev,
s32 *dbm)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(ndev);
s32 qdbm = 0;
s32 err;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
err = brcmf_fil_iovar_int_get(ifp, "qtxpower", &qdbm);
if (err) {
brcmf_err("error (%d)\n", err);
goto done;
}
*dbm = (qdbm & ~WL_TXPWR_OVERRIDE) / 4;
done:
brcmf_dbg(TRACE, "Exit (0x%x %d)\n", qdbm, *dbm);
return err;
}
static s32
brcmf_cfg80211_config_default_key(struct wiphy *wiphy, struct net_device *ndev,
u8 key_idx, bool unicast, bool multicast)
{
struct brcmf_if *ifp = netdev_priv(ndev);
u32 index;
u32 wsec;
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
brcmf_dbg(CONN, "key index (%d)\n", key_idx);
if (!check_vif_up(ifp->vif))
return -EIO;
err = brcmf_fil_bsscfg_int_get(ifp, "wsec", &wsec);
if (err) {
brcmf_err("WLC_GET_WSEC error (%d)\n", err);
goto done;
}
if (wsec & WEP_ENABLED) {
/* Just select a new current key */
index = key_idx;
err = brcmf_fil_cmd_int_set(ifp,
BRCMF_C_SET_KEY_PRIMARY, index);
if (err)
brcmf_err("error (%d)\n", err);
}
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_del_key(struct wiphy *wiphy, struct net_device *ndev,
u8 key_idx, bool pairwise, const u8 *mac_addr)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_wsec_key *key;
s32 err;
brcmf_dbg(TRACE, "Enter\n");
brcmf_dbg(CONN, "key index (%d)\n", key_idx);
if (!check_vif_up(ifp->vif))
return -EIO;
if (key_idx >= BRCMF_MAX_DEFAULT_KEYS) {
/* we ignore this key index in this case */
return -EINVAL;
}
key = &ifp->vif->profile.key[key_idx];
if (key->algo == CRYPTO_ALGO_OFF) {
brcmf_dbg(CONN, "Ignore clearing of (never configured) key\n");
return -EINVAL;
}
memset(key, 0, sizeof(*key));
key->index = (u32)key_idx;
key->flags = BRCMF_PRIMARY_KEY;
/* Clear the key/index */
err = send_key_to_dongle(ifp, key);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_add_key(struct wiphy *wiphy, struct net_device *ndev,
u8 key_idx, bool pairwise, const u8 *mac_addr,
struct key_params *params)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_wsec_key *key;
s32 val;
s32 wsec;
s32 err;
u8 keybuf[8];
bool ext_key;
brcmf_dbg(TRACE, "Enter\n");
brcmf_dbg(CONN, "key index (%d)\n", key_idx);
if (!check_vif_up(ifp->vif))
return -EIO;
if (key_idx >= BRCMF_MAX_DEFAULT_KEYS) {
/* we ignore this key index in this case */
brcmf_err("invalid key index (%d)\n", key_idx);
return -EINVAL;
}
if (params->key_len == 0)
return brcmf_cfg80211_del_key(wiphy, ndev, key_idx, pairwise,
mac_addr);
if (params->key_len > sizeof(key->data)) {
brcmf_err("Too long key length (%u)\n", params->key_len);
return -EINVAL;
}
ext_key = false;
if (mac_addr && (params->cipher != WLAN_CIPHER_SUITE_WEP40) &&
(params->cipher != WLAN_CIPHER_SUITE_WEP104)) {
brcmf_dbg(TRACE, "Ext key, mac %pM", mac_addr);
ext_key = true;
}
key = &ifp->vif->profile.key[key_idx];
memset(key, 0, sizeof(*key));
if ((ext_key) && (!is_multicast_ether_addr(mac_addr)))
memcpy((char *)&key->ea, (void *)mac_addr, ETH_ALEN);
key->len = params->key_len;
key->index = key_idx;
memcpy(key->data, params->key, key->len);
if (!ext_key)
key->flags = BRCMF_PRIMARY_KEY;
switch (params->cipher) {
case WLAN_CIPHER_SUITE_WEP40:
key->algo = CRYPTO_ALGO_WEP1;
val = WEP_ENABLED;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_WEP40\n");
break;
case WLAN_CIPHER_SUITE_WEP104:
key->algo = CRYPTO_ALGO_WEP128;
val = WEP_ENABLED;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_WEP104\n");
break;
case WLAN_CIPHER_SUITE_TKIP:
if (!brcmf_is_apmode(ifp->vif)) {
brcmf_dbg(CONN, "Swapping RX/TX MIC key\n");
memcpy(keybuf, &key->data[24], sizeof(keybuf));
memcpy(&key->data[24], &key->data[16], sizeof(keybuf));
memcpy(&key->data[16], keybuf, sizeof(keybuf));
}
key->algo = CRYPTO_ALGO_TKIP;
val = TKIP_ENABLED;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_TKIP\n");
break;
case WLAN_CIPHER_SUITE_AES_CMAC:
key->algo = CRYPTO_ALGO_AES_CCM;
val = AES_ENABLED;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_AES_CMAC\n");
break;
case WLAN_CIPHER_SUITE_CCMP:
key->algo = CRYPTO_ALGO_AES_CCM;
val = AES_ENABLED;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_CCMP\n");
break;
default:
brcmf_err("Invalid cipher (0x%x)\n", params->cipher);
err = -EINVAL;
goto done;
}
err = send_key_to_dongle(ifp, key);
if (ext_key || err)
goto done;
err = brcmf_fil_bsscfg_int_get(ifp, "wsec", &wsec);
if (err) {
brcmf_err("get wsec error (%d)\n", err);
goto done;
}
wsec |= val;
err = brcmf_fil_bsscfg_int_set(ifp, "wsec", wsec);
if (err) {
brcmf_err("set wsec error (%d)\n", err);
goto done;
}
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_get_key(struct wiphy *wiphy, struct net_device *ndev, u8 key_idx,
bool pairwise, const u8 *mac_addr, void *cookie,
void (*callback)(void *cookie,
struct key_params *params))
{
struct key_params params;
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct brcmf_cfg80211_security *sec;
s32 wsec;
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
brcmf_dbg(CONN, "key index (%d)\n", key_idx);
if (!check_vif_up(ifp->vif))
return -EIO;
memset(¶ms, 0, sizeof(params));
err = brcmf_fil_bsscfg_int_get(ifp, "wsec", &wsec);
if (err) {
brcmf_err("WLC_GET_WSEC error (%d)\n", err);
/* Ignore this error, may happen during DISASSOC */
err = -EAGAIN;
goto done;
}
if (wsec & WEP_ENABLED) {
sec = &profile->sec;
if (sec->cipher_pairwise & WLAN_CIPHER_SUITE_WEP40) {
params.cipher = WLAN_CIPHER_SUITE_WEP40;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_WEP40\n");
} else if (sec->cipher_pairwise & WLAN_CIPHER_SUITE_WEP104) {
params.cipher = WLAN_CIPHER_SUITE_WEP104;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_WEP104\n");
}
} else if (wsec & TKIP_ENABLED) {
params.cipher = WLAN_CIPHER_SUITE_TKIP;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_TKIP\n");
} else if (wsec & AES_ENABLED) {
params.cipher = WLAN_CIPHER_SUITE_AES_CMAC;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_AES_CMAC\n");
} else {
brcmf_err("Invalid algo (0x%x)\n", wsec);
err = -EINVAL;
goto done;
}
callback(cookie, ¶ms);
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_config_default_mgmt_key(struct wiphy *wiphy,
struct net_device *ndev, u8 key_idx)
{
struct brcmf_if *ifp = netdev_priv(ndev);
brcmf_dbg(TRACE, "Enter key_idx %d\n", key_idx);
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP))
return 0;
brcmf_dbg(INFO, "Not supported\n");
return -EOPNOTSUPP;
}
static void
brcmf_cfg80211_reconfigure_wep(struct brcmf_if *ifp)
{
s32 err;
u8 key_idx;
struct brcmf_wsec_key *key;
s32 wsec;
for (key_idx = 0; key_idx < BRCMF_MAX_DEFAULT_KEYS; key_idx++) {
key = &ifp->vif->profile.key[key_idx];
if ((key->algo == CRYPTO_ALGO_WEP1) ||
(key->algo == CRYPTO_ALGO_WEP128))
break;
}
if (key_idx == BRCMF_MAX_DEFAULT_KEYS)
return;
err = send_key_to_dongle(ifp, key);
if (err) {
brcmf_err("Setting WEP key failed (%d)\n", err);
return;
}
err = brcmf_fil_bsscfg_int_get(ifp, "wsec", &wsec);
if (err) {
brcmf_err("get wsec error (%d)\n", err);
return;
}
wsec |= WEP_ENABLED;
err = brcmf_fil_bsscfg_int_set(ifp, "wsec", wsec);
if (err)
brcmf_err("set wsec error (%d)\n", err);
}
static void brcmf_convert_sta_flags(u32 fw_sta_flags, struct station_info *si)
{
struct nl80211_sta_flag_update *sfu;
brcmf_dbg(TRACE, "flags %08x\n", fw_sta_flags);
si->filled |= BIT(NL80211_STA_INFO_STA_FLAGS);
sfu = &si->sta_flags;
sfu->mask = BIT(NL80211_STA_FLAG_WME) |
BIT(NL80211_STA_FLAG_AUTHENTICATED) |
BIT(NL80211_STA_FLAG_ASSOCIATED) |
BIT(NL80211_STA_FLAG_AUTHORIZED);
if (fw_sta_flags & BRCMF_STA_WME)
sfu->set |= BIT(NL80211_STA_FLAG_WME);
if (fw_sta_flags & BRCMF_STA_AUTHE)
sfu->set |= BIT(NL80211_STA_FLAG_AUTHENTICATED);
if (fw_sta_flags & BRCMF_STA_ASSOC)
sfu->set |= BIT(NL80211_STA_FLAG_ASSOCIATED);
if (fw_sta_flags & BRCMF_STA_AUTHO)
sfu->set |= BIT(NL80211_STA_FLAG_AUTHORIZED);
}
static void brcmf_fill_bss_param(struct brcmf_if *ifp, struct station_info *si)
{
struct {
__le32 len;
struct brcmf_bss_info_le bss_le;
} *buf;
u16 capability;
int err;
buf = kzalloc(WL_BSS_INFO_MAX, GFP_KERNEL);
if (!buf)
return;
buf->len = cpu_to_le32(WL_BSS_INFO_MAX);
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_BSS_INFO, buf,
WL_BSS_INFO_MAX);
if (err) {
brcmf_err("Failed to get bss info (%d)\n", err);
return;
}
si->filled |= BIT(NL80211_STA_INFO_BSS_PARAM);
si->bss_param.beacon_interval = le16_to_cpu(buf->bss_le.beacon_period);
si->bss_param.dtim_period = buf->bss_le.dtim_period;
capability = le16_to_cpu(buf->bss_le.capability);
if (capability & IEEE80211_HT_STBC_PARAM_DUAL_CTS_PROT)
si->bss_param.flags |= BSS_PARAM_FLAGS_CTS_PROT;
if (capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
si->bss_param.flags |= BSS_PARAM_FLAGS_SHORT_PREAMBLE;
if (capability & WLAN_CAPABILITY_SHORT_SLOT_TIME)
si->bss_param.flags |= BSS_PARAM_FLAGS_SHORT_SLOT_TIME;
}
static s32
brcmf_cfg80211_get_station_ibss(struct brcmf_if *ifp,
struct station_info *sinfo)
{
struct brcmf_scb_val_le scbval;
struct brcmf_pktcnt_le pktcnt;
s32 err;
u32 rate;
u32 rssi;
/* Get the current tx rate */
err = brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_RATE, &rate);
if (err < 0) {
brcmf_err("BRCMF_C_GET_RATE error (%d)\n", err);
return err;
}
sinfo->filled |= BIT(NL80211_STA_INFO_TX_BITRATE);
sinfo->txrate.legacy = rate * 5;
memset(&scbval, 0, sizeof(scbval));
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_RSSI, &scbval,
sizeof(scbval));
if (err) {
brcmf_err("BRCMF_C_GET_RSSI error (%d)\n", err);
return err;
}
rssi = le32_to_cpu(scbval.val);
sinfo->filled |= BIT(NL80211_STA_INFO_SIGNAL);
sinfo->signal = rssi;
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_GET_PKTCNTS, &pktcnt,
sizeof(pktcnt));
if (err) {
brcmf_err("BRCMF_C_GET_GET_PKTCNTS error (%d)\n", err);
return err;
}
sinfo->filled |= BIT(NL80211_STA_INFO_RX_PACKETS) |
BIT(NL80211_STA_INFO_RX_DROP_MISC) |
BIT(NL80211_STA_INFO_TX_PACKETS) |
BIT(NL80211_STA_INFO_TX_FAILED);
sinfo->rx_packets = le32_to_cpu(pktcnt.rx_good_pkt);
sinfo->rx_dropped_misc = le32_to_cpu(pktcnt.rx_bad_pkt);
sinfo->tx_packets = le32_to_cpu(pktcnt.tx_good_pkt);
sinfo->tx_failed = le32_to_cpu(pktcnt.tx_bad_pkt);
return 0;
}
static s32
brcmf_cfg80211_get_station(struct wiphy *wiphy, struct net_device *ndev,
const u8 *mac, struct station_info *sinfo)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_scb_val_le scb_val;
s32 err = 0;
struct brcmf_sta_info_le sta_info_le;
u32 sta_flags;
u32 is_tdls_peer;
s32 total_rssi;
s32 count_rssi;
int rssi;
u32 i;
brcmf_dbg(TRACE, "Enter, MAC %pM\n", mac);
if (!check_vif_up(ifp->vif))
return -EIO;
if (brcmf_is_ibssmode(ifp->vif))
return brcmf_cfg80211_get_station_ibss(ifp, sinfo);
memset(&sta_info_le, 0, sizeof(sta_info_le));
memcpy(&sta_info_le, mac, ETH_ALEN);
err = brcmf_fil_iovar_data_get(ifp, "tdls_sta_info",
&sta_info_le,
sizeof(sta_info_le));
is_tdls_peer = !err;
if (err) {
err = brcmf_fil_iovar_data_get(ifp, "sta_info",
&sta_info_le,
sizeof(sta_info_le));
if (err < 0) {
brcmf_err("GET STA INFO failed, %d\n", err);
goto done;
}
}
brcmf_dbg(TRACE, "version %d\n", le16_to_cpu(sta_info_le.ver));
sinfo->filled = BIT(NL80211_STA_INFO_INACTIVE_TIME);
sinfo->inactive_time = le32_to_cpu(sta_info_le.idle) * 1000;
sta_flags = le32_to_cpu(sta_info_le.flags);
brcmf_convert_sta_flags(sta_flags, sinfo);
sinfo->sta_flags.mask |= BIT(NL80211_STA_FLAG_TDLS_PEER);
if (is_tdls_peer)
sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_TDLS_PEER);
else
sinfo->sta_flags.set &= ~BIT(NL80211_STA_FLAG_TDLS_PEER);
if (sta_flags & BRCMF_STA_ASSOC) {
sinfo->filled |= BIT(NL80211_STA_INFO_CONNECTED_TIME);
sinfo->connected_time = le32_to_cpu(sta_info_le.in);
brcmf_fill_bss_param(ifp, sinfo);
}
if (sta_flags & BRCMF_STA_SCBSTATS) {
sinfo->filled |= BIT(NL80211_STA_INFO_TX_FAILED);
sinfo->tx_failed = le32_to_cpu(sta_info_le.tx_failures);
sinfo->filled |= BIT(NL80211_STA_INFO_TX_PACKETS);
sinfo->tx_packets = le32_to_cpu(sta_info_le.tx_pkts);
sinfo->tx_packets += le32_to_cpu(sta_info_le.tx_mcast_pkts);
sinfo->filled |= BIT(NL80211_STA_INFO_RX_PACKETS);
sinfo->rx_packets = le32_to_cpu(sta_info_le.rx_ucast_pkts);
sinfo->rx_packets += le32_to_cpu(sta_info_le.rx_mcast_pkts);
if (sinfo->tx_packets) {
sinfo->filled |= BIT(NL80211_STA_INFO_TX_BITRATE);
sinfo->txrate.legacy =
le32_to_cpu(sta_info_le.tx_rate) / 100;
}
if (sinfo->rx_packets) {
sinfo->filled |= BIT(NL80211_STA_INFO_RX_BITRATE);
sinfo->rxrate.legacy =
le32_to_cpu(sta_info_le.rx_rate) / 100;
}
if (le16_to_cpu(sta_info_le.ver) >= 4) {
sinfo->filled |= BIT(NL80211_STA_INFO_TX_BYTES);
sinfo->tx_bytes = le64_to_cpu(sta_info_le.tx_tot_bytes);
sinfo->filled |= BIT(NL80211_STA_INFO_RX_BYTES);
sinfo->rx_bytes = le64_to_cpu(sta_info_le.rx_tot_bytes);
}
total_rssi = 0;
count_rssi = 0;
for (i = 0; i < BRCMF_ANT_MAX; i++) {
if (sta_info_le.rssi[i]) {
sinfo->chain_signal_avg[count_rssi] =
sta_info_le.rssi[i];
sinfo->chain_signal[count_rssi] =
sta_info_le.rssi[i];
total_rssi += sta_info_le.rssi[i];
count_rssi++;
}
}
if (count_rssi) {
sinfo->filled |= BIT(NL80211_STA_INFO_CHAIN_SIGNAL);
sinfo->chains = count_rssi;
sinfo->filled |= BIT(NL80211_STA_INFO_SIGNAL);
total_rssi /= count_rssi;
sinfo->signal = total_rssi;
} else if (test_bit(BRCMF_VIF_STATUS_CONNECTED,
&ifp->vif->sme_state)) {
memset(&scb_val, 0, sizeof(scb_val));
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_RSSI,
&scb_val, sizeof(scb_val));
if (err) {
brcmf_err("Could not get rssi (%d)\n", err);
goto done;
} else {
rssi = le32_to_cpu(scb_val.val);
sinfo->filled |= BIT(NL80211_STA_INFO_SIGNAL);
sinfo->signal = rssi;
brcmf_dbg(CONN, "RSSI %d dBm\n", rssi);
}
}
}
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static int
brcmf_cfg80211_dump_station(struct wiphy *wiphy, struct net_device *ndev,
int idx, u8 *mac, struct station_info *sinfo)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
brcmf_dbg(TRACE, "Enter, idx %d\n", idx);
if (idx == 0) {
cfg->assoclist.count = cpu_to_le32(BRCMF_MAX_ASSOCLIST);
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_ASSOCLIST,
&cfg->assoclist,
sizeof(cfg->assoclist));
if (err) {
brcmf_err("BRCMF_C_GET_ASSOCLIST unsupported, err=%d\n",
err);
cfg->assoclist.count = 0;
return -EOPNOTSUPP;
}
}
if (idx < le32_to_cpu(cfg->assoclist.count)) {
memcpy(mac, cfg->assoclist.mac[idx], ETH_ALEN);
return brcmf_cfg80211_get_station(wiphy, ndev, mac, sinfo);
}
return -ENOENT;
}
static s32
brcmf_cfg80211_set_power_mgmt(struct wiphy *wiphy, struct net_device *ndev,
bool enabled, s32 timeout)
{
s32 pm;
s32 err = 0;
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
brcmf_dbg(TRACE, "Enter\n");
/*
* Powersave enable/disable request is coming from the
* cfg80211 even before the interface is up. In that
* scenario, driver will be storing the power save
* preference in cfg struct to apply this to
* FW later while initializing the dongle
*/
cfg->pwr_save = enabled;
if (!check_vif_up(ifp->vif)) {
brcmf_dbg(INFO, "Device is not ready, storing the value in cfg_info struct\n");
goto done;
}
pm = enabled ? PM_FAST : PM_OFF;
/* Do not enable the power save after assoc if it is a p2p interface */
if (ifp->vif->wdev.iftype == NL80211_IFTYPE_P2P_CLIENT) {
brcmf_dbg(INFO, "Do not enable power save for P2P clients\n");
pm = PM_OFF;
}
brcmf_dbg(INFO, "power save %s\n", (pm ? "enabled" : "disabled"));
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PM, pm);
if (err) {
if (err == -ENODEV)
brcmf_err("net_device is not ready yet\n");
else
brcmf_err("error (%d)\n", err);
}
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32 brcmf_inform_single_bss(struct brcmf_cfg80211_info *cfg,
struct brcmf_bss_info_le *bi)
{
struct wiphy *wiphy = cfg_to_wiphy(cfg);
struct ieee80211_channel *notify_channel;
struct cfg80211_bss *bss;
struct ieee80211_supported_band *band;
struct brcmu_chan ch;
u16 channel;
u32 freq;
u16 notify_capability;
u16 notify_interval;
u8 *notify_ie;
size_t notify_ielen;
s32 notify_signal;
if (le32_to_cpu(bi->length) > WL_BSS_INFO_MAX) {
brcmf_err("Bss info is larger than buffer. Discarding\n");
return 0;
}
if (!bi->ctl_ch) {
ch.chspec = le16_to_cpu(bi->chanspec);
cfg->d11inf.decchspec(&ch);
bi->ctl_ch = ch.control_ch_num;
}
channel = bi->ctl_ch;
if (channel <= CH_MAX_2G_CHANNEL)
band = wiphy->bands[NL80211_BAND_2GHZ];
else
band = wiphy->bands[NL80211_BAND_5GHZ];
freq = ieee80211_channel_to_frequency(channel, band->band);
notify_channel = ieee80211_get_channel(wiphy, freq);
notify_capability = le16_to_cpu(bi->capability);
notify_interval = le16_to_cpu(bi->beacon_period);
notify_ie = (u8 *)bi + le16_to_cpu(bi->ie_offset);
notify_ielen = le32_to_cpu(bi->ie_length);
notify_signal = (s16)le16_to_cpu(bi->RSSI) * 100;
brcmf_dbg(CONN, "bssid: %pM\n", bi->BSSID);
brcmf_dbg(CONN, "Channel: %d(%d)\n", channel, freq);
brcmf_dbg(CONN, "Capability: %X\n", notify_capability);
brcmf_dbg(CONN, "Beacon interval: %d\n", notify_interval);
brcmf_dbg(CONN, "Signal: %d\n", notify_signal);
bss = cfg80211_inform_bss(wiphy, notify_channel,
CFG80211_BSS_FTYPE_UNKNOWN,
(const u8 *)bi->BSSID,
0, notify_capability,
notify_interval, notify_ie,
notify_ielen, notify_signal,
GFP_KERNEL);
if (!bss)
return -ENOMEM;
cfg80211_put_bss(wiphy, bss);
return 0;
}
static struct brcmf_bss_info_le *
next_bss_le(struct brcmf_scan_results *list, struct brcmf_bss_info_le *bss)
{
if (bss == NULL)
return list->bss_info_le;
return (struct brcmf_bss_info_le *)((unsigned long)bss +
le32_to_cpu(bss->length));
}
static s32 brcmf_inform_bss(struct brcmf_cfg80211_info *cfg)
{
struct brcmf_scan_results *bss_list;
struct brcmf_bss_info_le *bi = NULL; /* must be initialized */
s32 err = 0;
int i;
bss_list = (struct brcmf_scan_results *)cfg->escan_info.escan_buf;
if (bss_list->count != 0 &&
bss_list->version != BRCMF_BSS_INFO_VERSION) {
brcmf_err("Version %d != WL_BSS_INFO_VERSION\n",
bss_list->version);
return -EOPNOTSUPP;
}
brcmf_dbg(SCAN, "scanned AP count (%d)\n", bss_list->count);
for (i = 0; i < bss_list->count; i++) {
bi = next_bss_le(bss_list, bi);
err = brcmf_inform_single_bss(cfg, bi);
if (err)
break;
}
return err;
}
static s32 brcmf_inform_ibss(struct brcmf_cfg80211_info *cfg,
struct net_device *ndev, const u8 *bssid)
{
struct wiphy *wiphy = cfg_to_wiphy(cfg);
struct ieee80211_channel *notify_channel;
struct brcmf_bss_info_le *bi = NULL;
struct ieee80211_supported_band *band;
struct cfg80211_bss *bss;
struct brcmu_chan ch;
u8 *buf = NULL;
s32 err = 0;
u32 freq;
u16 notify_capability;
u16 notify_interval;
u8 *notify_ie;
size_t notify_ielen;
s32 notify_signal;
brcmf_dbg(TRACE, "Enter\n");
buf = kzalloc(WL_BSS_INFO_MAX, GFP_KERNEL);
if (buf == NULL) {
err = -ENOMEM;
goto CleanUp;
}
*(__le32 *)buf = cpu_to_le32(WL_BSS_INFO_MAX);
err = brcmf_fil_cmd_data_get(netdev_priv(ndev), BRCMF_C_GET_BSS_INFO,
buf, WL_BSS_INFO_MAX);
if (err) {
brcmf_err("WLC_GET_BSS_INFO failed: %d\n", err);
goto CleanUp;
}
bi = (struct brcmf_bss_info_le *)(buf + 4);
ch.chspec = le16_to_cpu(bi->chanspec);
cfg->d11inf.decchspec(&ch);
if (ch.band == BRCMU_CHAN_BAND_2G)
band = wiphy->bands[NL80211_BAND_2GHZ];
else
band = wiphy->bands[NL80211_BAND_5GHZ];
freq = ieee80211_channel_to_frequency(ch.control_ch_num, band->band);
cfg->channel = freq;
notify_channel = ieee80211_get_channel(wiphy, freq);
notify_capability = le16_to_cpu(bi->capability);
notify_interval = le16_to_cpu(bi->beacon_period);
notify_ie = (u8 *)bi + le16_to_cpu(bi->ie_offset);
notify_ielen = le32_to_cpu(bi->ie_length);
notify_signal = (s16)le16_to_cpu(bi->RSSI) * 100;
brcmf_dbg(CONN, "channel: %d(%d)\n", ch.control_ch_num, freq);
brcmf_dbg(CONN, "capability: %X\n", notify_capability);
brcmf_dbg(CONN, "beacon interval: %d\n", notify_interval);
brcmf_dbg(CONN, "signal: %d\n", notify_signal);
bss = cfg80211_inform_bss(wiphy, notify_channel,
CFG80211_BSS_FTYPE_UNKNOWN, bssid, 0,
notify_capability, notify_interval,
notify_ie, notify_ielen, notify_signal,
GFP_KERNEL);
if (!bss) {
err = -ENOMEM;
goto CleanUp;
}
cfg80211_put_bss(wiphy, bss);
CleanUp:
kfree(buf);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32 brcmf_update_bss_info(struct brcmf_cfg80211_info *cfg,
struct brcmf_if *ifp)
{
struct brcmf_bss_info_le *bi;
const struct brcmf_tlv *tim;
u16 beacon_interval;
u8 dtim_period;
size_t ie_len;
u8 *ie;
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
if (brcmf_is_ibssmode(ifp->vif))
return err;
*(__le32 *)cfg->extra_buf = cpu_to_le32(WL_EXTRA_BUF_MAX);
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_BSS_INFO,
cfg->extra_buf, WL_EXTRA_BUF_MAX);
if (err) {
brcmf_err("Could not get bss info %d\n", err);
goto update_bss_info_out;
}
bi = (struct brcmf_bss_info_le *)(cfg->extra_buf + 4);
err = brcmf_inform_single_bss(cfg, bi);
if (err)
goto update_bss_info_out;
ie = ((u8 *)bi) + le16_to_cpu(bi->ie_offset);
ie_len = le32_to_cpu(bi->ie_length);
beacon_interval = le16_to_cpu(bi->beacon_period);
tim = brcmf_parse_tlvs(ie, ie_len, WLAN_EID_TIM);
if (tim)
dtim_period = tim->data[1];
else {
/*
* active scan was done so we could not get dtim
* information out of probe response.
* so we speficially query dtim information to dongle.
*/
u32 var;
err = brcmf_fil_iovar_int_get(ifp, "dtim_assoc", &var);
if (err) {
brcmf_err("wl dtim_assoc failed (%d)\n", err);
goto update_bss_info_out;
}
dtim_period = (u8)var;
}
update_bss_info_out:
brcmf_dbg(TRACE, "Exit");
return err;
}
void brcmf_abort_scanning(struct brcmf_cfg80211_info *cfg)
{
struct escan_info *escan = &cfg->escan_info;
set_bit(BRCMF_SCAN_STATUS_ABORT, &cfg->scan_status);
if (cfg->scan_request) {
escan->escan_state = WL_ESCAN_STATE_IDLE;
brcmf_notify_escan_complete(cfg, escan->ifp, true, true);
}
clear_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status);
clear_bit(BRCMF_SCAN_STATUS_ABORT, &cfg->scan_status);
}
static void brcmf_cfg80211_escan_timeout_worker(struct work_struct *work)
{
struct brcmf_cfg80211_info *cfg =
container_of(work, struct brcmf_cfg80211_info,
escan_timeout_work);
brcmf_inform_bss(cfg);
brcmf_notify_escan_complete(cfg, cfg->escan_info.ifp, true, true);
}
static void brcmf_escan_timeout(unsigned long data)
{
struct brcmf_cfg80211_info *cfg =
(struct brcmf_cfg80211_info *)data;
if (cfg->scan_request) {
brcmf_err("timer expired\n");
schedule_work(&cfg->escan_timeout_work);
}
}
static s32
brcmf_compare_update_same_bss(struct brcmf_cfg80211_info *cfg,
struct brcmf_bss_info_le *bss,
struct brcmf_bss_info_le *bss_info_le)
{
struct brcmu_chan ch_bss, ch_bss_info_le;
ch_bss.chspec = le16_to_cpu(bss->chanspec);
cfg->d11inf.decchspec(&ch_bss);
ch_bss_info_le.chspec = le16_to_cpu(bss_info_le->chanspec);
cfg->d11inf.decchspec(&ch_bss_info_le);
if (!memcmp(&bss_info_le->BSSID, &bss->BSSID, ETH_ALEN) &&
ch_bss.band == ch_bss_info_le.band &&
bss_info_le->SSID_len == bss->SSID_len &&
!memcmp(bss_info_le->SSID, bss->SSID, bss_info_le->SSID_len)) {
if ((bss->flags & BRCMF_BSS_RSSI_ON_CHANNEL) ==
(bss_info_le->flags & BRCMF_BSS_RSSI_ON_CHANNEL)) {
s16 bss_rssi = le16_to_cpu(bss->RSSI);
s16 bss_info_rssi = le16_to_cpu(bss_info_le->RSSI);
/* preserve max RSSI if the measurements are
* both on-channel or both off-channel
*/
if (bss_info_rssi > bss_rssi)
bss->RSSI = bss_info_le->RSSI;
} else if ((bss->flags & BRCMF_BSS_RSSI_ON_CHANNEL) &&
(bss_info_le->flags & BRCMF_BSS_RSSI_ON_CHANNEL) == 0) {
/* preserve the on-channel rssi measurement
* if the new measurement is off channel
*/
bss->RSSI = bss_info_le->RSSI;
bss->flags |= BRCMF_BSS_RSSI_ON_CHANNEL;
}
return 1;
}
return 0;
}
static s32
brcmf_cfg80211_escan_handler(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
s32 status;
struct brcmf_escan_result_le *escan_result_le;
struct brcmf_bss_info_le *bss_info_le;
struct brcmf_bss_info_le *bss = NULL;
u32 bi_length;
struct brcmf_scan_results *list;
u32 i;
bool aborted;
status = e->status;
if (!test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status)) {
brcmf_err("scan not ready, bsscfgidx=%d\n", ifp->bsscfgidx);
return -EPERM;
}
if (status == BRCMF_E_STATUS_PARTIAL) {
brcmf_dbg(SCAN, "ESCAN Partial result\n");
escan_result_le = (struct brcmf_escan_result_le *) data;
if (!escan_result_le) {
brcmf_err("Invalid escan result (NULL pointer)\n");
goto exit;
}
if (le16_to_cpu(escan_result_le->bss_count) != 1) {
brcmf_err("Invalid bss_count %d: ignoring\n",
escan_result_le->bss_count);
goto exit;
}
bss_info_le = &escan_result_le->bss_info_le;
if (brcmf_p2p_scan_finding_common_channel(cfg, bss_info_le))
goto exit;
if (!cfg->scan_request) {
brcmf_dbg(SCAN, "result without cfg80211 request\n");
goto exit;
}
bi_length = le32_to_cpu(bss_info_le->length);
if (bi_length != (le32_to_cpu(escan_result_le->buflen) -
WL_ESCAN_RESULTS_FIXED_SIZE)) {
brcmf_err("Invalid bss_info length %d: ignoring\n",
bi_length);
goto exit;
}
if (!(cfg_to_wiphy(cfg)->interface_modes &
BIT(NL80211_IFTYPE_ADHOC))) {
if (le16_to_cpu(bss_info_le->capability) &
WLAN_CAPABILITY_IBSS) {
brcmf_err("Ignoring IBSS result\n");
goto exit;
}
}
list = (struct brcmf_scan_results *)
cfg->escan_info.escan_buf;
if (bi_length > BRCMF_ESCAN_BUF_SIZE - list->buflen) {
brcmf_err("Buffer is too small: ignoring\n");
goto exit;
}
for (i = 0; i < list->count; i++) {
bss = bss ? (struct brcmf_bss_info_le *)
((unsigned char *)bss +
le32_to_cpu(bss->length)) : list->bss_info_le;
if (brcmf_compare_update_same_bss(cfg, bss,
bss_info_le))
goto exit;
}
memcpy(&cfg->escan_info.escan_buf[list->buflen], bss_info_le,
bi_length);
list->version = le32_to_cpu(bss_info_le->version);
list->buflen += bi_length;
list->count++;
} else {
cfg->escan_info.escan_state = WL_ESCAN_STATE_IDLE;
if (brcmf_p2p_scan_finding_common_channel(cfg, NULL))
goto exit;
if (cfg->scan_request) {
brcmf_inform_bss(cfg);
aborted = status != BRCMF_E_STATUS_SUCCESS;
brcmf_notify_escan_complete(cfg, ifp, aborted, false);
} else
brcmf_dbg(SCAN, "Ignored scan complete result 0x%x\n",
status);
}
exit:
return 0;
}
static void brcmf_init_escan(struct brcmf_cfg80211_info *cfg)
{
brcmf_fweh_register(cfg->pub, BRCMF_E_ESCAN_RESULT,
brcmf_cfg80211_escan_handler);
cfg->escan_info.escan_state = WL_ESCAN_STATE_IDLE;
/* Init scan_timeout timer */
init_timer(&cfg->escan_timeout);
cfg->escan_timeout.data = (unsigned long) cfg;
cfg->escan_timeout.function = brcmf_escan_timeout;
INIT_WORK(&cfg->escan_timeout_work,
brcmf_cfg80211_escan_timeout_worker);
}
/* PFN result doesn't have all the info which are required by the supplicant
* (For e.g IEs) Do a target Escan so that sched scan results are reported
* via wl_inform_single_bss in the required format. Escan does require the
* scan request in the form of cfg80211_scan_request. For timebeing, create
* cfg80211_scan_request one out of the received PNO event.
*/
static s32
brcmf_notify_sched_scan_results(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct brcmf_pno_net_info_le *netinfo, *netinfo_start;
struct cfg80211_scan_request *request = NULL;
struct cfg80211_ssid *ssid = NULL;
struct ieee80211_channel *channel = NULL;
struct wiphy *wiphy = cfg_to_wiphy(cfg);
int err = 0;
int channel_req = 0;
int band = 0;
struct brcmf_pno_scanresults_le *pfn_result;
u32 result_count;
u32 status;
brcmf_dbg(SCAN, "Enter\n");
if (e->datalen < (sizeof(*pfn_result) + sizeof(*netinfo))) {
brcmf_dbg(SCAN, "Event data to small. Ignore\n");
return 0;
}
if (e->event_code == BRCMF_E_PFN_NET_LOST) {
brcmf_dbg(SCAN, "PFN NET LOST event. Do Nothing\n");
return 0;
}
pfn_result = (struct brcmf_pno_scanresults_le *)data;
result_count = le32_to_cpu(pfn_result->count);
status = le32_to_cpu(pfn_result->status);
/* PFN event is limited to fit 512 bytes so we may get
* multiple NET_FOUND events. For now place a warning here.
*/
WARN_ON(status != BRCMF_PNO_SCAN_COMPLETE);
brcmf_dbg(SCAN, "PFN NET FOUND event. count: %d\n", result_count);
if (result_count > 0) {
int i;
request = kzalloc(sizeof(*request), GFP_KERNEL);
ssid = kcalloc(result_count, sizeof(*ssid), GFP_KERNEL);
channel = kcalloc(result_count, sizeof(*channel), GFP_KERNEL);
if (!request || !ssid || !channel) {
err = -ENOMEM;
goto out_err;
}
request->wiphy = wiphy;
data += sizeof(struct brcmf_pno_scanresults_le);
netinfo_start = (struct brcmf_pno_net_info_le *)data;
for (i = 0; i < result_count; i++) {
netinfo = &netinfo_start[i];
if (!netinfo) {
brcmf_err("Invalid netinfo ptr. index: %d\n",
i);
err = -EINVAL;
goto out_err;
}
brcmf_dbg(SCAN, "SSID:%s Channel:%d\n",
netinfo->SSID, netinfo->channel);
memcpy(ssid[i].ssid, netinfo->SSID, netinfo->SSID_len);
ssid[i].ssid_len = netinfo->SSID_len;
request->n_ssids++;
channel_req = netinfo->channel;
if (channel_req <= CH_MAX_2G_CHANNEL)
band = NL80211_BAND_2GHZ;
else
band = NL80211_BAND_5GHZ;
channel[i].center_freq =
ieee80211_channel_to_frequency(channel_req,
band);
channel[i].band = band;
channel[i].flags |= IEEE80211_CHAN_NO_HT40;
request->channels[i] = &channel[i];
request->n_channels++;
}
/* assign parsed ssid array */
if (request->n_ssids)
request->ssids = &ssid[0];
if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status)) {
/* Abort any on-going scan */
brcmf_abort_scanning(cfg);
}
set_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status);
cfg->escan_info.run = brcmf_run_escan;
err = brcmf_do_escan(cfg, wiphy, ifp, request);
if (err) {
clear_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status);
goto out_err;
}
cfg->sched_escan = true;
cfg->scan_request = request;
} else {
brcmf_err("FALSE PNO Event. (pfn_count == 0)\n");
goto out_err;
}
kfree(ssid);
kfree(channel);
kfree(request);
return 0;
out_err:
kfree(ssid);
kfree(channel);
kfree(request);
cfg80211_sched_scan_stopped(wiphy);
return err;
}
static int brcmf_dev_pno_clean(struct net_device *ndev)
{
int ret;
/* Disable pfn */
ret = brcmf_fil_iovar_int_set(netdev_priv(ndev), "pfn", 0);
if (ret == 0) {
/* clear pfn */
ret = brcmf_fil_iovar_data_set(netdev_priv(ndev), "pfnclear",
NULL, 0);
}
if (ret < 0)
brcmf_err("failed code %d\n", ret);
return ret;
}
static int brcmf_dev_pno_config(struct brcmf_if *ifp,
struct cfg80211_sched_scan_request *request)
{
struct brcmf_pno_param_le pfn_param;
struct brcmf_pno_macaddr_le pfn_mac;
s32 err;
u8 *mac_mask;
int i;
memset(&pfn_param, 0, sizeof(pfn_param));
pfn_param.version = cpu_to_le32(BRCMF_PNO_VERSION);
/* set extra pno params */
pfn_param.flags = cpu_to_le16(1 << BRCMF_PNO_ENABLE_ADAPTSCAN_BIT);
pfn_param.repeat = BRCMF_PNO_REPEAT;
pfn_param.exp = BRCMF_PNO_FREQ_EXPO_MAX;
/* set up pno scan fr */
pfn_param.scan_freq = cpu_to_le32(BRCMF_PNO_TIME);
err = brcmf_fil_iovar_data_set(ifp, "pfn_set", &pfn_param,
sizeof(pfn_param));
if (err) {
brcmf_err("pfn_set failed, err=%d\n", err);
return err;
}
/* Find out if mac randomization should be turned on */
if (!(request->flags & NL80211_SCAN_FLAG_RANDOM_ADDR))
return 0;
pfn_mac.version = BRCMF_PFN_MACADDR_CFG_VER;
pfn_mac.flags = BRCMF_PFN_MAC_OUI_ONLY | BRCMF_PFN_SET_MAC_UNASSOC;
memcpy(pfn_mac.mac, request->mac_addr, ETH_ALEN);
mac_mask = request->mac_addr_mask;
for (i = 0; i < ETH_ALEN; i++) {
pfn_mac.mac[i] &= mac_mask[i];
pfn_mac.mac[i] |= get_random_int() & ~(mac_mask[i]);
}
/* Clear multi bit */
pfn_mac.mac[0] &= 0xFE;
/* Set locally administered */
pfn_mac.mac[0] |= 0x02;
err = brcmf_fil_iovar_data_set(ifp, "pfn_macaddr", &pfn_mac,
sizeof(pfn_mac));
if (err)
brcmf_err("pfn_macaddr failed, err=%d\n", err);
return err;
}
static int
brcmf_cfg80211_sched_scan_start(struct wiphy *wiphy,
struct net_device *ndev,
struct cfg80211_sched_scan_request *request)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct brcmf_pno_net_param_le pfn;
int i;
int ret = 0;
brcmf_dbg(SCAN, "Enter n_match_sets:%d n_ssids:%d\n",
request->n_match_sets, request->n_ssids);
if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status)) {
brcmf_err("Scanning already: status (%lu)\n", cfg->scan_status);
return -EAGAIN;
}
if (test_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status)) {
brcmf_err("Scanning suppressed: status (%lu)\n",
cfg->scan_status);
return -EAGAIN;
}
if (!request->n_ssids || !request->n_match_sets) {
brcmf_dbg(SCAN, "Invalid sched scan req!! n_ssids:%d\n",
request->n_ssids);
return -EINVAL;
}
if (request->n_ssids > 0) {
for (i = 0; i < request->n_ssids; i++) {
/* Active scan req for ssids */
brcmf_dbg(SCAN, ">>> Active scan req for ssid (%s)\n",
request->ssids[i].ssid);
/* match_set ssids is a supert set of n_ssid list,
* so we need not add these set separately.
*/
}
}
if (request->n_match_sets > 0) {
/* clean up everything */
ret = brcmf_dev_pno_clean(ndev);
if (ret < 0) {
brcmf_err("failed error=%d\n", ret);
return ret;
}
/* configure pno */
if (brcmf_dev_pno_config(ifp, request))
return -EINVAL;
/* configure each match set */
for (i = 0; i < request->n_match_sets; i++) {
struct cfg80211_ssid *ssid;
u32 ssid_len;
ssid = &request->match_sets[i].ssid;
ssid_len = ssid->ssid_len;
if (!ssid_len) {
brcmf_err("skip broadcast ssid\n");
continue;
}
pfn.auth = cpu_to_le32(WLAN_AUTH_OPEN);
pfn.wpa_auth = cpu_to_le32(BRCMF_PNO_WPA_AUTH_ANY);
pfn.wsec = cpu_to_le32(0);
pfn.infra = cpu_to_le32(1);
pfn.flags = cpu_to_le32(1 << BRCMF_PNO_HIDDEN_BIT);
pfn.ssid.SSID_len = cpu_to_le32(ssid_len);
memcpy(pfn.ssid.SSID, ssid->ssid, ssid_len);
ret = brcmf_fil_iovar_data_set(ifp, "pfn_add", &pfn,
sizeof(pfn));
brcmf_dbg(SCAN, ">>> PNO filter %s for ssid (%s)\n",
ret == 0 ? "set" : "failed", ssid->ssid);
}
/* Enable the PNO */
if (brcmf_fil_iovar_int_set(ifp, "pfn", 1) < 0) {
brcmf_err("PNO enable failed!! ret=%d\n", ret);
return -EINVAL;
}
} else {
return -EINVAL;
}
return 0;
}
static int brcmf_cfg80211_sched_scan_stop(struct wiphy *wiphy,
struct net_device *ndev)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
brcmf_dbg(SCAN, "enter\n");
brcmf_dev_pno_clean(ndev);
if (cfg->sched_escan)
brcmf_notify_escan_complete(cfg, netdev_priv(ndev), true, true);
return 0;
}
static __always_inline void brcmf_delay(u32 ms)
{
if (ms < 1000 / HZ) {
cond_resched();
mdelay(ms);
} else {
msleep(ms);
}
}
static s32 brcmf_config_wowl_pattern(struct brcmf_if *ifp, u8 cmd[4],
u8 *pattern, u32 patternsize, u8 *mask,
u32 packet_offset)
{
struct brcmf_fil_wowl_pattern_le *filter;
u32 masksize;
u32 patternoffset;
u8 *buf;
u32 bufsize;
s32 ret;
masksize = (patternsize + 7) / 8;
patternoffset = sizeof(*filter) - sizeof(filter->cmd) + masksize;
bufsize = sizeof(*filter) + patternsize + masksize;
buf = kzalloc(bufsize, GFP_KERNEL);
if (!buf)
return -ENOMEM;
filter = (struct brcmf_fil_wowl_pattern_le *)buf;
memcpy(filter->cmd, cmd, 4);
filter->masksize = cpu_to_le32(masksize);
filter->offset = cpu_to_le32(packet_offset);
filter->patternoffset = cpu_to_le32(patternoffset);
filter->patternsize = cpu_to_le32(patternsize);
filter->type = cpu_to_le32(BRCMF_WOWL_PATTERN_TYPE_BITMAP);
if ((mask) && (masksize))
memcpy(buf + sizeof(*filter), mask, masksize);
if ((pattern) && (patternsize))
memcpy(buf + sizeof(*filter) + masksize, pattern, patternsize);
ret = brcmf_fil_iovar_data_set(ifp, "wowl_pattern", buf, bufsize);
kfree(buf);
return ret;
}
static s32
brcmf_wowl_nd_results(struct brcmf_if *ifp, const struct brcmf_event_msg *e,
void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct brcmf_pno_scanresults_le *pfn_result;
struct brcmf_pno_net_info_le *netinfo;
brcmf_dbg(SCAN, "Enter\n");
if (e->datalen < (sizeof(*pfn_result) + sizeof(*netinfo))) {
brcmf_dbg(SCAN, "Event data to small. Ignore\n");
return 0;
}
pfn_result = (struct brcmf_pno_scanresults_le *)data;
if (e->event_code == BRCMF_E_PFN_NET_LOST) {
brcmf_dbg(SCAN, "PFN NET LOST event. Ignore\n");
return 0;
}
if (le32_to_cpu(pfn_result->count) < 1) {
brcmf_err("Invalid result count, expected 1 (%d)\n",
le32_to_cpu(pfn_result->count));
return -EINVAL;
}
data += sizeof(struct brcmf_pno_scanresults_le);
netinfo = (struct brcmf_pno_net_info_le *)data;
memcpy(cfg->wowl.nd->ssid.ssid, netinfo->SSID, netinfo->SSID_len);
cfg->wowl.nd->ssid.ssid_len = netinfo->SSID_len;
cfg->wowl.nd->n_channels = 1;
cfg->wowl.nd->channels[0] =
ieee80211_channel_to_frequency(netinfo->channel,
netinfo->channel <= CH_MAX_2G_CHANNEL ?
NL80211_BAND_2GHZ : NL80211_BAND_5GHZ);
cfg->wowl.nd_info->n_matches = 1;
cfg->wowl.nd_info->matches[0] = cfg->wowl.nd;
/* Inform (the resume task) that the net detect information was recvd */
cfg->wowl.nd_data_completed = true;
wake_up(&cfg->wowl.nd_data_wait);
return 0;
}
#ifdef CONFIG_PM
static void brcmf_report_wowl_wakeind(struct wiphy *wiphy, struct brcmf_if *ifp)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_wowl_wakeind_le wake_ind_le;
struct cfg80211_wowlan_wakeup wakeup_data;
struct cfg80211_wowlan_wakeup *wakeup;
u32 wakeind;
s32 err;
int timeout;
err = brcmf_fil_iovar_data_get(ifp, "wowl_wakeind", &wake_ind_le,
sizeof(wake_ind_le));
if (err) {
brcmf_err("Get wowl_wakeind failed, err = %d\n", err);
return;
}
wakeind = le32_to_cpu(wake_ind_le.ucode_wakeind);
if (wakeind & (BRCMF_WOWL_MAGIC | BRCMF_WOWL_DIS | BRCMF_WOWL_BCN |
BRCMF_WOWL_RETR | BRCMF_WOWL_NET |
BRCMF_WOWL_PFN_FOUND)) {
wakeup = &wakeup_data;
memset(&wakeup_data, 0, sizeof(wakeup_data));
wakeup_data.pattern_idx = -1;
if (wakeind & BRCMF_WOWL_MAGIC) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_MAGIC\n");
wakeup_data.magic_pkt = true;
}
if (wakeind & BRCMF_WOWL_DIS) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_DIS\n");
wakeup_data.disconnect = true;
}
if (wakeind & BRCMF_WOWL_BCN) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_BCN\n");
wakeup_data.disconnect = true;
}
if (wakeind & BRCMF_WOWL_RETR) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_RETR\n");
wakeup_data.disconnect = true;
}
if (wakeind & BRCMF_WOWL_NET) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_NET\n");
/* For now always map to pattern 0, no API to get
* correct information available at the moment.
*/
wakeup_data.pattern_idx = 0;
}
if (wakeind & BRCMF_WOWL_PFN_FOUND) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_PFN_FOUND\n");
timeout = wait_event_timeout(cfg->wowl.nd_data_wait,
cfg->wowl.nd_data_completed,
BRCMF_ND_INFO_TIMEOUT);
if (!timeout)
brcmf_err("No result for wowl net detect\n");
else
wakeup_data.net_detect = cfg->wowl.nd_info;
}
if (wakeind & BRCMF_WOWL_GTK_FAILURE) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_GTK_FAILURE\n");
wakeup_data.gtk_rekey_failure = true;
}
} else {
wakeup = NULL;
}
cfg80211_report_wowlan_wakeup(&ifp->vif->wdev, wakeup, GFP_KERNEL);
}
#else
static void brcmf_report_wowl_wakeind(struct wiphy *wiphy, struct brcmf_if *ifp)
{
}
#endif /* CONFIG_PM */
static s32 brcmf_cfg80211_resume(struct wiphy *wiphy)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(ndev);
brcmf_dbg(TRACE, "Enter\n");
if (cfg->wowl.active) {
brcmf_report_wowl_wakeind(wiphy, ifp);
brcmf_fil_iovar_int_set(ifp, "wowl_clear", 0);
brcmf_config_wowl_pattern(ifp, "clr", NULL, 0, NULL, 0);
if (!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_ARP_ND))
brcmf_configure_arp_nd_offload(ifp, true);
brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PM,
cfg->wowl.pre_pmmode);
cfg->wowl.active = false;
if (cfg->wowl.nd_enabled) {
brcmf_cfg80211_sched_scan_stop(cfg->wiphy, ifp->ndev);
brcmf_fweh_unregister(cfg->pub, BRCMF_E_PFN_NET_FOUND);
brcmf_fweh_register(cfg->pub, BRCMF_E_PFN_NET_FOUND,
brcmf_notify_sched_scan_results);
cfg->wowl.nd_enabled = false;
}
}
return 0;
}
static void brcmf_configure_wowl(struct brcmf_cfg80211_info *cfg,
struct brcmf_if *ifp,
struct cfg80211_wowlan *wowl)
{
u32 wowl_config;
u32 i;
brcmf_dbg(TRACE, "Suspend, wowl config.\n");
if (!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_ARP_ND))
brcmf_configure_arp_nd_offload(ifp, false);
brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_PM, &cfg->wowl.pre_pmmode);
brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PM, PM_MAX);
wowl_config = 0;
if (wowl->disconnect)
wowl_config = BRCMF_WOWL_DIS | BRCMF_WOWL_BCN | BRCMF_WOWL_RETR;
if (wowl->magic_pkt)
wowl_config |= BRCMF_WOWL_MAGIC;
if ((wowl->patterns) && (wowl->n_patterns)) {
wowl_config |= BRCMF_WOWL_NET;
for (i = 0; i < wowl->n_patterns; i++) {
brcmf_config_wowl_pattern(ifp, "add",
(u8 *)wowl->patterns[i].pattern,
wowl->patterns[i].pattern_len,
(u8 *)wowl->patterns[i].mask,
wowl->patterns[i].pkt_offset);
}
}
if (wowl->nd_config) {
brcmf_cfg80211_sched_scan_start(cfg->wiphy, ifp->ndev,
wowl->nd_config);
wowl_config |= BRCMF_WOWL_PFN_FOUND;
cfg->wowl.nd_data_completed = false;
cfg->wowl.nd_enabled = true;
/* Now reroute the event for PFN to the wowl function. */
brcmf_fweh_unregister(cfg->pub, BRCMF_E_PFN_NET_FOUND);
brcmf_fweh_register(cfg->pub, BRCMF_E_PFN_NET_FOUND,
brcmf_wowl_nd_results);
}
if (wowl->gtk_rekey_failure)
wowl_config |= BRCMF_WOWL_GTK_FAILURE;
if (!test_bit(BRCMF_VIF_STATUS_CONNECTED, &ifp->vif->sme_state))
wowl_config |= BRCMF_WOWL_UNASSOC;
brcmf_fil_iovar_data_set(ifp, "wowl_wakeind", "clear",
sizeof(struct brcmf_wowl_wakeind_le));
brcmf_fil_iovar_int_set(ifp, "wowl", wowl_config);
brcmf_fil_iovar_int_set(ifp, "wowl_activate", 1);
brcmf_bus_wowl_config(cfg->pub->bus_if, true);
cfg->wowl.active = true;
}
static s32 brcmf_cfg80211_suspend(struct wiphy *wiphy,
struct cfg80211_wowlan *wowl)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_vif *vif;
brcmf_dbg(TRACE, "Enter\n");
/* if the primary net_device is not READY there is nothing
* we can do but pray resume goes smoothly.
*/
if (!check_vif_up(ifp->vif))
goto exit;
/* Stop scheduled scan */
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_PNO))
brcmf_cfg80211_sched_scan_stop(wiphy, ndev);
/* end any scanning */
if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status))
brcmf_abort_scanning(cfg);
if (wowl == NULL) {
brcmf_bus_wowl_config(cfg->pub->bus_if, false);
list_for_each_entry(vif, &cfg->vif_list, list) {
if (!test_bit(BRCMF_VIF_STATUS_READY, &vif->sme_state))
continue;
/* While going to suspend if associated with AP
* disassociate from AP to save power while system is
* in suspended state
*/
brcmf_link_down(vif, WLAN_REASON_UNSPECIFIED);
/* Make sure WPA_Supplicant receives all the event
* generated due to DISASSOC call to the fw to keep
* the state fw and WPA_Supplicant state consistent
*/
brcmf_delay(500);
}
/* Configure MPC */
brcmf_set_mpc(ifp, 1);
} else {
/* Configure WOWL paramaters */
brcmf_configure_wowl(cfg, ifp, wowl);
}
exit:
brcmf_dbg(TRACE, "Exit\n");
/* clear any scanning activity */
cfg->scan_status = 0;
return 0;
}
static __used s32
brcmf_update_pmklist(struct brcmf_cfg80211_info *cfg, struct brcmf_if *ifp)
{
struct brcmf_pmk_list_le *pmk_list;
int i;
u32 npmk;
s32 err;
pmk_list = &cfg->pmk_list;
npmk = le32_to_cpu(pmk_list->npmk);
brcmf_dbg(CONN, "No of elements %d\n", npmk);
for (i = 0; i < npmk; i++)
brcmf_dbg(CONN, "PMK[%d]: %pM\n", i, &pmk_list->pmk[i].bssid);
err = brcmf_fil_iovar_data_set(ifp, "pmkid_info", pmk_list,
sizeof(*pmk_list));
return err;
}
static s32
brcmf_cfg80211_set_pmksa(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_pmksa *pmksa)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_pmksa *pmk = &cfg->pmk_list.pmk[0];
s32 err;
u32 npmk, i;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
npmk = le32_to_cpu(cfg->pmk_list.npmk);
for (i = 0; i < npmk; i++)
if (!memcmp(pmksa->bssid, pmk[i].bssid, ETH_ALEN))
break;
if (i < BRCMF_MAXPMKID) {
memcpy(pmk[i].bssid, pmksa->bssid, ETH_ALEN);
memcpy(pmk[i].pmkid, pmksa->pmkid, WLAN_PMKID_LEN);
if (i == npmk) {
npmk++;
cfg->pmk_list.npmk = cpu_to_le32(npmk);
}
} else {
brcmf_err("Too many PMKSA entries cached %d\n", npmk);
return -EINVAL;
}
brcmf_dbg(CONN, "set_pmksa - PMK bssid: %pM =\n", pmk[npmk].bssid);
for (i = 0; i < WLAN_PMKID_LEN; i += 4)
brcmf_dbg(CONN, "%02x %02x %02x %02x\n", pmk[npmk].pmkid[i],
pmk[npmk].pmkid[i + 1], pmk[npmk].pmkid[i + 2],
pmk[npmk].pmkid[i + 3]);
err = brcmf_update_pmklist(cfg, ifp);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_del_pmksa(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_pmksa *pmksa)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_pmksa *pmk = &cfg->pmk_list.pmk[0];
s32 err;
u32 npmk, i;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
brcmf_dbg(CONN, "del_pmksa - PMK bssid = %pM\n", &pmksa->bssid);
npmk = le32_to_cpu(cfg->pmk_list.npmk);
for (i = 0; i < npmk; i++)
if (!memcmp(&pmksa->bssid, &pmk[i].bssid, ETH_ALEN))
break;
if ((npmk > 0) && (i < npmk)) {
for (; i < (npmk - 1); i++) {
memcpy(&pmk[i].bssid, &pmk[i + 1].bssid, ETH_ALEN);
memcpy(&pmk[i].pmkid, &pmk[i + 1].pmkid,
WLAN_PMKID_LEN);
}
memset(&pmk[i], 0, sizeof(*pmk));
cfg->pmk_list.npmk = cpu_to_le32(npmk - 1);
} else {
brcmf_err("Cache entry not found\n");
return -EINVAL;
}
err = brcmf_update_pmklist(cfg, ifp);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_flush_pmksa(struct wiphy *wiphy, struct net_device *ndev)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
memset(&cfg->pmk_list, 0, sizeof(cfg->pmk_list));
err = brcmf_update_pmklist(cfg, ifp);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32 brcmf_configure_opensecurity(struct brcmf_if *ifp)
{
s32 err;
/* set auth */
err = brcmf_fil_bsscfg_int_set(ifp, "auth", 0);
if (err < 0) {
brcmf_err("auth error %d\n", err);
return err;
}
/* set wsec */
err = brcmf_fil_bsscfg_int_set(ifp, "wsec", 0);
if (err < 0) {
brcmf_err("wsec error %d\n", err);
return err;
}
/* set upper-layer auth */
err = brcmf_fil_bsscfg_int_set(ifp, "wpa_auth", WPA_AUTH_NONE);
if (err < 0) {
brcmf_err("wpa_auth error %d\n", err);
return err;
}
return 0;
}
static bool brcmf_valid_wpa_oui(u8 *oui, bool is_rsn_ie)
{
if (is_rsn_ie)
return (memcmp(oui, RSN_OUI, TLV_OUI_LEN) == 0);
return (memcmp(oui, WPA_OUI, TLV_OUI_LEN) == 0);
}
static s32
brcmf_configure_wpaie(struct brcmf_if *ifp,
const struct brcmf_vs_tlv *wpa_ie,
bool is_rsn_ie)
{
u32 auth = 0; /* d11 open authentication */
u16 count;
s32 err = 0;
s32 len;
u32 i;
u32 wsec;
u32 pval = 0;
u32 gval = 0;
u32 wpa_auth = 0;
u32 offset;
u8 *data;
u16 rsn_cap;
u32 wme_bss_disable;
u32 mfp;
brcmf_dbg(TRACE, "Enter\n");
if (wpa_ie == NULL)
goto exit;
len = wpa_ie->len + TLV_HDR_LEN;
data = (u8 *)wpa_ie;
offset = TLV_HDR_LEN;
if (!is_rsn_ie)
offset += VS_IE_FIXED_HDR_LEN;
else
offset += WPA_IE_VERSION_LEN;
/* check for multicast cipher suite */
if (offset + WPA_IE_MIN_OUI_LEN > len) {
err = -EINVAL;
brcmf_err("no multicast cipher suite\n");
goto exit;
}
if (!brcmf_valid_wpa_oui(&data[offset], is_rsn_ie)) {
err = -EINVAL;
brcmf_err("ivalid OUI\n");
goto exit;
}
offset += TLV_OUI_LEN;
/* pick up multicast cipher */
switch (data[offset]) {
case WPA_CIPHER_NONE:
gval = 0;
break;
case WPA_CIPHER_WEP_40:
case WPA_CIPHER_WEP_104:
gval = WEP_ENABLED;
break;
case WPA_CIPHER_TKIP:
gval = TKIP_ENABLED;
break;
case WPA_CIPHER_AES_CCM:
gval = AES_ENABLED;
break;
default:
err = -EINVAL;
brcmf_err("Invalid multi cast cipher info\n");
goto exit;
}
offset++;
/* walk thru unicast cipher list and pick up what we recognize */
count = data[offset] + (data[offset + 1] << 8);
offset += WPA_IE_SUITE_COUNT_LEN;
/* Check for unicast suite(s) */
if (offset + (WPA_IE_MIN_OUI_LEN * count) > len) {
err = -EINVAL;
brcmf_err("no unicast cipher suite\n");
goto exit;
}
for (i = 0; i < count; i++) {
if (!brcmf_valid_wpa_oui(&data[offset], is_rsn_ie)) {
err = -EINVAL;
brcmf_err("ivalid OUI\n");
goto exit;
}
offset += TLV_OUI_LEN;
switch (data[offset]) {
case WPA_CIPHER_NONE:
break;
case WPA_CIPHER_WEP_40:
case WPA_CIPHER_WEP_104:
pval |= WEP_ENABLED;
break;
case WPA_CIPHER_TKIP:
pval |= TKIP_ENABLED;
break;
case WPA_CIPHER_AES_CCM:
pval |= AES_ENABLED;
break;
default:
brcmf_err("Ivalid unicast security info\n");
}
offset++;
}
/* walk thru auth management suite list and pick up what we recognize */
count = data[offset] + (data[offset + 1] << 8);
offset += WPA_IE_SUITE_COUNT_LEN;
/* Check for auth key management suite(s) */
if (offset + (WPA_IE_MIN_OUI_LEN * count) > len) {
err = -EINVAL;
brcmf_err("no auth key mgmt suite\n");
goto exit;
}
for (i = 0; i < count; i++) {
if (!brcmf_valid_wpa_oui(&data[offset], is_rsn_ie)) {
err = -EINVAL;
brcmf_err("ivalid OUI\n");
goto exit;
}
offset += TLV_OUI_LEN;
switch (data[offset]) {
case RSN_AKM_NONE:
brcmf_dbg(TRACE, "RSN_AKM_NONE\n");
wpa_auth |= WPA_AUTH_NONE;
break;
case RSN_AKM_UNSPECIFIED:
brcmf_dbg(TRACE, "RSN_AKM_UNSPECIFIED\n");
is_rsn_ie ? (wpa_auth |= WPA2_AUTH_UNSPECIFIED) :
(wpa_auth |= WPA_AUTH_UNSPECIFIED);
break;
case RSN_AKM_PSK:
brcmf_dbg(TRACE, "RSN_AKM_PSK\n");
is_rsn_ie ? (wpa_auth |= WPA2_AUTH_PSK) :
(wpa_auth |= WPA_AUTH_PSK);
break;
case RSN_AKM_SHA256_PSK:
brcmf_dbg(TRACE, "RSN_AKM_MFP_PSK\n");
wpa_auth |= WPA2_AUTH_PSK_SHA256;
break;
case RSN_AKM_SHA256_1X:
brcmf_dbg(TRACE, "RSN_AKM_MFP_1X\n");
wpa_auth |= WPA2_AUTH_1X_SHA256;
break;
default:
brcmf_err("Ivalid key mgmt info\n");
}
offset++;
}
mfp = BRCMF_MFP_NONE;
if (is_rsn_ie) {
wme_bss_disable = 1;
if ((offset + RSN_CAP_LEN) <= len) {
rsn_cap = data[offset] + (data[offset + 1] << 8);
if (rsn_cap & RSN_CAP_PTK_REPLAY_CNTR_MASK)
wme_bss_disable = 0;
if (rsn_cap & RSN_CAP_MFPR_MASK) {
brcmf_dbg(TRACE, "MFP Required\n");
mfp = BRCMF_MFP_REQUIRED;
/* Firmware only supports mfp required in
* combination with WPA2_AUTH_PSK_SHA256 or
* WPA2_AUTH_1X_SHA256.
*/
if (!(wpa_auth & (WPA2_AUTH_PSK_SHA256 |
WPA2_AUTH_1X_SHA256))) {
err = -EINVAL;
goto exit;
}
/* Firmware has requirement that WPA2_AUTH_PSK/
* WPA2_AUTH_UNSPECIFIED be set, if SHA256 OUI
* is to be included in the rsn ie.
*/
if (wpa_auth & WPA2_AUTH_PSK_SHA256)
wpa_auth |= WPA2_AUTH_PSK;
else if (wpa_auth & WPA2_AUTH_1X_SHA256)
wpa_auth |= WPA2_AUTH_UNSPECIFIED;
} else if (rsn_cap & RSN_CAP_MFPC_MASK) {
brcmf_dbg(TRACE, "MFP Capable\n");
mfp = BRCMF_MFP_CAPABLE;
}
}
offset += RSN_CAP_LEN;
/* set wme_bss_disable to sync RSN Capabilities */
err = brcmf_fil_bsscfg_int_set(ifp, "wme_bss_disable",
wme_bss_disable);
if (err < 0) {
brcmf_err("wme_bss_disable error %d\n", err);
goto exit;
}
/* Skip PMKID cnt as it is know to be 0 for AP. */
offset += RSN_PMKID_COUNT_LEN;
/* See if there is BIP wpa suite left for MFP */
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP) &&
((offset + WPA_IE_MIN_OUI_LEN) <= len)) {
err = brcmf_fil_bsscfg_data_set(ifp, "bip",
&data[offset],
WPA_IE_MIN_OUI_LEN);
if (err < 0) {
brcmf_err("bip error %d\n", err);
goto exit;
}
}
}
/* FOR WPS , set SES_OW_ENABLED */
wsec = (pval | gval | SES_OW_ENABLED);
/* set auth */
err = brcmf_fil_bsscfg_int_set(ifp, "auth", auth);
if (err < 0) {
brcmf_err("auth error %d\n", err);
goto exit;
}
/* set wsec */
err = brcmf_fil_bsscfg_int_set(ifp, "wsec", wsec);
if (err < 0) {
brcmf_err("wsec error %d\n", err);
goto exit;
}
/* Configure MFP, this needs to go after wsec otherwise the wsec command
* will overwrite the values set by MFP
*/
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP)) {
err = brcmf_fil_bsscfg_int_set(ifp, "mfp", mfp);
if (err < 0) {
brcmf_err("mfp error %d\n", err);
goto exit;
}
}
/* set upper-layer auth */
err = brcmf_fil_bsscfg_int_set(ifp, "wpa_auth", wpa_auth);
if (err < 0) {
brcmf_err("wpa_auth error %d\n", err);
goto exit;
}
exit:
return err;
}
static s32
brcmf_parse_vndr_ies(const u8 *vndr_ie_buf, u32 vndr_ie_len,
struct parsed_vndr_ies *vndr_ies)
{
struct brcmf_vs_tlv *vndrie;
struct brcmf_tlv *ie;
struct parsed_vndr_ie_info *parsed_info;
s32 remaining_len;
remaining_len = (s32)vndr_ie_len;
memset(vndr_ies, 0, sizeof(*vndr_ies));
ie = (struct brcmf_tlv *)vndr_ie_buf;
while (ie) {
if (ie->id != WLAN_EID_VENDOR_SPECIFIC)
goto next;
vndrie = (struct brcmf_vs_tlv *)ie;
/* len should be bigger than OUI length + one */
if (vndrie->len < (VS_IE_FIXED_HDR_LEN - TLV_HDR_LEN + 1)) {
brcmf_err("invalid vndr ie. length is too small %d\n",
vndrie->len);
goto next;
}
/* if wpa or wme ie, do not add ie */
if (!memcmp(vndrie->oui, (u8 *)WPA_OUI, TLV_OUI_LEN) &&
((vndrie->oui_type == WPA_OUI_TYPE) ||
(vndrie->oui_type == WME_OUI_TYPE))) {
brcmf_dbg(TRACE, "Found WPA/WME oui. Do not add it\n");
goto next;
}
parsed_info = &vndr_ies->ie_info[vndr_ies->count];
/* save vndr ie information */
parsed_info->ie_ptr = (char *)vndrie;
parsed_info->ie_len = vndrie->len + TLV_HDR_LEN;
memcpy(&parsed_info->vndrie, vndrie, sizeof(*vndrie));
vndr_ies->count++;
brcmf_dbg(TRACE, "** OUI %02x %02x %02x, type 0x%02x\n",
parsed_info->vndrie.oui[0],
parsed_info->vndrie.oui[1],
parsed_info->vndrie.oui[2],
parsed_info->vndrie.oui_type);
if (vndr_ies->count >= VNDR_IE_PARSE_LIMIT)
break;
next:
remaining_len -= (ie->len + TLV_HDR_LEN);
if (remaining_len <= TLV_HDR_LEN)
ie = NULL;
else
ie = (struct brcmf_tlv *)(((u8 *)ie) + ie->len +
TLV_HDR_LEN);
}
return 0;
}
static u32
brcmf_vndr_ie(u8 *iebuf, s32 pktflag, u8 *ie_ptr, u32 ie_len, s8 *add_del_cmd)
{
strncpy(iebuf, add_del_cmd, VNDR_IE_CMD_LEN - 1);
iebuf[VNDR_IE_CMD_LEN - 1] = '\0';
put_unaligned_le32(1, &iebuf[VNDR_IE_COUNT_OFFSET]);
put_unaligned_le32(pktflag, &iebuf[VNDR_IE_PKTFLAG_OFFSET]);
memcpy(&iebuf[VNDR_IE_VSIE_OFFSET], ie_ptr, ie_len);
return ie_len + VNDR_IE_HDR_SIZE;
}
s32 brcmf_vif_set_mgmt_ie(struct brcmf_cfg80211_vif *vif, s32 pktflag,
const u8 *vndr_ie_buf, u32 vndr_ie_len)
{
struct brcmf_if *ifp;
struct vif_saved_ie *saved_ie;
s32 err = 0;
u8 *iovar_ie_buf;
u8 *curr_ie_buf;
u8 *mgmt_ie_buf = NULL;
int mgmt_ie_buf_len;
u32 *mgmt_ie_len;
u32 del_add_ie_buf_len = 0;
u32 total_ie_buf_len = 0;
u32 parsed_ie_buf_len = 0;
struct parsed_vndr_ies old_vndr_ies;
struct parsed_vndr_ies new_vndr_ies;
struct parsed_vndr_ie_info *vndrie_info;
s32 i;
u8 *ptr;
int remained_buf_len;
if (!vif)
return -ENODEV;
ifp = vif->ifp;
saved_ie = &vif->saved_ie;
brcmf_dbg(TRACE, "bsscfgidx %d, pktflag : 0x%02X\n", ifp->bsscfgidx,
pktflag);
iovar_ie_buf = kzalloc(WL_EXTRA_BUF_MAX, GFP_KERNEL);
if (!iovar_ie_buf)
return -ENOMEM;
curr_ie_buf = iovar_ie_buf;
switch (pktflag) {
case BRCMF_VNDR_IE_PRBREQ_FLAG:
mgmt_ie_buf = saved_ie->probe_req_ie;
mgmt_ie_len = &saved_ie->probe_req_ie_len;
mgmt_ie_buf_len = sizeof(saved_ie->probe_req_ie);
break;
case BRCMF_VNDR_IE_PRBRSP_FLAG:
mgmt_ie_buf = saved_ie->probe_res_ie;
mgmt_ie_len = &saved_ie->probe_res_ie_len;
mgmt_ie_buf_len = sizeof(saved_ie->probe_res_ie);
break;
case BRCMF_VNDR_IE_BEACON_FLAG:
mgmt_ie_buf = saved_ie->beacon_ie;
mgmt_ie_len = &saved_ie->beacon_ie_len;
mgmt_ie_buf_len = sizeof(saved_ie->beacon_ie);
break;
case BRCMF_VNDR_IE_ASSOCREQ_FLAG:
mgmt_ie_buf = saved_ie->assoc_req_ie;
mgmt_ie_len = &saved_ie->assoc_req_ie_len;
mgmt_ie_buf_len = sizeof(saved_ie->assoc_req_ie);
break;
default:
err = -EPERM;
brcmf_err("not suitable type\n");
goto exit;
}
if (vndr_ie_len > mgmt_ie_buf_len) {
err = -ENOMEM;
brcmf_err("extra IE size too big\n");
goto exit;
}
/* parse and save new vndr_ie in curr_ie_buff before comparing it */
if (vndr_ie_buf && vndr_ie_len && curr_ie_buf) {
ptr = curr_ie_buf;
brcmf_parse_vndr_ies(vndr_ie_buf, vndr_ie_len, &new_vndr_ies);
for (i = 0; i < new_vndr_ies.count; i++) {
vndrie_info = &new_vndr_ies.ie_info[i];
memcpy(ptr + parsed_ie_buf_len, vndrie_info->ie_ptr,
vndrie_info->ie_len);
parsed_ie_buf_len += vndrie_info->ie_len;
}
}
if (mgmt_ie_buf && *mgmt_ie_len) {
if (parsed_ie_buf_len && (parsed_ie_buf_len == *mgmt_ie_len) &&
(memcmp(mgmt_ie_buf, curr_ie_buf,
parsed_ie_buf_len) == 0)) {
brcmf_dbg(TRACE, "Previous mgmt IE equals to current IE\n");
goto exit;
}
/* parse old vndr_ie */
brcmf_parse_vndr_ies(mgmt_ie_buf, *mgmt_ie_len, &old_vndr_ies);
/* make a command to delete old ie */
for (i = 0; i < old_vndr_ies.count; i++) {
vndrie_info = &old_vndr_ies.ie_info[i];
brcmf_dbg(TRACE, "DEL ID : %d, Len: %d , OUI:%02x:%02x:%02x\n",
vndrie_info->vndrie.id,
vndrie_info->vndrie.len,
vndrie_info->vndrie.oui[0],
vndrie_info->vndrie.oui[1],
vndrie_info->vndrie.oui[2]);
del_add_ie_buf_len = brcmf_vndr_ie(curr_ie_buf, pktflag,
vndrie_info->ie_ptr,
vndrie_info->ie_len,
"del");
curr_ie_buf += del_add_ie_buf_len;
total_ie_buf_len += del_add_ie_buf_len;
}
}
*mgmt_ie_len = 0;
/* Add if there is any extra IE */
if (mgmt_ie_buf && parsed_ie_buf_len) {
ptr = mgmt_ie_buf;
remained_buf_len = mgmt_ie_buf_len;
/* make a command to add new ie */
for (i = 0; i < new_vndr_ies.count; i++) {
vndrie_info = &new_vndr_ies.ie_info[i];
/* verify remained buf size before copy data */
if (remained_buf_len < (vndrie_info->vndrie.len +
VNDR_IE_VSIE_OFFSET)) {
brcmf_err("no space in mgmt_ie_buf: len left %d",
remained_buf_len);
break;
}
remained_buf_len -= (vndrie_info->ie_len +
VNDR_IE_VSIE_OFFSET);
brcmf_dbg(TRACE, "ADDED ID : %d, Len: %d, OUI:%02x:%02x:%02x\n",
vndrie_info->vndrie.id,
vndrie_info->vndrie.len,
vndrie_info->vndrie.oui[0],
vndrie_info->vndrie.oui[1],
vndrie_info->vndrie.oui[2]);
del_add_ie_buf_len = brcmf_vndr_ie(curr_ie_buf, pktflag,
vndrie_info->ie_ptr,
vndrie_info->ie_len,
"add");
/* save the parsed IE in wl struct */
memcpy(ptr + (*mgmt_ie_len), vndrie_info->ie_ptr,
vndrie_info->ie_len);
*mgmt_ie_len += vndrie_info->ie_len;
curr_ie_buf += del_add_ie_buf_len;
total_ie_buf_len += del_add_ie_buf_len;
}
}
if (total_ie_buf_len) {
err = brcmf_fil_bsscfg_data_set(ifp, "vndr_ie", iovar_ie_buf,
total_ie_buf_len);
if (err)
brcmf_err("vndr ie set error : %d\n", err);
}
exit:
kfree(iovar_ie_buf);
return err;
}
s32 brcmf_vif_clear_mgmt_ies(struct brcmf_cfg80211_vif *vif)
{
s32 pktflags[] = {
BRCMF_VNDR_IE_PRBREQ_FLAG,
BRCMF_VNDR_IE_PRBRSP_FLAG,
BRCMF_VNDR_IE_BEACON_FLAG
};
int i;
for (i = 0; i < ARRAY_SIZE(pktflags); i++)
brcmf_vif_set_mgmt_ie(vif, pktflags[i], NULL, 0);
memset(&vif->saved_ie, 0, sizeof(vif->saved_ie));
return 0;
}
static s32
brcmf_config_ap_mgmt_ie(struct brcmf_cfg80211_vif *vif,
struct cfg80211_beacon_data *beacon)
{
s32 err;
/* Set Beacon IEs to FW */
err = brcmf_vif_set_mgmt_ie(vif, BRCMF_VNDR_IE_BEACON_FLAG,
beacon->tail, beacon->tail_len);
if (err) {
brcmf_err("Set Beacon IE Failed\n");
return err;
}
brcmf_dbg(TRACE, "Applied Vndr IEs for Beacon\n");
/* Set Probe Response IEs to FW */
err = brcmf_vif_set_mgmt_ie(vif, BRCMF_VNDR_IE_PRBRSP_FLAG,
beacon->proberesp_ies,
beacon->proberesp_ies_len);
if (err)
brcmf_err("Set Probe Resp IE Failed\n");
else
brcmf_dbg(TRACE, "Applied Vndr IEs for Probe Resp\n");
return err;
}
static s32
brcmf_cfg80211_start_ap(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_ap_settings *settings)
{
s32 ie_offset;
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
const struct brcmf_tlv *ssid_ie;
const struct brcmf_tlv *country_ie;
struct brcmf_ssid_le ssid_le;
s32 err = -EPERM;
const struct brcmf_tlv *rsn_ie;
const struct brcmf_vs_tlv *wpa_ie;
struct brcmf_join_params join_params;
enum nl80211_iftype dev_role;
struct brcmf_fil_bss_enable_le bss_enable;
u16 chanspec = chandef_to_chanspec(&cfg->d11inf, &settings->chandef);
bool mbss;
int is_11d;
brcmf_dbg(TRACE, "ctrlchn=%d, center=%d, bw=%d, beacon_interval=%d, dtim_period=%d,\n",
settings->chandef.chan->hw_value,
settings->chandef.center_freq1, settings->chandef.width,
settings->beacon_interval, settings->dtim_period);
brcmf_dbg(TRACE, "ssid=%s(%zu), auth_type=%d, inactivity_timeout=%d\n",
settings->ssid, settings->ssid_len, settings->auth_type,
settings->inactivity_timeout);
dev_role = ifp->vif->wdev.iftype;
mbss = ifp->vif->mbss;
/* store current 11d setting */
brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_REGULATORY, &ifp->vif->is_11d);
country_ie = brcmf_parse_tlvs((u8 *)settings->beacon.tail,
settings->beacon.tail_len,
WLAN_EID_COUNTRY);
is_11d = country_ie ? 1 : 0;
memset(&ssid_le, 0, sizeof(ssid_le));
if (settings->ssid == NULL || settings->ssid_len == 0) {
ie_offset = DOT11_MGMT_HDR_LEN + DOT11_BCN_PRB_FIXED_LEN;
ssid_ie = brcmf_parse_tlvs(
(u8 *)&settings->beacon.head[ie_offset],
settings->beacon.head_len - ie_offset,
WLAN_EID_SSID);
if (!ssid_ie || ssid_ie->len > IEEE80211_MAX_SSID_LEN)
return -EINVAL;
memcpy(ssid_le.SSID, ssid_ie->data, ssid_ie->len);
ssid_le.SSID_len = cpu_to_le32(ssid_ie->len);
brcmf_dbg(TRACE, "SSID is (%s) in Head\n", ssid_le.SSID);
} else {
memcpy(ssid_le.SSID, settings->ssid, settings->ssid_len);
ssid_le.SSID_len = cpu_to_le32((u32)settings->ssid_len);
}
if (!mbss) {
brcmf_set_mpc(ifp, 0);
brcmf_configure_arp_nd_offload(ifp, false);
}
/* find the RSN_IE */
rsn_ie = brcmf_parse_tlvs((u8 *)settings->beacon.tail,
settings->beacon.tail_len, WLAN_EID_RSN);
/* find the WPA_IE */
wpa_ie = brcmf_find_wpaie((u8 *)settings->beacon.tail,
settings->beacon.tail_len);
if ((wpa_ie != NULL || rsn_ie != NULL)) {
brcmf_dbg(TRACE, "WPA(2) IE is found\n");
if (wpa_ie != NULL) {
/* WPA IE */
err = brcmf_configure_wpaie(ifp, wpa_ie, false);
if (err < 0)
goto exit;
} else {
struct brcmf_vs_tlv *tmp_ie;
tmp_ie = (struct brcmf_vs_tlv *)rsn_ie;
/* RSN IE */
err = brcmf_configure_wpaie(ifp, tmp_ie, true);
if (err < 0)
goto exit;
}
} else {
brcmf_dbg(TRACE, "No WPA(2) IEs found\n");
brcmf_configure_opensecurity(ifp);
}
brcmf_config_ap_mgmt_ie(ifp->vif, &settings->beacon);
/* Parameters shared by all radio interfaces */
if (!mbss) {
if (is_11d != ifp->vif->is_11d) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_REGULATORY,
is_11d);
if (err < 0) {
brcmf_err("Regulatory Set Error, %d\n", err);
goto exit;
}
}
if (settings->beacon_interval) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_BCNPRD,
settings->beacon_interval);
if (err < 0) {
brcmf_err("Beacon Interval Set Error, %d\n",
err);
goto exit;
}
}
if (settings->dtim_period) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_DTIMPRD,
settings->dtim_period);
if (err < 0) {
brcmf_err("DTIM Interval Set Error, %d\n", err);
goto exit;
}
}
if ((dev_role == NL80211_IFTYPE_AP) &&
((ifp->ifidx == 0) ||
!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_RSDB))) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_DOWN, 1);
if (err < 0) {
brcmf_err("BRCMF_C_DOWN error %d\n", err);
goto exit;
}
brcmf_fil_iovar_int_set(ifp, "apsta", 0);
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_INFRA, 1);
if (err < 0) {
brcmf_err("SET INFRA error %d\n", err);
goto exit;
}
} else if (WARN_ON(is_11d != ifp->vif->is_11d)) {
/* Multiple-BSS should use same 11d configuration */
err = -EINVAL;
goto exit;
}
/* Interface specific setup */
if (dev_role == NL80211_IFTYPE_AP) {
if ((brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MBSS)) && (!mbss))
brcmf_fil_iovar_int_set(ifp, "mbss", 1);
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_AP, 1);
if (err < 0) {
brcmf_err("setting AP mode failed %d\n", err);
goto exit;
}
if (!mbss) {
/* Firmware 10.x requires setting channel after enabling
* AP and before bringing interface up.
*/
err = brcmf_fil_iovar_int_set(ifp, "chanspec", chanspec);
if (err < 0) {
brcmf_err("Set Channel failed: chspec=%d, %d\n",
chanspec, err);
goto exit;
}
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_UP, 1);
if (err < 0) {
brcmf_err("BRCMF_C_UP error (%d)\n", err);
goto exit;
}
/* On DOWN the firmware removes the WEP keys, reconfigure
* them if they were set.
*/
brcmf_cfg80211_reconfigure_wep(ifp);
memset(&join_params, 0, sizeof(join_params));
/* join parameters starts with ssid */
memcpy(&join_params.ssid_le, &ssid_le, sizeof(ssid_le));
/* create softap */
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,
&join_params, sizeof(join_params));
if (err < 0) {
brcmf_err("SET SSID error (%d)\n", err);
goto exit;
}
if (settings->hidden_ssid) {
err = brcmf_fil_iovar_int_set(ifp, "closednet", 1);
if (err) {
brcmf_err("closednet error (%d)\n", err);
goto exit;
}
}
brcmf_dbg(TRACE, "AP mode configuration complete\n");
} else if (dev_role == NL80211_IFTYPE_P2P_GO) {
err = brcmf_fil_iovar_int_set(ifp, "chanspec", chanspec);
if (err < 0) {
brcmf_err("Set Channel failed: chspec=%d, %d\n",
chanspec, err);
goto exit;
}
err = brcmf_fil_bsscfg_data_set(ifp, "ssid", &ssid_le,
sizeof(ssid_le));
if (err < 0) {
brcmf_err("setting ssid failed %d\n", err);
goto exit;
}
bss_enable.bsscfgidx = cpu_to_le32(ifp->bsscfgidx);
bss_enable.enable = cpu_to_le32(1);
err = brcmf_fil_iovar_data_set(ifp, "bss", &bss_enable,
sizeof(bss_enable));
if (err < 0) {
brcmf_err("bss_enable config failed %d\n", err);
goto exit;
}
brcmf_dbg(TRACE, "GO mode configuration complete\n");
} else {
WARN_ON(1);
}
set_bit(BRCMF_VIF_STATUS_AP_CREATED, &ifp->vif->sme_state);
brcmf_net_setcarrier(ifp, true);
exit:
if ((err) && (!mbss)) {
brcmf_set_mpc(ifp, 1);
brcmf_configure_arp_nd_offload(ifp, true);
}
return err;
}
static int brcmf_cfg80211_stop_ap(struct wiphy *wiphy, struct net_device *ndev)
{
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
struct brcmf_fil_bss_enable_le bss_enable;
struct brcmf_join_params join_params;
brcmf_dbg(TRACE, "Enter\n");
if (ifp->vif->wdev.iftype == NL80211_IFTYPE_AP) {
/* Due to most likely deauths outstanding we sleep */
/* first to make sure they get processed by fw. */
msleep(400);
if (ifp->vif->mbss) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_DOWN, 1);
return err;
}
/* First BSS doesn't get a full reset */
if (ifp->bsscfgidx == 0)
brcmf_fil_iovar_int_set(ifp, "closednet", 0);
memset(&join_params, 0, sizeof(join_params));
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,
&join_params, sizeof(join_params));
if (err < 0)
brcmf_err("SET SSID error (%d)\n", err);
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_DOWN, 1);
if (err < 0)
brcmf_err("BRCMF_C_DOWN error %d\n", err);
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_AP, 0);
if (err < 0)
brcmf_err("setting AP mode failed %d\n", err);
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_INFRA, 0);
if (err < 0)
brcmf_err("setting INFRA mode failed %d\n", err);
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MBSS))
brcmf_fil_iovar_int_set(ifp, "mbss", 0);
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_REGULATORY,
ifp->vif->is_11d);
if (err < 0)
brcmf_err("restoring REGULATORY setting failed %d\n",
err);
/* Bring device back up so it can be used again */
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_UP, 1);
if (err < 0)
brcmf_err("BRCMF_C_UP error %d\n", err);
} else {
bss_enable.bsscfgidx = cpu_to_le32(ifp->bsscfgidx);
bss_enable.enable = cpu_to_le32(0);
err = brcmf_fil_iovar_data_set(ifp, "bss", &bss_enable,
sizeof(bss_enable));
if (err < 0)
brcmf_err("bss_enable config failed %d\n", err);
}
brcmf_set_mpc(ifp, 1);
brcmf_configure_arp_nd_offload(ifp, true);
clear_bit(BRCMF_VIF_STATUS_AP_CREATED, &ifp->vif->sme_state);
brcmf_net_setcarrier(ifp, false);
return err;
}
static s32
brcmf_cfg80211_change_beacon(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_beacon_data *info)
{
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
brcmf_dbg(TRACE, "Enter\n");
err = brcmf_config_ap_mgmt_ie(ifp->vif, info);
return err;
}
static int
brcmf_cfg80211_del_station(struct wiphy *wiphy, struct net_device *ndev,
struct station_del_parameters *params)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_scb_val_le scbval;
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
if (!params->mac)
return -EFAULT;
brcmf_dbg(TRACE, "Enter %pM\n", params->mac);
if (ifp->vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif)
ifp = cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif->ifp;
if (!check_vif_up(ifp->vif))
return -EIO;
memcpy(&scbval.ea, params->mac, ETH_ALEN);
scbval.val = cpu_to_le32(params->reason_code);
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SCB_DEAUTHENTICATE_FOR_REASON,
&scbval, sizeof(scbval));
if (err)
brcmf_err("SCB_DEAUTHENTICATE_FOR_REASON failed %d\n", err);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static int
brcmf_cfg80211_change_station(struct wiphy *wiphy, struct net_device *ndev,
const u8 *mac, struct station_parameters *params)
{
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
brcmf_dbg(TRACE, "Enter, MAC %pM, mask 0x%04x set 0x%04x\n", mac,
params->sta_flags_mask, params->sta_flags_set);
/* Ignore all 00 MAC */
if (is_zero_ether_addr(mac))
return 0;
if (!(params->sta_flags_mask & BIT(NL80211_STA_FLAG_AUTHORIZED)))
return 0;
if (params->sta_flags_set & BIT(NL80211_STA_FLAG_AUTHORIZED))
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SCB_AUTHORIZE,
(void *)mac, ETH_ALEN);
else
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SCB_DEAUTHORIZE,
(void *)mac, ETH_ALEN);
if (err < 0)
brcmf_err("Setting SCB (de-)authorize failed, %d\n", err);
return err;
}
static void
brcmf_cfg80211_mgmt_frame_register(struct wiphy *wiphy,
struct wireless_dev *wdev,
u16 frame_type, bool reg)
{
struct brcmf_cfg80211_vif *vif;
u16 mgmt_type;
brcmf_dbg(TRACE, "Enter, frame_type %04x, reg=%d\n", frame_type, reg);
mgmt_type = (frame_type & IEEE80211_FCTL_STYPE) >> 4;
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
if (reg)
vif->mgmt_rx_reg |= BIT(mgmt_type);
else
vif->mgmt_rx_reg &= ~BIT(mgmt_type);
}
static int
brcmf_cfg80211_mgmt_tx(struct wiphy *wiphy, struct wireless_dev *wdev,
struct cfg80211_mgmt_tx_params *params, u64 *cookie)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct ieee80211_channel *chan = params->chan;
const u8 *buf = params->buf;
size_t len = params->len;
const struct ieee80211_mgmt *mgmt;
struct brcmf_cfg80211_vif *vif;
s32 err = 0;
s32 ie_offset;
s32 ie_len;
struct brcmf_fil_action_frame_le *action_frame;
struct brcmf_fil_af_params_le *af_params;
bool ack;
s32 chan_nr;
u32 freq;
brcmf_dbg(TRACE, "Enter\n");
*cookie = 0;
mgmt = (const struct ieee80211_mgmt *)buf;
if (!ieee80211_is_mgmt(mgmt->frame_control)) {
brcmf_err("Driver only allows MGMT packet type\n");
return -EPERM;
}
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
if (ieee80211_is_probe_resp(mgmt->frame_control)) {
/* Right now the only reason to get a probe response */
/* is for p2p listen response or for p2p GO from */
/* wpa_supplicant. Unfortunately the probe is send */
/* on primary ndev, while dongle wants it on the p2p */
/* vif. Since this is only reason for a probe */
/* response to be sent, the vif is taken from cfg. */
/* If ever desired to send proberesp for non p2p */
/* response then data should be checked for */
/* "DIRECT-". Note in future supplicant will take */
/* dedicated p2p wdev to do this and then this 'hack'*/
/* is not needed anymore. */
ie_offset = DOT11_MGMT_HDR_LEN +
DOT11_BCN_PRB_FIXED_LEN;
ie_len = len - ie_offset;
if (vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif)
vif = cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif;
err = brcmf_vif_set_mgmt_ie(vif,
BRCMF_VNDR_IE_PRBRSP_FLAG,
&buf[ie_offset],
ie_len);
cfg80211_mgmt_tx_status(wdev, *cookie, buf, len, true,
GFP_KERNEL);
} else if (ieee80211_is_action(mgmt->frame_control)) {
af_params = kzalloc(sizeof(*af_params), GFP_KERNEL);
if (af_params == NULL) {
brcmf_err("unable to allocate frame\n");
err = -ENOMEM;
goto exit;
}
action_frame = &af_params->action_frame;
/* Add the packet Id */
action_frame->packet_id = cpu_to_le32(*cookie);
/* Add BSSID */
memcpy(&action_frame->da[0], &mgmt->da[0], ETH_ALEN);
memcpy(&af_params->bssid[0], &mgmt->bssid[0], ETH_ALEN);
/* Add the length exepted for 802.11 header */
action_frame->len = cpu_to_le16(len - DOT11_MGMT_HDR_LEN);
/* Add the channel. Use the one specified as parameter if any or
* the current one (got from the firmware) otherwise
*/
if (chan)
freq = chan->center_freq;
else
brcmf_fil_cmd_int_get(vif->ifp, BRCMF_C_GET_CHANNEL,
&freq);
chan_nr = ieee80211_frequency_to_channel(freq);
af_params->channel = cpu_to_le32(chan_nr);
memcpy(action_frame->data, &buf[DOT11_MGMT_HDR_LEN],
le16_to_cpu(action_frame->len));
brcmf_dbg(TRACE, "Action frame, cookie=%lld, len=%d, freq=%d\n",
*cookie, le16_to_cpu(action_frame->len), freq);
ack = brcmf_p2p_send_action_frame(cfg, cfg_to_ndev(cfg),
af_params);
cfg80211_mgmt_tx_status(wdev, *cookie, buf, len, ack,
GFP_KERNEL);
kfree(af_params);
} else {
brcmf_dbg(TRACE, "Unhandled, fc=%04x!!\n", mgmt->frame_control);
brcmf_dbg_hex_dump(true, buf, len, "payload, len=%Zu\n", len);
}
exit:
return err;
}
static int
brcmf_cfg80211_cancel_remain_on_channel(struct wiphy *wiphy,
struct wireless_dev *wdev,
u64 cookie)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_cfg80211_vif *vif;
int err = 0;
brcmf_dbg(TRACE, "Enter p2p listen cancel\n");
vif = cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif;
if (vif == NULL) {
brcmf_err("No p2p device available for probe response\n");
err = -ENODEV;
goto exit;
}
brcmf_p2p_cancel_remain_on_channel(vif->ifp);
exit:
return err;
}
static int brcmf_cfg80211_get_channel(struct wiphy *wiphy,
struct wireless_dev *wdev,
struct cfg80211_chan_def *chandef)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = wdev->netdev;
struct brcmf_if *ifp;
struct brcmu_chan ch;
enum nl80211_band band = 0;
enum nl80211_chan_width width = 0;
u32 chanspec;
int freq, err;
if (!ndev)
return -ENODEV;
ifp = netdev_priv(ndev);
err = brcmf_fil_iovar_int_get(ifp, "chanspec", &chanspec);
if (err) {
brcmf_err("chanspec failed (%d)\n", err);
return err;
}
ch.chspec = chanspec;
cfg->d11inf.decchspec(&ch);
switch (ch.band) {
case BRCMU_CHAN_BAND_2G:
band = NL80211_BAND_2GHZ;
break;
case BRCMU_CHAN_BAND_5G:
band = NL80211_BAND_5GHZ;
break;
}
switch (ch.bw) {
case BRCMU_CHAN_BW_80:
width = NL80211_CHAN_WIDTH_80;
break;
case BRCMU_CHAN_BW_40:
width = NL80211_CHAN_WIDTH_40;
break;
case BRCMU_CHAN_BW_20:
width = NL80211_CHAN_WIDTH_20;
break;
case BRCMU_CHAN_BW_80P80:
width = NL80211_CHAN_WIDTH_80P80;
break;
case BRCMU_CHAN_BW_160:
width = NL80211_CHAN_WIDTH_160;
break;
}
freq = ieee80211_channel_to_frequency(ch.control_ch_num, band);
chandef->chan = ieee80211_get_channel(wiphy, freq);
chandef->width = width;
chandef->center_freq1 = ieee80211_channel_to_frequency(ch.chnum, band);
chandef->center_freq2 = 0;
return 0;
}
static int brcmf_cfg80211_crit_proto_start(struct wiphy *wiphy,
struct wireless_dev *wdev,
enum nl80211_crit_proto_id proto,
u16 duration)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_cfg80211_vif *vif;
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
/* only DHCP support for now */
if (proto != NL80211_CRIT_PROTO_DHCP)
return -EINVAL;
/* suppress and abort scanning */
set_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status);
brcmf_abort_scanning(cfg);
return brcmf_btcoex_set_mode(vif, BRCMF_BTCOEX_DISABLED, duration);
}
static void brcmf_cfg80211_crit_proto_stop(struct wiphy *wiphy,
struct wireless_dev *wdev)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_cfg80211_vif *vif;
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
brcmf_btcoex_set_mode(vif, BRCMF_BTCOEX_ENABLED, 0);
clear_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status);
}
static s32
brcmf_notify_tdls_peer_event(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
switch (e->reason) {
case BRCMF_E_REASON_TDLS_PEER_DISCOVERED:
brcmf_dbg(TRACE, "TDLS Peer Discovered\n");
break;
case BRCMF_E_REASON_TDLS_PEER_CONNECTED:
brcmf_dbg(TRACE, "TDLS Peer Connected\n");
brcmf_proto_add_tdls_peer(ifp->drvr, ifp->ifidx, (u8 *)e->addr);
break;
case BRCMF_E_REASON_TDLS_PEER_DISCONNECTED:
brcmf_dbg(TRACE, "TDLS Peer Disconnected\n");
brcmf_proto_delete_peer(ifp->drvr, ifp->ifidx, (u8 *)e->addr);
break;
}
return 0;
}
static int brcmf_convert_nl80211_tdls_oper(enum nl80211_tdls_operation oper)
{
int ret;
switch (oper) {
case NL80211_TDLS_DISCOVERY_REQ:
ret = BRCMF_TDLS_MANUAL_EP_DISCOVERY;
break;
case NL80211_TDLS_SETUP:
ret = BRCMF_TDLS_MANUAL_EP_CREATE;
break;
case NL80211_TDLS_TEARDOWN:
ret = BRCMF_TDLS_MANUAL_EP_DELETE;
break;
default:
brcmf_err("unsupported operation: %d\n", oper);
ret = -EOPNOTSUPP;
}
return ret;
}
static int brcmf_cfg80211_tdls_oper(struct wiphy *wiphy,
struct net_device *ndev, const u8 *peer,
enum nl80211_tdls_operation oper)
{
struct brcmf_if *ifp;
struct brcmf_tdls_iovar_le info;
int ret = 0;
ret = brcmf_convert_nl80211_tdls_oper(oper);
if (ret < 0)
return ret;
ifp = netdev_priv(ndev);
memset(&info, 0, sizeof(info));
info.mode = (u8)ret;
if (peer)
memcpy(info.ea, peer, ETH_ALEN);
ret = brcmf_fil_iovar_data_set(ifp, "tdls_endpoint",
&info, sizeof(info));
if (ret < 0)
brcmf_err("tdls_endpoint iovar failed: ret=%d\n", ret);
return ret;
}
#ifdef CONFIG_PM
static int
brcmf_cfg80211_set_rekey_data(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_gtk_rekey_data *gtk)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_gtk_keyinfo_le gtk_le;
int ret;
brcmf_dbg(TRACE, "Enter, bssidx=%d\n", ifp->bsscfgidx);
memcpy(gtk_le.kck, gtk->kck, sizeof(gtk_le.kck));
memcpy(gtk_le.kek, gtk->kek, sizeof(gtk_le.kek));
memcpy(gtk_le.replay_counter, gtk->replay_ctr,
sizeof(gtk_le.replay_counter));
ret = brcmf_fil_iovar_data_set(ifp, "gtk_key_info", >k_le,
sizeof(gtk_le));
if (ret < 0)
brcmf_err("gtk_key_info iovar failed: ret=%d\n", ret);
return ret;
}
#endif
static struct cfg80211_ops brcmf_cfg80211_ops = {
.add_virtual_intf = brcmf_cfg80211_add_iface,
.del_virtual_intf = brcmf_cfg80211_del_iface,
.change_virtual_intf = brcmf_cfg80211_change_iface,
.scan = brcmf_cfg80211_scan,
.set_wiphy_params = brcmf_cfg80211_set_wiphy_params,
.join_ibss = brcmf_cfg80211_join_ibss,
.leave_ibss = brcmf_cfg80211_leave_ibss,
.get_station = brcmf_cfg80211_get_station,
.dump_station = brcmf_cfg80211_dump_station,
.set_tx_power = brcmf_cfg80211_set_tx_power,
.get_tx_power = brcmf_cfg80211_get_tx_power,
.add_key = brcmf_cfg80211_add_key,
.del_key = brcmf_cfg80211_del_key,
.get_key = brcmf_cfg80211_get_key,
.set_default_key = brcmf_cfg80211_config_default_key,
.set_default_mgmt_key = brcmf_cfg80211_config_default_mgmt_key,
.set_power_mgmt = brcmf_cfg80211_set_power_mgmt,
.connect = brcmf_cfg80211_connect,
.disconnect = brcmf_cfg80211_disconnect,
.suspend = brcmf_cfg80211_suspend,
.resume = brcmf_cfg80211_resume,
.set_pmksa = brcmf_cfg80211_set_pmksa,
.del_pmksa = brcmf_cfg80211_del_pmksa,
.flush_pmksa = brcmf_cfg80211_flush_pmksa,
.start_ap = brcmf_cfg80211_start_ap,
.stop_ap = brcmf_cfg80211_stop_ap,
.change_beacon = brcmf_cfg80211_change_beacon,
.del_station = brcmf_cfg80211_del_station,
.change_station = brcmf_cfg80211_change_station,
.sched_scan_start = brcmf_cfg80211_sched_scan_start,
.sched_scan_stop = brcmf_cfg80211_sched_scan_stop,
.mgmt_frame_register = brcmf_cfg80211_mgmt_frame_register,
.mgmt_tx = brcmf_cfg80211_mgmt_tx,
.remain_on_channel = brcmf_p2p_remain_on_channel,
.cancel_remain_on_channel = brcmf_cfg80211_cancel_remain_on_channel,
.get_channel = brcmf_cfg80211_get_channel,
.start_p2p_device = brcmf_p2p_start_device,
.stop_p2p_device = brcmf_p2p_stop_device,
.crit_proto_start = brcmf_cfg80211_crit_proto_start,
.crit_proto_stop = brcmf_cfg80211_crit_proto_stop,
.tdls_oper = brcmf_cfg80211_tdls_oper,
};
struct brcmf_cfg80211_vif *brcmf_alloc_vif(struct brcmf_cfg80211_info *cfg,
enum nl80211_iftype type)
{
struct brcmf_cfg80211_vif *vif_walk;
struct brcmf_cfg80211_vif *vif;
bool mbss;
brcmf_dbg(TRACE, "allocating virtual interface (size=%zu)\n",
sizeof(*vif));
vif = kzalloc(sizeof(*vif), GFP_KERNEL);
if (!vif)
return ERR_PTR(-ENOMEM);
vif->wdev.wiphy = cfg->wiphy;
vif->wdev.iftype = type;
brcmf_init_prof(&vif->profile);
if (type == NL80211_IFTYPE_AP) {
mbss = false;
list_for_each_entry(vif_walk, &cfg->vif_list, list) {
if (vif_walk->wdev.iftype == NL80211_IFTYPE_AP) {
mbss = true;
break;
}
}
vif->mbss = mbss;
}
list_add_tail(&vif->list, &cfg->vif_list);
return vif;
}
void brcmf_free_vif(struct brcmf_cfg80211_vif *vif)
{
list_del(&vif->list);
kfree(vif);
}
void brcmf_cfg80211_free_netdev(struct net_device *ndev)
{
struct brcmf_cfg80211_vif *vif;
struct brcmf_if *ifp;
ifp = netdev_priv(ndev);
vif = ifp->vif;
if (vif)
brcmf_free_vif(vif);
free_netdev(ndev);
}
static bool brcmf_is_linkup(const struct brcmf_event_msg *e)
{
u32 event = e->event_code;
u32 status = e->status;
if (event == BRCMF_E_SET_SSID && status == BRCMF_E_STATUS_SUCCESS) {
brcmf_dbg(CONN, "Processing set ssid\n");
return true;
}
return false;
}
static bool brcmf_is_linkdown(const struct brcmf_event_msg *e)
{
u32 event = e->event_code;
u16 flags = e->flags;
if ((event == BRCMF_E_DEAUTH) || (event == BRCMF_E_DEAUTH_IND) ||
(event == BRCMF_E_DISASSOC_IND) ||
((event == BRCMF_E_LINK) && (!(flags & BRCMF_EVENT_MSG_LINK)))) {
brcmf_dbg(CONN, "Processing link down\n");
return true;
}
return false;
}
static bool brcmf_is_nonetwork(struct brcmf_cfg80211_info *cfg,
const struct brcmf_event_msg *e)
{
u32 event = e->event_code;
u32 status = e->status;
if (event == BRCMF_E_LINK && status == BRCMF_E_STATUS_NO_NETWORKS) {
brcmf_dbg(CONN, "Processing Link %s & no network found\n",
e->flags & BRCMF_EVENT_MSG_LINK ? "up" : "down");
return true;
}
if (event == BRCMF_E_SET_SSID && status != BRCMF_E_STATUS_SUCCESS) {
brcmf_dbg(CONN, "Processing connecting & no network found\n");
return true;
}
return false;
}
static void brcmf_clear_assoc_ies(struct brcmf_cfg80211_info *cfg)
{
struct brcmf_cfg80211_connect_info *conn_info = cfg_to_conn(cfg);
kfree(conn_info->req_ie);
conn_info->req_ie = NULL;
conn_info->req_ie_len = 0;
kfree(conn_info->resp_ie);
conn_info->resp_ie = NULL;
conn_info->resp_ie_len = 0;
}
static s32 brcmf_get_assoc_ies(struct brcmf_cfg80211_info *cfg,
struct brcmf_if *ifp)
{
struct brcmf_cfg80211_assoc_ielen_le *assoc_info;
struct brcmf_cfg80211_connect_info *conn_info = cfg_to_conn(cfg);
u32 req_len;
u32 resp_len;
s32 err = 0;
brcmf_clear_assoc_ies(cfg);
err = brcmf_fil_iovar_data_get(ifp, "assoc_info",
cfg->extra_buf, WL_ASSOC_INFO_MAX);
if (err) {
brcmf_err("could not get assoc info (%d)\n", err);
return err;
}
assoc_info =
(struct brcmf_cfg80211_assoc_ielen_le *)cfg->extra_buf;
req_len = le32_to_cpu(assoc_info->req_len);
resp_len = le32_to_cpu(assoc_info->resp_len);
if (req_len) {
err = brcmf_fil_iovar_data_get(ifp, "assoc_req_ies",
cfg->extra_buf,
WL_ASSOC_INFO_MAX);
if (err) {
brcmf_err("could not get assoc req (%d)\n", err);
return err;
}
conn_info->req_ie_len = req_len;
conn_info->req_ie =
kmemdup(cfg->extra_buf, conn_info->req_ie_len,
GFP_KERNEL);
} else {
conn_info->req_ie_len = 0;
conn_info->req_ie = NULL;
}
if (resp_len) {
err = brcmf_fil_iovar_data_get(ifp, "assoc_resp_ies",
cfg->extra_buf,
WL_ASSOC_INFO_MAX);
if (err) {
brcmf_err("could not get assoc resp (%d)\n", err);
return err;
}
conn_info->resp_ie_len = resp_len;
conn_info->resp_ie =
kmemdup(cfg->extra_buf, conn_info->resp_ie_len,
GFP_KERNEL);
} else {
conn_info->resp_ie_len = 0;
conn_info->resp_ie = NULL;
}
brcmf_dbg(CONN, "req len (%d) resp len (%d)\n",
conn_info->req_ie_len, conn_info->resp_ie_len);
return err;
}
static s32
brcmf_bss_roaming_done(struct brcmf_cfg80211_info *cfg,
struct net_device *ndev,
const struct brcmf_event_msg *e)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct brcmf_cfg80211_connect_info *conn_info = cfg_to_conn(cfg);
struct wiphy *wiphy = cfg_to_wiphy(cfg);
struct ieee80211_channel *notify_channel = NULL;
struct ieee80211_supported_band *band;
struct brcmf_bss_info_le *bi;
struct brcmu_chan ch;
u32 freq;
s32 err = 0;
u8 *buf;
brcmf_dbg(TRACE, "Enter\n");
brcmf_get_assoc_ies(cfg, ifp);
memcpy(profile->bssid, e->addr, ETH_ALEN);
brcmf_update_bss_info(cfg, ifp);
buf = kzalloc(WL_BSS_INFO_MAX, GFP_KERNEL);
if (buf == NULL) {
err = -ENOMEM;
goto done;
}
/* data sent to dongle has to be little endian */
*(__le32 *)buf = cpu_to_le32(WL_BSS_INFO_MAX);
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_BSS_INFO,
buf, WL_BSS_INFO_MAX);
if (err)
goto done;
bi = (struct brcmf_bss_info_le *)(buf + 4);
ch.chspec = le16_to_cpu(bi->chanspec);
cfg->d11inf.decchspec(&ch);
if (ch.band == BRCMU_CHAN_BAND_2G)
band = wiphy->bands[NL80211_BAND_2GHZ];
else
band = wiphy->bands[NL80211_BAND_5GHZ];
freq = ieee80211_channel_to_frequency(ch.control_ch_num, band->band);
notify_channel = ieee80211_get_channel(wiphy, freq);
done:
kfree(buf);
cfg80211_roamed(ndev, notify_channel, (u8 *)profile->bssid,
conn_info->req_ie, conn_info->req_ie_len,
conn_info->resp_ie, conn_info->resp_ie_len, GFP_KERNEL);
brcmf_dbg(CONN, "Report roaming result\n");
set_bit(BRCMF_VIF_STATUS_CONNECTED, &ifp->vif->sme_state);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_bss_connect_done(struct brcmf_cfg80211_info *cfg,
struct net_device *ndev, const struct brcmf_event_msg *e,
bool completed)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct brcmf_cfg80211_connect_info *conn_info = cfg_to_conn(cfg);
brcmf_dbg(TRACE, "Enter\n");
if (test_and_clear_bit(BRCMF_VIF_STATUS_CONNECTING,
&ifp->vif->sme_state)) {
if (completed) {
brcmf_get_assoc_ies(cfg, ifp);
memcpy(profile->bssid, e->addr, ETH_ALEN);
brcmf_update_bss_info(cfg, ifp);
set_bit(BRCMF_VIF_STATUS_CONNECTED,
&ifp->vif->sme_state);
}
cfg80211_connect_result(ndev,
(u8 *)profile->bssid,
conn_info->req_ie,
conn_info->req_ie_len,
conn_info->resp_ie,
conn_info->resp_ie_len,
completed ? WLAN_STATUS_SUCCESS :
WLAN_STATUS_AUTH_TIMEOUT,
GFP_KERNEL);
brcmf_dbg(CONN, "Report connect result - connection %s\n",
completed ? "succeeded" : "failed");
}
brcmf_dbg(TRACE, "Exit\n");
return 0;
}
static s32
brcmf_notify_connect_status_ap(struct brcmf_cfg80211_info *cfg,
struct net_device *ndev,
const struct brcmf_event_msg *e, void *data)
{
static int generation;
u32 event = e->event_code;
u32 reason = e->reason;
struct station_info sinfo;
brcmf_dbg(CONN, "event %d, reason %d\n", event, reason);
if (event == BRCMF_E_LINK && reason == BRCMF_E_REASON_LINK_BSSCFG_DIS &&
ndev != cfg_to_ndev(cfg)) {
brcmf_dbg(CONN, "AP mode link down\n");
complete(&cfg->vif_disabled);
return 0;
}
if (((event == BRCMF_E_ASSOC_IND) || (event == BRCMF_E_REASSOC_IND)) &&
(reason == BRCMF_E_STATUS_SUCCESS)) {
memset(&sinfo, 0, sizeof(sinfo));
if (!data) {
brcmf_err("No IEs present in ASSOC/REASSOC_IND");
return -EINVAL;
}
sinfo.assoc_req_ies = data;
sinfo.assoc_req_ies_len = e->datalen;
generation++;
sinfo.generation = generation;
cfg80211_new_sta(ndev, e->addr, &sinfo, GFP_KERNEL);
} else if ((event == BRCMF_E_DISASSOC_IND) ||
(event == BRCMF_E_DEAUTH_IND) ||
(event == BRCMF_E_DEAUTH)) {
cfg80211_del_sta(ndev, e->addr, GFP_KERNEL);
}
return 0;
}
static s32
brcmf_notify_connect_status(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct net_device *ndev = ifp->ndev;
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct ieee80211_channel *chan;
s32 err = 0;
if ((e->event_code == BRCMF_E_DEAUTH) ||
(e->event_code == BRCMF_E_DEAUTH_IND) ||
(e->event_code == BRCMF_E_DISASSOC_IND) ||
((e->event_code == BRCMF_E_LINK) && (!e->flags))) {
brcmf_proto_delete_peer(ifp->drvr, ifp->ifidx, (u8 *)e->addr);
}
if (brcmf_is_apmode(ifp->vif)) {
err = brcmf_notify_connect_status_ap(cfg, ndev, e, data);
} else if (brcmf_is_linkup(e)) {
brcmf_dbg(CONN, "Linkup\n");
if (brcmf_is_ibssmode(ifp->vif)) {
brcmf_inform_ibss(cfg, ndev, e->addr);
chan = ieee80211_get_channel(cfg->wiphy, cfg->channel);
memcpy(profile->bssid, e->addr, ETH_ALEN);
cfg80211_ibss_joined(ndev, e->addr, chan, GFP_KERNEL);
clear_bit(BRCMF_VIF_STATUS_CONNECTING,
&ifp->vif->sme_state);
set_bit(BRCMF_VIF_STATUS_CONNECTED,
&ifp->vif->sme_state);
} else
brcmf_bss_connect_done(cfg, ndev, e, true);
brcmf_net_setcarrier(ifp, true);
} else if (brcmf_is_linkdown(e)) {
brcmf_dbg(CONN, "Linkdown\n");
if (!brcmf_is_ibssmode(ifp->vif)) {
brcmf_bss_connect_done(cfg, ndev, e, false);
brcmf_link_down(ifp->vif,
brcmf_map_fw_linkdown_reason(e));
brcmf_init_prof(ndev_to_prof(ndev));
if (ndev != cfg_to_ndev(cfg))
complete(&cfg->vif_disabled);
brcmf_net_setcarrier(ifp, false);
}
} else if (brcmf_is_nonetwork(cfg, e)) {
if (brcmf_is_ibssmode(ifp->vif))
clear_bit(BRCMF_VIF_STATUS_CONNECTING,
&ifp->vif->sme_state);
else
brcmf_bss_connect_done(cfg, ndev, e, false);
}
return err;
}
static s32
brcmf_notify_roaming_status(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
u32 event = e->event_code;
u32 status = e->status;
if (event == BRCMF_E_ROAM && status == BRCMF_E_STATUS_SUCCESS) {
if (test_bit(BRCMF_VIF_STATUS_CONNECTED, &ifp->vif->sme_state))
brcmf_bss_roaming_done(cfg, ifp->ndev, e);
else
brcmf_bss_connect_done(cfg, ifp->ndev, e, true);
}
return 0;
}
static s32
brcmf_notify_mic_status(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
u16 flags = e->flags;
enum nl80211_key_type key_type;
if (flags & BRCMF_EVENT_MSG_GROUP)
key_type = NL80211_KEYTYPE_GROUP;
else
key_type = NL80211_KEYTYPE_PAIRWISE;
cfg80211_michael_mic_failure(ifp->ndev, (u8 *)&e->addr, key_type, -1,
NULL, GFP_KERNEL);
return 0;
}
static s32 brcmf_notify_vif_event(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct brcmf_if_event *ifevent = (struct brcmf_if_event *)data;
struct brcmf_cfg80211_vif_event *event = &cfg->vif_event;
struct brcmf_cfg80211_vif *vif;
brcmf_dbg(TRACE, "Enter: action %u flags %u ifidx %u bsscfgidx %u\n",
ifevent->action, ifevent->flags, ifevent->ifidx,
ifevent->bsscfgidx);
spin_lock(&event->vif_event_lock);
event->action = ifevent->action;
vif = event->vif;
switch (ifevent->action) {
case BRCMF_E_IF_ADD:
/* waiting process may have timed out */
if (!cfg->vif_event.vif) {
spin_unlock(&event->vif_event_lock);
return -EBADF;
}
ifp->vif = vif;
vif->ifp = ifp;
if (ifp->ndev) {
vif->wdev.netdev = ifp->ndev;
ifp->ndev->ieee80211_ptr = &vif->wdev;
SET_NETDEV_DEV(ifp->ndev, wiphy_dev(cfg->wiphy));
}
spin_unlock(&event->vif_event_lock);
wake_up(&event->vif_wq);
return 0;
case BRCMF_E_IF_DEL:
spin_unlock(&event->vif_event_lock);
/* event may not be upon user request */
if (brcmf_cfg80211_vif_event_armed(cfg))
wake_up(&event->vif_wq);
return 0;
case BRCMF_E_IF_CHANGE:
spin_unlock(&event->vif_event_lock);
wake_up(&event->vif_wq);
return 0;
default:
spin_unlock(&event->vif_event_lock);
break;
}
return -EINVAL;
}
static void brcmf_init_conf(struct brcmf_cfg80211_conf *conf)
{
conf->frag_threshold = (u32)-1;
conf->rts_threshold = (u32)-1;
conf->retry_short = (u32)-1;
conf->retry_long = (u32)-1;
}
static void brcmf_register_event_handlers(struct brcmf_cfg80211_info *cfg)
{
brcmf_fweh_register(cfg->pub, BRCMF_E_LINK,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_DEAUTH_IND,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_DEAUTH,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_DISASSOC_IND,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_ASSOC_IND,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_REASSOC_IND,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_ROAM,
brcmf_notify_roaming_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_MIC_ERROR,
brcmf_notify_mic_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_SET_SSID,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_PFN_NET_FOUND,
brcmf_notify_sched_scan_results);
brcmf_fweh_register(cfg->pub, BRCMF_E_IF,
brcmf_notify_vif_event);
brcmf_fweh_register(cfg->pub, BRCMF_E_P2P_PROBEREQ_MSG,
brcmf_p2p_notify_rx_mgmt_p2p_probereq);
brcmf_fweh_register(cfg->pub, BRCMF_E_P2P_DISC_LISTEN_COMPLETE,
brcmf_p2p_notify_listen_complete);
brcmf_fweh_register(cfg->pub, BRCMF_E_ACTION_FRAME_RX,
brcmf_p2p_notify_action_frame_rx);
brcmf_fweh_register(cfg->pub, BRCMF_E_ACTION_FRAME_COMPLETE,
brcmf_p2p_notify_action_tx_complete);
brcmf_fweh_register(cfg->pub, BRCMF_E_ACTION_FRAME_OFF_CHAN_COMPLETE,
brcmf_p2p_notify_action_tx_complete);
}
static void brcmf_deinit_priv_mem(struct brcmf_cfg80211_info *cfg)
{
kfree(cfg->conf);
cfg->conf = NULL;
kfree(cfg->extra_buf);
cfg->extra_buf = NULL;
kfree(cfg->wowl.nd);
cfg->wowl.nd = NULL;
kfree(cfg->wowl.nd_info);
cfg->wowl.nd_info = NULL;
kfree(cfg->escan_info.escan_buf);
cfg->escan_info.escan_buf = NULL;
}
static s32 brcmf_init_priv_mem(struct brcmf_cfg80211_info *cfg)
{
cfg->conf = kzalloc(sizeof(*cfg->conf), GFP_KERNEL);
if (!cfg->conf)
goto init_priv_mem_out;
cfg->extra_buf = kzalloc(WL_EXTRA_BUF_MAX, GFP_KERNEL);
if (!cfg->extra_buf)
goto init_priv_mem_out;
cfg->wowl.nd = kzalloc(sizeof(*cfg->wowl.nd) + sizeof(u32), GFP_KERNEL);
if (!cfg->wowl.nd)
goto init_priv_mem_out;
cfg->wowl.nd_info = kzalloc(sizeof(*cfg->wowl.nd_info) +
sizeof(struct cfg80211_wowlan_nd_match *),
GFP_KERNEL);
if (!cfg->wowl.nd_info)
goto init_priv_mem_out;
cfg->escan_info.escan_buf = kzalloc(BRCMF_ESCAN_BUF_SIZE, GFP_KERNEL);
if (!cfg->escan_info.escan_buf)
goto init_priv_mem_out;
return 0;
init_priv_mem_out:
brcmf_deinit_priv_mem(cfg);
return -ENOMEM;
}
static s32 wl_init_priv(struct brcmf_cfg80211_info *cfg)
{
s32 err = 0;
cfg->scan_request = NULL;
cfg->pwr_save = true;
cfg->active_scan = true; /* we do active scan per default */
cfg->dongle_up = false; /* dongle is not up yet */
err = brcmf_init_priv_mem(cfg);
if (err)
return err;
brcmf_register_event_handlers(cfg);
mutex_init(&cfg->usr_sync);
brcmf_init_escan(cfg);
brcmf_init_conf(cfg->conf);
init_completion(&cfg->vif_disabled);
return err;
}
static void wl_deinit_priv(struct brcmf_cfg80211_info *cfg)
{
cfg->dongle_up = false; /* dongle down */
brcmf_abort_scanning(cfg);
brcmf_deinit_priv_mem(cfg);
}
static void init_vif_event(struct brcmf_cfg80211_vif_event *event)
{
init_waitqueue_head(&event->vif_wq);
spin_lock_init(&event->vif_event_lock);
}
static s32 brcmf_dongle_roam(struct brcmf_if *ifp)
{
s32 err;
u32 bcn_timeout;
__le32 roamtrigger[2];
__le32 roam_delta[2];
/* Configure beacon timeout value based upon roaming setting */
if (ifp->drvr->settings->roamoff)
bcn_timeout = BRCMF_DEFAULT_BCN_TIMEOUT_ROAM_OFF;
else
bcn_timeout = BRCMF_DEFAULT_BCN_TIMEOUT_ROAM_ON;
err = brcmf_fil_iovar_int_set(ifp, "bcn_timeout", bcn_timeout);
if (err) {
brcmf_err("bcn_timeout error (%d)\n", err);
goto roam_setup_done;
}
/* Enable/Disable built-in roaming to allow supplicant to take care of
* roaming.
*/
brcmf_dbg(INFO, "Internal Roaming = %s\n",
ifp->drvr->settings->roamoff ? "Off" : "On");
err = brcmf_fil_iovar_int_set(ifp, "roam_off",
ifp->drvr->settings->roamoff);
if (err) {
brcmf_err("roam_off error (%d)\n", err);
goto roam_setup_done;
}
roamtrigger[0] = cpu_to_le32(WL_ROAM_TRIGGER_LEVEL);
roamtrigger[1] = cpu_to_le32(BRCM_BAND_ALL);
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_ROAM_TRIGGER,
(void *)roamtrigger, sizeof(roamtrigger));
if (err) {
brcmf_err("WLC_SET_ROAM_TRIGGER error (%d)\n", err);
goto roam_setup_done;
}
roam_delta[0] = cpu_to_le32(WL_ROAM_DELTA);
roam_delta[1] = cpu_to_le32(BRCM_BAND_ALL);
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_ROAM_DELTA,
(void *)roam_delta, sizeof(roam_delta));
if (err) {
brcmf_err("WLC_SET_ROAM_DELTA error (%d)\n", err);
goto roam_setup_done;
}
roam_setup_done:
return err;
}
static s32
brcmf_dongle_scantime(struct brcmf_if *ifp)
{
s32 err = 0;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_SCAN_CHANNEL_TIME,
BRCMF_SCAN_CHANNEL_TIME);
if (err) {
brcmf_err("Scan assoc time error (%d)\n", err);
goto dongle_scantime_out;
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_SCAN_UNASSOC_TIME,
BRCMF_SCAN_UNASSOC_TIME);
if (err) {
brcmf_err("Scan unassoc time error (%d)\n", err);
goto dongle_scantime_out;
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_SCAN_PASSIVE_TIME,
BRCMF_SCAN_PASSIVE_TIME);
if (err) {
brcmf_err("Scan passive time error (%d)\n", err);
goto dongle_scantime_out;
}
dongle_scantime_out:
return err;
}
static void brcmf_update_bw40_channel_flag(struct ieee80211_channel *channel,
struct brcmu_chan *ch)
{
u32 ht40_flag;
ht40_flag = channel->flags & IEEE80211_CHAN_NO_HT40;
if (ch->sb == BRCMU_CHAN_SB_U) {
if (ht40_flag == IEEE80211_CHAN_NO_HT40)
channel->flags &= ~IEEE80211_CHAN_NO_HT40;
channel->flags |= IEEE80211_CHAN_NO_HT40PLUS;
} else {
/* It should be one of
* IEEE80211_CHAN_NO_HT40 or
* IEEE80211_CHAN_NO_HT40PLUS
*/
channel->flags &= ~IEEE80211_CHAN_NO_HT40;
if (ht40_flag == IEEE80211_CHAN_NO_HT40)
channel->flags |= IEEE80211_CHAN_NO_HT40MINUS;
}
}
static int brcmf_construct_chaninfo(struct brcmf_cfg80211_info *cfg,
u32 bw_cap[])
{
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
struct ieee80211_supported_band *band;
struct ieee80211_channel *channel;
struct wiphy *wiphy;
struct brcmf_chanspec_list *list;
struct brcmu_chan ch;
int err;
u8 *pbuf;
u32 i, j;
u32 total;
u32 chaninfo;
u32 index;
pbuf = kzalloc(BRCMF_DCMD_MEDLEN, GFP_KERNEL);
if (pbuf == NULL)
return -ENOMEM;
list = (struct brcmf_chanspec_list *)pbuf;
err = brcmf_fil_iovar_data_get(ifp, "chanspecs", pbuf,
BRCMF_DCMD_MEDLEN);
if (err) {
brcmf_err("get chanspecs error (%d)\n", err);
goto fail_pbuf;
}
wiphy = cfg_to_wiphy(cfg);
band = wiphy->bands[NL80211_BAND_2GHZ];
if (band)
for (i = 0; i < band->n_channels; i++)
band->channels[i].flags = IEEE80211_CHAN_DISABLED;
band = wiphy->bands[NL80211_BAND_5GHZ];
if (band)
for (i = 0; i < band->n_channels; i++)
band->channels[i].flags = IEEE80211_CHAN_DISABLED;
total = le32_to_cpu(list->count);
for (i = 0; i < total; i++) {
ch.chspec = (u16)le32_to_cpu(list->element[i]);
cfg->d11inf.decchspec(&ch);
if (ch.band == BRCMU_CHAN_BAND_2G) {
band = wiphy->bands[NL80211_BAND_2GHZ];
} else if (ch.band == BRCMU_CHAN_BAND_5G) {
band = wiphy->bands[NL80211_BAND_5GHZ];
} else {
brcmf_err("Invalid channel Spec. 0x%x.\n", ch.chspec);
continue;
}
if (!band)
continue;
if (!(bw_cap[band->band] & WLC_BW_40MHZ_BIT) &&
ch.bw == BRCMU_CHAN_BW_40)
continue;
if (!(bw_cap[band->band] & WLC_BW_80MHZ_BIT) &&
ch.bw == BRCMU_CHAN_BW_80)
continue;
channel = band->channels;
index = band->n_channels;
for (j = 0; j < band->n_channels; j++) {
if (channel[j].hw_value == ch.control_ch_num) {
index = j;
break;
}
}
channel[index].center_freq =
ieee80211_channel_to_frequency(ch.control_ch_num,
band->band);
channel[index].hw_value = ch.control_ch_num;
/* assuming the chanspecs order is HT20,
* HT40 upper, HT40 lower, and VHT80.
*/
if (ch.bw == BRCMU_CHAN_BW_80) {
channel[index].flags &= ~IEEE80211_CHAN_NO_80MHZ;
} else if (ch.bw == BRCMU_CHAN_BW_40) {
brcmf_update_bw40_channel_flag(&channel[index], &ch);
} else {
/* enable the channel and disable other bandwidths
* for now as mentioned order assure they are enabled
* for subsequent chanspecs.
*/
channel[index].flags = IEEE80211_CHAN_NO_HT40 |
IEEE80211_CHAN_NO_80MHZ;
ch.bw = BRCMU_CHAN_BW_20;
cfg->d11inf.encchspec(&ch);
chaninfo = ch.chspec;
err = brcmf_fil_bsscfg_int_get(ifp, "per_chan_info",
&chaninfo);
if (!err) {
if (chaninfo & WL_CHAN_RADAR)
channel[index].flags |=
(IEEE80211_CHAN_RADAR |
IEEE80211_CHAN_NO_IR);
if (chaninfo & WL_CHAN_PASSIVE)
channel[index].flags |=
IEEE80211_CHAN_NO_IR;
}
}
}
fail_pbuf:
kfree(pbuf);
return err;
}
static int brcmf_enable_bw40_2g(struct brcmf_cfg80211_info *cfg)
{
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
struct ieee80211_supported_band *band;
struct brcmf_fil_bwcap_le band_bwcap;
struct brcmf_chanspec_list *list;
u8 *pbuf;
u32 val;
int err;
struct brcmu_chan ch;
u32 num_chan;
int i, j;
/* verify support for bw_cap command */
val = WLC_BAND_5G;
err = brcmf_fil_iovar_int_get(ifp, "bw_cap", &val);
if (!err) {
/* only set 2G bandwidth using bw_cap command */
band_bwcap.band = cpu_to_le32(WLC_BAND_2G);
band_bwcap.bw_cap = cpu_to_le32(WLC_BW_CAP_40MHZ);
err = brcmf_fil_iovar_data_set(ifp, "bw_cap", &band_bwcap,
sizeof(band_bwcap));
} else {
brcmf_dbg(INFO, "fallback to mimo_bw_cap\n");
val = WLC_N_BW_40ALL;
err = brcmf_fil_iovar_int_set(ifp, "mimo_bw_cap", val);
}
if (!err) {
/* update channel info in 2G band */
pbuf = kzalloc(BRCMF_DCMD_MEDLEN, GFP_KERNEL);
if (pbuf == NULL)
return -ENOMEM;
ch.band = BRCMU_CHAN_BAND_2G;
ch.bw = BRCMU_CHAN_BW_40;
ch.sb = BRCMU_CHAN_SB_NONE;
ch.chnum = 0;
cfg->d11inf.encchspec(&ch);
/* pass encoded chanspec in query */
*(__le16 *)pbuf = cpu_to_le16(ch.chspec);
err = brcmf_fil_iovar_data_get(ifp, "chanspecs", pbuf,
BRCMF_DCMD_MEDLEN);
if (err) {
brcmf_err("get chanspecs error (%d)\n", err);
kfree(pbuf);
return err;
}
band = cfg_to_wiphy(cfg)->bands[NL80211_BAND_2GHZ];
list = (struct brcmf_chanspec_list *)pbuf;
num_chan = le32_to_cpu(list->count);
for (i = 0; i < num_chan; i++) {
ch.chspec = (u16)le32_to_cpu(list->element[i]);
cfg->d11inf.decchspec(&ch);
if (WARN_ON(ch.band != BRCMU_CHAN_BAND_2G))
continue;
if (WARN_ON(ch.bw != BRCMU_CHAN_BW_40))
continue;
for (j = 0; j < band->n_channels; j++) {
if (band->channels[j].hw_value == ch.control_ch_num)
break;
}
if (WARN_ON(j == band->n_channels))
continue;
brcmf_update_bw40_channel_flag(&band->channels[j], &ch);
}
kfree(pbuf);
}
return err;
}
static void brcmf_get_bwcap(struct brcmf_if *ifp, u32 bw_cap[])
{
u32 band, mimo_bwcap;
int err;
band = WLC_BAND_2G;
err = brcmf_fil_iovar_int_get(ifp, "bw_cap", &band);
if (!err) {
bw_cap[NL80211_BAND_2GHZ] = band;
band = WLC_BAND_5G;
err = brcmf_fil_iovar_int_get(ifp, "bw_cap", &band);
if (!err) {
bw_cap[NL80211_BAND_5GHZ] = band;
return;
}
WARN_ON(1);
return;
}
brcmf_dbg(INFO, "fallback to mimo_bw_cap info\n");
mimo_bwcap = 0;
err = brcmf_fil_iovar_int_get(ifp, "mimo_bw_cap", &mimo_bwcap);
if (err)
/* assume 20MHz if firmware does not give a clue */
mimo_bwcap = WLC_N_BW_20ALL;
switch (mimo_bwcap) {
case WLC_N_BW_40ALL:
bw_cap[NL80211_BAND_2GHZ] |= WLC_BW_40MHZ_BIT;
/* fall-thru */
case WLC_N_BW_20IN2G_40IN5G:
bw_cap[NL80211_BAND_5GHZ] |= WLC_BW_40MHZ_BIT;
/* fall-thru */
case WLC_N_BW_20ALL:
bw_cap[NL80211_BAND_2GHZ] |= WLC_BW_20MHZ_BIT;
bw_cap[NL80211_BAND_5GHZ] |= WLC_BW_20MHZ_BIT;
break;
default:
brcmf_err("invalid mimo_bw_cap value\n");
}
}
static void brcmf_update_ht_cap(struct ieee80211_supported_band *band,
u32 bw_cap[2], u32 nchain)
{
band->ht_cap.ht_supported = true;
if (bw_cap[band->band] & WLC_BW_40MHZ_BIT) {
band->ht_cap.cap |= IEEE80211_HT_CAP_SGI_40;
band->ht_cap.cap |= IEEE80211_HT_CAP_SUP_WIDTH_20_40;
}
band->ht_cap.cap |= IEEE80211_HT_CAP_SGI_20;
band->ht_cap.cap |= IEEE80211_HT_CAP_DSSSCCK40;
band->ht_cap.ampdu_factor = IEEE80211_HT_MAX_AMPDU_64K;
band->ht_cap.ampdu_density = IEEE80211_HT_MPDU_DENSITY_16;
memset(band->ht_cap.mcs.rx_mask, 0xff, nchain);
band->ht_cap.mcs.tx_params = IEEE80211_HT_MCS_TX_DEFINED;
}
static __le16 brcmf_get_mcs_map(u32 nchain, enum ieee80211_vht_mcs_support supp)
{
u16 mcs_map;
int i;
for (i = 0, mcs_map = 0xFFFF; i < nchain; i++)
mcs_map = (mcs_map << 2) | supp;
return cpu_to_le16(mcs_map);
}
static void brcmf_update_vht_cap(struct ieee80211_supported_band *band,
u32 bw_cap[2], u32 nchain, u32 txstreams,
u32 txbf_bfe_cap, u32 txbf_bfr_cap)
{
__le16 mcs_map;
/* not allowed in 2.4G band */
if (band->band == NL80211_BAND_2GHZ)
return;
band->vht_cap.vht_supported = true;
/* 80MHz is mandatory */
band->vht_cap.cap |= IEEE80211_VHT_CAP_SHORT_GI_80;
if (bw_cap[band->band] & WLC_BW_160MHZ_BIT) {
band->vht_cap.cap |= IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_160MHZ;
band->vht_cap.cap |= IEEE80211_VHT_CAP_SHORT_GI_160;
}
/* all support 256-QAM */
mcs_map = brcmf_get_mcs_map(nchain, IEEE80211_VHT_MCS_SUPPORT_0_9);
band->vht_cap.vht_mcs.rx_mcs_map = mcs_map;
band->vht_cap.vht_mcs.tx_mcs_map = mcs_map;
/* Beamforming support information */
if (txbf_bfe_cap & BRCMF_TXBF_SU_BFE_CAP)
band->vht_cap.cap |= IEEE80211_VHT_CAP_SU_BEAMFORMEE_CAPABLE;
if (txbf_bfe_cap & BRCMF_TXBF_MU_BFE_CAP)
band->vht_cap.cap |= IEEE80211_VHT_CAP_MU_BEAMFORMEE_CAPABLE;
if (txbf_bfr_cap & BRCMF_TXBF_SU_BFR_CAP)
band->vht_cap.cap |= IEEE80211_VHT_CAP_SU_BEAMFORMER_CAPABLE;
if (txbf_bfr_cap & BRCMF_TXBF_MU_BFR_CAP)
band->vht_cap.cap |= IEEE80211_VHT_CAP_MU_BEAMFORMER_CAPABLE;
if ((txbf_bfe_cap || txbf_bfr_cap) && (txstreams > 1)) {
band->vht_cap.cap |=
(2 << IEEE80211_VHT_CAP_BEAMFORMEE_STS_SHIFT);
band->vht_cap.cap |= ((txstreams - 1) <<
IEEE80211_VHT_CAP_SOUNDING_DIMENSIONS_SHIFT);
band->vht_cap.cap |=
IEEE80211_VHT_CAP_VHT_LINK_ADAPTATION_VHT_MRQ_MFB;
}
}
static int brcmf_setup_wiphybands(struct wiphy *wiphy)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
u32 nmode = 0;
u32 vhtmode = 0;
u32 bw_cap[2] = { WLC_BW_20MHZ_BIT, WLC_BW_20MHZ_BIT };
u32 rxchain;
u32 nchain;
int err;
s32 i;
struct ieee80211_supported_band *band;
u32 txstreams = 0;
u32 txbf_bfe_cap = 0;
u32 txbf_bfr_cap = 0;
(void)brcmf_fil_iovar_int_get(ifp, "vhtmode", &vhtmode);
err = brcmf_fil_iovar_int_get(ifp, "nmode", &nmode);
if (err) {
brcmf_err("nmode error (%d)\n", err);
} else {
brcmf_get_bwcap(ifp, bw_cap);
}
brcmf_dbg(INFO, "nmode=%d, vhtmode=%d, bw_cap=(%d, %d)\n",
nmode, vhtmode, bw_cap[NL80211_BAND_2GHZ],
bw_cap[NL80211_BAND_5GHZ]);
err = brcmf_fil_iovar_int_get(ifp, "rxchain", &rxchain);
if (err) {
brcmf_err("rxchain error (%d)\n", err);
nchain = 1;
} else {
for (nchain = 0; rxchain; nchain++)
rxchain = rxchain & (rxchain - 1);
}
brcmf_dbg(INFO, "nchain=%d\n", nchain);
err = brcmf_construct_chaninfo(cfg, bw_cap);
if (err) {
brcmf_err("brcmf_construct_chaninfo failed (%d)\n", err);
return err;
}
if (vhtmode) {
(void)brcmf_fil_iovar_int_get(ifp, "txstreams", &txstreams);
(void)brcmf_fil_iovar_int_get(ifp, "txbf_bfe_cap",
&txbf_bfe_cap);
(void)brcmf_fil_iovar_int_get(ifp, "txbf_bfr_cap",
&txbf_bfr_cap);
}
wiphy = cfg_to_wiphy(cfg);
for (i = 0; i < ARRAY_SIZE(wiphy->bands); i++) {
band = wiphy->bands[i];
if (band == NULL)
continue;
if (nmode)
brcmf_update_ht_cap(band, bw_cap, nchain);
if (vhtmode)
brcmf_update_vht_cap(band, bw_cap, nchain, txstreams,
txbf_bfe_cap, txbf_bfr_cap);
}
return 0;
}
static const struct ieee80211_txrx_stypes
brcmf_txrx_stypes[NUM_NL80211_IFTYPES] = {
[NL80211_IFTYPE_STATION] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ACTION >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4)
},
[NL80211_IFTYPE_P2P_CLIENT] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ACTION >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4)
},
[NL80211_IFTYPE_P2P_GO] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_REASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4) |
BIT(IEEE80211_STYPE_DISASSOC >> 4) |
BIT(IEEE80211_STYPE_AUTH >> 4) |
BIT(IEEE80211_STYPE_DEAUTH >> 4) |
BIT(IEEE80211_STYPE_ACTION >> 4)
},
[NL80211_IFTYPE_P2P_DEVICE] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ACTION >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4)
}
};
/**
* brcmf_setup_ifmodes() - determine interface modes and combinations.
*
* @wiphy: wiphy object.
* @ifp: interface object needed for feat module api.
*
* The interface modes and combinations are determined dynamically here
* based on firmware functionality.
*
* no p2p and no mbss:
*
* #STA <= 1, #AP <= 1, channels = 1, 2 total
*
* no p2p and mbss:
*
* #STA <= 1, #AP <= 1, channels = 1, 2 total
* #AP <= 4, matching BI, channels = 1, 4 total
*
* p2p, no mchan, and mbss:
*
* #STA <= 1, #P2P-DEV <= 1, #{P2P-CL, P2P-GO} <= 1, channels = 1, 3 total
* #STA <= 1, #P2P-DEV <= 1, #AP <= 1, #P2P-CL <= 1, channels = 1, 4 total
* #AP <= 4, matching BI, channels = 1, 4 total
*
* p2p, mchan, and mbss:
*
* #STA <= 1, #P2P-DEV <= 1, #{P2P-CL, P2P-GO} <= 1, channels = 2, 3 total
* #STA <= 1, #P2P-DEV <= 1, #AP <= 1, #P2P-CL <= 1, channels = 1, 4 total
* #AP <= 4, matching BI, channels = 1, 4 total
*/
static int brcmf_setup_ifmodes(struct wiphy *wiphy, struct brcmf_if *ifp)
{
struct ieee80211_iface_combination *combo = NULL;
struct ieee80211_iface_limit *c0_limits = NULL;
struct ieee80211_iface_limit *p2p_limits = NULL;
struct ieee80211_iface_limit *mbss_limits = NULL;
bool mbss, p2p;
int i, c, n_combos;
mbss = brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MBSS);
p2p = brcmf_feat_is_enabled(ifp, BRCMF_FEAT_P2P);
n_combos = 1 + !!p2p + !!mbss;
combo = kcalloc(n_combos, sizeof(*combo), GFP_KERNEL);
if (!combo)
goto err;
wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC) |
BIT(NL80211_IFTYPE_AP);
c = 0;
i = 0;
c0_limits = kcalloc(p2p ? 3 : 2, sizeof(*c0_limits), GFP_KERNEL);
if (!c0_limits)
goto err;
c0_limits[i].max = 1;
c0_limits[i++].types = BIT(NL80211_IFTYPE_STATION);
if (p2p) {
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MCHAN))
combo[c].num_different_channels = 2;
wiphy->interface_modes |= BIT(NL80211_IFTYPE_P2P_CLIENT) |
BIT(NL80211_IFTYPE_P2P_GO) |
BIT(NL80211_IFTYPE_P2P_DEVICE);
c0_limits[i].max = 1;
c0_limits[i++].types = BIT(NL80211_IFTYPE_P2P_DEVICE);
c0_limits[i].max = 1;
c0_limits[i++].types = BIT(NL80211_IFTYPE_P2P_CLIENT) |
BIT(NL80211_IFTYPE_P2P_GO);
} else {
c0_limits[i].max = 1;
c0_limits[i++].types = BIT(NL80211_IFTYPE_AP);
}
combo[c].num_different_channels = 1;
combo[c].max_interfaces = i;
combo[c].n_limits = i;
combo[c].limits = c0_limits;
if (p2p) {
c++;
i = 0;
p2p_limits = kcalloc(4, sizeof(*p2p_limits), GFP_KERNEL);
if (!p2p_limits)
goto err;
p2p_limits[i].max = 1;
p2p_limits[i++].types = BIT(NL80211_IFTYPE_STATION);
p2p_limits[i].max = 1;
p2p_limits[i++].types = BIT(NL80211_IFTYPE_AP);
p2p_limits[i].max = 1;
p2p_limits[i++].types = BIT(NL80211_IFTYPE_P2P_CLIENT);
p2p_limits[i].max = 1;
p2p_limits[i++].types = BIT(NL80211_IFTYPE_P2P_DEVICE);
combo[c].num_different_channels = 1;
combo[c].max_interfaces = i;
combo[c].n_limits = i;
combo[c].limits = p2p_limits;
}
if (mbss) {
c++;
i = 0;
mbss_limits = kcalloc(1, sizeof(*mbss_limits), GFP_KERNEL);
if (!mbss_limits)
goto err;
mbss_limits[i].max = 4;
mbss_limits[i++].types = BIT(NL80211_IFTYPE_AP);
combo[c].beacon_int_infra_match = true;
combo[c].num_different_channels = 1;
combo[c].max_interfaces = 4;
combo[c].n_limits = i;
combo[c].limits = mbss_limits;
}
wiphy->n_iface_combinations = n_combos;
wiphy->iface_combinations = combo;
return 0;
err:
kfree(c0_limits);
kfree(p2p_limits);
kfree(mbss_limits);
kfree(combo);
return -ENOMEM;
}
static void brcmf_wiphy_pno_params(struct wiphy *wiphy)
{
/* scheduled scan settings */
wiphy->max_sched_scan_ssids = BRCMF_PNO_MAX_PFN_COUNT;
wiphy->max_match_sets = BRCMF_PNO_MAX_PFN_COUNT;
wiphy->max_sched_scan_ie_len = BRCMF_SCAN_IE_LEN_MAX;
wiphy->flags |= WIPHY_FLAG_SUPPORTS_SCHED_SCAN;
}
#ifdef CONFIG_PM
static struct wiphy_wowlan_support brcmf_wowlan_support = {
.flags = WIPHY_WOWLAN_MAGIC_PKT | WIPHY_WOWLAN_DISCONNECT,
.n_patterns = BRCMF_WOWL_MAXPATTERNS,
.pattern_max_len = BRCMF_WOWL_MAXPATTERNSIZE,
.pattern_min_len = 1,
.max_pkt_offset = 1500,
};
#endif
static void brcmf_wiphy_wowl_params(struct wiphy *wiphy, struct brcmf_if *ifp)
{
#ifdef CONFIG_PM
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_PNO)) {
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_ND)) {
brcmf_wowlan_support.flags |= WIPHY_WOWLAN_NET_DETECT;
init_waitqueue_head(&cfg->wowl.nd_data_wait);
}
}
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_GTK)) {
brcmf_wowlan_support.flags |= WIPHY_WOWLAN_SUPPORTS_GTK_REKEY;
brcmf_wowlan_support.flags |= WIPHY_WOWLAN_GTK_REKEY_FAILURE;
}
wiphy->wowlan = &brcmf_wowlan_support;
#endif
}
static int brcmf_setup_wiphy(struct wiphy *wiphy, struct brcmf_if *ifp)
{
struct brcmf_pub *drvr = ifp->drvr;
const struct ieee80211_iface_combination *combo;
struct ieee80211_supported_band *band;
u16 max_interfaces = 0;
__le32 bandlist[3];
u32 n_bands;
int err, i;
wiphy->max_scan_ssids = WL_NUM_SCAN_MAX;
wiphy->max_scan_ie_len = BRCMF_SCAN_IE_LEN_MAX;
wiphy->max_num_pmkids = BRCMF_MAXPMKID;
err = brcmf_setup_ifmodes(wiphy, ifp);
if (err)
return err;
for (i = 0, combo = wiphy->iface_combinations;
i < wiphy->n_iface_combinations; i++, combo++) {
max_interfaces = max(max_interfaces, combo->max_interfaces);
}
for (i = 0; i < max_interfaces && i < ARRAY_SIZE(drvr->addresses);
i++) {
u8 *addr = drvr->addresses[i].addr;
memcpy(addr, drvr->mac, ETH_ALEN);
if (i) {
addr[0] |= BIT(1);
addr[ETH_ALEN - 1] ^= i;
}
}
wiphy->addresses = drvr->addresses;
wiphy->n_addresses = i;
wiphy->signal_type = CFG80211_SIGNAL_TYPE_MBM;
wiphy->cipher_suites = brcmf_cipher_suites;
wiphy->n_cipher_suites = ARRAY_SIZE(brcmf_cipher_suites);
if (!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP))
wiphy->n_cipher_suites--;
wiphy->bss_select_support = BIT(NL80211_BSS_SELECT_ATTR_RSSI) |
BIT(NL80211_BSS_SELECT_ATTR_BAND_PREF) |
BIT(NL80211_BSS_SELECT_ATTR_RSSI_ADJUST);
wiphy->flags |= WIPHY_FLAG_PS_ON_BY_DEFAULT |
WIPHY_FLAG_OFFCHAN_TX |
WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL;
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_TDLS))
wiphy->flags |= WIPHY_FLAG_SUPPORTS_TDLS;
if (!ifp->drvr->settings->roamoff)
wiphy->flags |= WIPHY_FLAG_SUPPORTS_FW_ROAM;
wiphy->mgmt_stypes = brcmf_txrx_stypes;
wiphy->max_remain_on_channel_duration = 5000;
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_PNO))
brcmf_wiphy_pno_params(wiphy);
/* vendor commands/events support */
wiphy->vendor_commands = brcmf_vendor_cmds;
wiphy->n_vendor_commands = BRCMF_VNDR_CMDS_LAST - 1;
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL))
brcmf_wiphy_wowl_params(wiphy, ifp);
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_BANDLIST, &bandlist,
sizeof(bandlist));
if (err) {
brcmf_err("could not obtain band info: err=%d\n", err);
return err;
}
/* first entry in bandlist is number of bands */
n_bands = le32_to_cpu(bandlist[0]);
for (i = 1; i <= n_bands && i < ARRAY_SIZE(bandlist); i++) {
if (bandlist[i] == cpu_to_le32(WLC_BAND_2G)) {
band = kmemdup(&__wl_band_2ghz, sizeof(__wl_band_2ghz),
GFP_KERNEL);
if (!band)
return -ENOMEM;
band->channels = kmemdup(&__wl_2ghz_channels,
sizeof(__wl_2ghz_channels),
GFP_KERNEL);
if (!band->channels) {
kfree(band);
return -ENOMEM;
}
band->n_channels = ARRAY_SIZE(__wl_2ghz_channels);
wiphy->bands[NL80211_BAND_2GHZ] = band;
}
if (bandlist[i] == cpu_to_le32(WLC_BAND_5G)) {
band = kmemdup(&__wl_band_5ghz, sizeof(__wl_band_5ghz),
GFP_KERNEL);
if (!band)
return -ENOMEM;
band->channels = kmemdup(&__wl_5ghz_channels,
sizeof(__wl_5ghz_channels),
GFP_KERNEL);
if (!band->channels) {
kfree(band);
return -ENOMEM;
}
band->n_channels = ARRAY_SIZE(__wl_5ghz_channels);
wiphy->bands[NL80211_BAND_5GHZ] = band;
}
}
err = brcmf_setup_wiphybands(wiphy);
return err;
}
static s32 brcmf_config_dongle(struct brcmf_cfg80211_info *cfg)
{
struct net_device *ndev;
struct wireless_dev *wdev;
struct brcmf_if *ifp;
s32 power_mode;
s32 err = 0;
if (cfg->dongle_up)
return err;
ndev = cfg_to_ndev(cfg);
wdev = ndev->ieee80211_ptr;
ifp = netdev_priv(ndev);
/* make sure RF is ready for work */
brcmf_fil_cmd_int_set(ifp, BRCMF_C_UP, 0);
brcmf_dongle_scantime(ifp);
power_mode = cfg->pwr_save ? PM_FAST : PM_OFF;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PM, power_mode);
if (err)
goto default_conf_out;
brcmf_dbg(INFO, "power save set to %s\n",
(power_mode ? "enabled" : "disabled"));
err = brcmf_dongle_roam(ifp);
if (err)
goto default_conf_out;
err = brcmf_cfg80211_change_iface(wdev->wiphy, ndev, wdev->iftype,
NULL, NULL);
if (err)
goto default_conf_out;
brcmf_configure_arp_nd_offload(ifp, true);
cfg->dongle_up = true;
default_conf_out:
return err;
}
static s32 __brcmf_cfg80211_up(struct brcmf_if *ifp)
{
set_bit(BRCMF_VIF_STATUS_READY, &ifp->vif->sme_state);
return brcmf_config_dongle(ifp->drvr->config);
}
static s32 __brcmf_cfg80211_down(struct brcmf_if *ifp)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
/*
* While going down, if associated with AP disassociate
* from AP to save power
*/
if (check_vif_up(ifp->vif)) {
brcmf_link_down(ifp->vif, WLAN_REASON_UNSPECIFIED);
/* Make sure WPA_Supplicant receives all the event
generated due to DISASSOC call to the fw to keep
the state fw and WPA_Supplicant state consistent
*/
brcmf_delay(500);
}
brcmf_abort_scanning(cfg);
clear_bit(BRCMF_VIF_STATUS_READY, &ifp->vif->sme_state);
return 0;
}
s32 brcmf_cfg80211_up(struct net_device *ndev)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
s32 err = 0;
mutex_lock(&cfg->usr_sync);
err = __brcmf_cfg80211_up(ifp);
mutex_unlock(&cfg->usr_sync);
return err;
}
s32 brcmf_cfg80211_down(struct net_device *ndev)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
s32 err = 0;
mutex_lock(&cfg->usr_sync);
err = __brcmf_cfg80211_down(ifp);
mutex_unlock(&cfg->usr_sync);
return err;
}
enum nl80211_iftype brcmf_cfg80211_get_iftype(struct brcmf_if *ifp)
{
struct wireless_dev *wdev = &ifp->vif->wdev;
return wdev->iftype;
}
bool brcmf_get_vif_state_any(struct brcmf_cfg80211_info *cfg,
unsigned long state)
{
struct brcmf_cfg80211_vif *vif;
list_for_each_entry(vif, &cfg->vif_list, list) {
if (test_bit(state, &vif->sme_state))
return true;
}
return false;
}
static inline bool vif_event_equals(struct brcmf_cfg80211_vif_event *event,
u8 action)
{
u8 evt_action;
spin_lock(&event->vif_event_lock);
evt_action = event->action;
spin_unlock(&event->vif_event_lock);
return evt_action == action;
}
void brcmf_cfg80211_arm_vif_event(struct brcmf_cfg80211_info *cfg,
struct brcmf_cfg80211_vif *vif)
{
struct brcmf_cfg80211_vif_event *event = &cfg->vif_event;
spin_lock(&event->vif_event_lock);
event->vif = vif;
event->action = 0;
spin_unlock(&event->vif_event_lock);
}
bool brcmf_cfg80211_vif_event_armed(struct brcmf_cfg80211_info *cfg)
{
struct brcmf_cfg80211_vif_event *event = &cfg->vif_event;
bool armed;
spin_lock(&event->vif_event_lock);
armed = event->vif != NULL;
spin_unlock(&event->vif_event_lock);
return armed;
}
int brcmf_cfg80211_wait_vif_event(struct brcmf_cfg80211_info *cfg,
u8 action, ulong timeout)
{
struct brcmf_cfg80211_vif_event *event = &cfg->vif_event;
return wait_event_timeout(event->vif_wq,
vif_event_equals(event, action), timeout);
}
static s32 brcmf_translate_country_code(struct brcmf_pub *drvr, char alpha2[2],
struct brcmf_fil_country_le *ccreq)
{
struct brcmfmac_pd_cc *country_codes;
struct brcmfmac_pd_cc_entry *cc;
s32 found_index;
int i;
country_codes = drvr->settings->country_codes;
if (!country_codes) {
brcmf_dbg(TRACE, "No country codes configured for device\n");
return -EINVAL;
}
if ((alpha2[0] == ccreq->country_abbrev[0]) &&
(alpha2[1] == ccreq->country_abbrev[1])) {
brcmf_dbg(TRACE, "Country code already set\n");
return -EAGAIN;
}
found_index = -1;
for (i = 0; i < country_codes->table_size; i++) {
cc = &country_codes->table[i];
if ((cc->iso3166[0] == '\0') && (found_index == -1))
found_index = i;
if ((cc->iso3166[0] == alpha2[0]) &&
(cc->iso3166[1] == alpha2[1])) {
found_index = i;
break;
}
}
if (found_index == -1) {
brcmf_dbg(TRACE, "No country code match found\n");
return -EINVAL;
}
memset(ccreq, 0, sizeof(*ccreq));
ccreq->rev = cpu_to_le32(country_codes->table[found_index].rev);
memcpy(ccreq->ccode, country_codes->table[found_index].cc,
BRCMF_COUNTRY_BUF_SZ);
ccreq->country_abbrev[0] = alpha2[0];
ccreq->country_abbrev[1] = alpha2[1];
ccreq->country_abbrev[2] = 0;
return 0;
}
static void brcmf_cfg80211_reg_notifier(struct wiphy *wiphy,
struct regulatory_request *req)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
struct brcmf_fil_country_le ccreq;
s32 err;
int i;
/* ignore non-ISO3166 country codes */
for (i = 0; i < sizeof(req->alpha2); i++)
if (req->alpha2[i] < 'A' || req->alpha2[i] > 'Z') {
brcmf_err("not a ISO3166 code (0x%02x 0x%02x)\n",
req->alpha2[0], req->alpha2[1]);
return;
}
brcmf_dbg(TRACE, "Enter: initiator=%d, alpha=%c%c\n", req->initiator,
req->alpha2[0], req->alpha2[1]);
err = brcmf_fil_iovar_data_get(ifp, "country", &ccreq, sizeof(ccreq));
if (err) {
brcmf_err("Country code iovar returned err = %d\n", err);
return;
}
err = brcmf_translate_country_code(ifp->drvr, req->alpha2, &ccreq);
if (err)
return;
err = brcmf_fil_iovar_data_set(ifp, "country", &ccreq, sizeof(ccreq));
if (err) {
brcmf_err("Firmware rejected country setting\n");
return;
}
brcmf_setup_wiphybands(wiphy);
}
static void brcmf_free_wiphy(struct wiphy *wiphy)
{
int i;
if (!wiphy)
return;
if (wiphy->iface_combinations) {
for (i = 0; i < wiphy->n_iface_combinations; i++)
kfree(wiphy->iface_combinations[i].limits);
}
kfree(wiphy->iface_combinations);
if (wiphy->bands[NL80211_BAND_2GHZ]) {
kfree(wiphy->bands[NL80211_BAND_2GHZ]->channels);
kfree(wiphy->bands[NL80211_BAND_2GHZ]);
}
if (wiphy->bands[NL80211_BAND_5GHZ]) {
kfree(wiphy->bands[NL80211_BAND_5GHZ]->channels);
kfree(wiphy->bands[NL80211_BAND_5GHZ]);
}
wiphy_free(wiphy);
}
struct brcmf_cfg80211_info *brcmf_cfg80211_attach(struct brcmf_pub *drvr,
struct device *busdev,
bool p2pdev_forced)
{
struct net_device *ndev = brcmf_get_ifp(drvr, 0)->ndev;
struct brcmf_cfg80211_info *cfg;
struct wiphy *wiphy;
struct cfg80211_ops *ops;
struct brcmf_cfg80211_vif *vif;
struct brcmf_if *ifp;
s32 err = 0;
s32 io_type;
u16 *cap = NULL;
if (!ndev) {
brcmf_err("ndev is invalid\n");
return NULL;
}
ops = kmemdup(&brcmf_cfg80211_ops, sizeof(*ops), GFP_KERNEL);
if (!ops)
return NULL;
ifp = netdev_priv(ndev);
#ifdef CONFIG_PM
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_GTK))
ops->set_rekey_data = brcmf_cfg80211_set_rekey_data;
#endif
wiphy = wiphy_new(ops, sizeof(struct brcmf_cfg80211_info));
if (!wiphy) {
brcmf_err("Could not allocate wiphy device\n");
return NULL;
}
memcpy(wiphy->perm_addr, drvr->mac, ETH_ALEN);
set_wiphy_dev(wiphy, busdev);
cfg = wiphy_priv(wiphy);
cfg->wiphy = wiphy;
cfg->ops = ops;
cfg->pub = drvr;
init_vif_event(&cfg->vif_event);
INIT_LIST_HEAD(&cfg->vif_list);
vif = brcmf_alloc_vif(cfg, NL80211_IFTYPE_STATION);
if (IS_ERR(vif))
goto wiphy_out;
vif->ifp = ifp;
vif->wdev.netdev = ndev;
ndev->ieee80211_ptr = &vif->wdev;
SET_NETDEV_DEV(ndev, wiphy_dev(cfg->wiphy));
err = wl_init_priv(cfg);
if (err) {
brcmf_err("Failed to init iwm_priv (%d)\n", err);
brcmf_free_vif(vif);
goto wiphy_out;
}
ifp->vif = vif;
/* determine d11 io type before wiphy setup */
err = brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_VERSION, &io_type);
if (err) {
brcmf_err("Failed to get D11 version (%d)\n", err);
goto priv_out;
}
cfg->d11inf.io_type = (u8)io_type;
brcmu_d11_attach(&cfg->d11inf);
err = brcmf_setup_wiphy(wiphy, ifp);
if (err < 0)
goto priv_out;
brcmf_dbg(INFO, "Registering custom regulatory\n");
wiphy->reg_notifier = brcmf_cfg80211_reg_notifier;
wiphy->regulatory_flags |= REGULATORY_CUSTOM_REG;
wiphy_apply_custom_regulatory(wiphy, &brcmf_regdom);
/* firmware defaults to 40MHz disabled in 2G band. We signal
* cfg80211 here that we do and have it decide we can enable
* it. But first check if device does support 2G operation.
*/
if (wiphy->bands[NL80211_BAND_2GHZ]) {
cap = &wiphy->bands[NL80211_BAND_2GHZ]->ht_cap.cap;
*cap |= IEEE80211_HT_CAP_SUP_WIDTH_20_40;
}
err = wiphy_register(wiphy);
if (err < 0) {
brcmf_err("Could not register wiphy device (%d)\n", err);
goto priv_out;
}
/* If cfg80211 didn't disable 40MHz HT CAP in wiphy_register(),
* setup 40MHz in 2GHz band and enable OBSS scanning.
*/
if (cap && (*cap & IEEE80211_HT_CAP_SUP_WIDTH_20_40)) {
err = brcmf_enable_bw40_2g(cfg);
if (!err)
err = brcmf_fil_iovar_int_set(ifp, "obss_coex",
BRCMF_OBSS_COEX_AUTO);
else
*cap &= ~IEEE80211_HT_CAP_SUP_WIDTH_20_40;
}
/* p2p might require that "if-events" get processed by fweh. So
* activate the already registered event handlers now and activate
* the rest when initialization has completed. drvr->config needs to
* be assigned before activating events.
*/
drvr->config = cfg;
err = brcmf_fweh_activate_events(ifp);
if (err) {
brcmf_err("FWEH activation failed (%d)\n", err);
goto wiphy_unreg_out;
}
err = brcmf_p2p_attach(cfg, p2pdev_forced);
if (err) {
brcmf_err("P2P initilisation failed (%d)\n", err);
goto wiphy_unreg_out;
}
err = brcmf_btcoex_attach(cfg);
if (err) {
brcmf_err("BT-coex initialisation failed (%d)\n", err);
brcmf_p2p_detach(&cfg->p2p);
goto wiphy_unreg_out;
}
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_TDLS)) {
err = brcmf_fil_iovar_int_set(ifp, "tdls_enable", 1);
if (err) {
brcmf_dbg(INFO, "TDLS not enabled (%d)\n", err);
wiphy->flags &= ~WIPHY_FLAG_SUPPORTS_TDLS;
} else {
brcmf_fweh_register(cfg->pub, BRCMF_E_TDLS_PEER_EVENT,
brcmf_notify_tdls_peer_event);
}
}
/* (re-) activate FWEH event handling */
err = brcmf_fweh_activate_events(ifp);
if (err) {
brcmf_err("FWEH activation failed (%d)\n", err);
goto wiphy_unreg_out;
}
/* Fill in some of the advertised nl80211 supported features */
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_SCAN_RANDOM_MAC)) {
wiphy->features |= NL80211_FEATURE_SCHED_SCAN_RANDOM_MAC_ADDR;
#ifdef CONFIG_PM
if (wiphy->wowlan &&
wiphy->wowlan->flags & WIPHY_WOWLAN_NET_DETECT)
wiphy->features |= NL80211_FEATURE_ND_RANDOM_MAC_ADDR;
#endif
}
return cfg;
wiphy_unreg_out:
wiphy_unregister(cfg->wiphy);
priv_out:
wl_deinit_priv(cfg);
brcmf_free_vif(vif);
ifp->vif = NULL;
wiphy_out:
brcmf_free_wiphy(wiphy);
kfree(ops);
return NULL;
}
void brcmf_cfg80211_detach(struct brcmf_cfg80211_info *cfg)
{
if (!cfg)
return;
brcmf_btcoex_detach(cfg);
wiphy_unregister(cfg->wiphy);
kfree(cfg->ops);
wl_deinit_priv(cfg);
brcmf_free_wiphy(cfg->wiphy);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5355_0 |
crossvul-cpp_data_bad_342_3 | /*
* card-tcos.c: Support for TCOS cards
*
* Copyright (C) 2011 Peter Koch <pk@opensc-project.org>
* Copyright (C) 2002 g10 Code GmbH
* Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static struct sc_atr_table tcos_atrs[] = {
/* Infineon SLE44 */
{ "3B:BA:13:00:81:31:86:5D:00:64:05:0A:02:01:31:80:90:00:8B", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66S */
{ "3B:BA:14:00:81:31:86:5D:00:64:05:14:02:02:31:80:90:00:91", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX320P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:60:02:03:31:80:90:00:66", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX322P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:7B:02:03:31:80:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Philips P5CT072 */
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:03:01:31:C0:73:F7:01:D0:00:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:04:0F:31:C0:73:F7:01:D0:00:90:00:74", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
/* Philips P5CT080 */
{ "3B:BF:B6:00:81:31:FE:5D:00:64:04:28:03:02:31:C0:73:F7:01:D0:00:90:00:67", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
static struct sc_card_operations tcos_ops;
static struct sc_card_driver tcos_drv = {
"TCOS 3.0",
"tcos",
&tcos_ops,
NULL, 0, NULL
};
static const struct sc_card_operations *iso_ops = NULL;
typedef struct tcos_data_st {
unsigned int pad_flags;
unsigned int next_sign;
} tcos_data;
static int tcos_finish(sc_card_t *card)
{
free(card->drv_data);
return 0;
}
static int tcos_match_card(sc_card_t *card)
{
int i;
i = _sc_match_atr(card, tcos_atrs, &card->type);
if (i < 0)
return 0;
return 1;
}
static int tcos_init(sc_card_t *card)
{
unsigned long flags;
tcos_data *data = malloc(sizeof(tcos_data));
if (!data) return SC_ERROR_OUT_OF_MEMORY;
card->name = "TCOS";
card->drv_data = (void *)data;
card->cla = 0x00;
flags = SC_ALGORITHM_RSA_RAW;
flags |= SC_ALGORITHM_RSA_PAD_PKCS1;
flags |= SC_ALGORITHM_RSA_HASH_NONE;
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 768, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
if (card->type == SC_CARD_TYPE_TCOS_V3) {
card->caps |= SC_CARD_CAP_APDU_EXT;
_sc_card_add_rsa_alg(card, 1280, flags, 0);
_sc_card_add_rsa_alg(card, 1536, flags, 0);
_sc_card_add_rsa_alg(card, 1792, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
return 0;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static int tcos_construct_fci(const sc_file_t *file,
u8 *out, size_t *outlen)
{
u8 *p = out;
u8 buf[64];
size_t n;
/* FIXME: possible buffer overflow */
*p++ = 0x6F; /* FCI */
p++;
/* File size */
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x81, buf, 2, p, 16, &p);
/* File descriptor */
n = 0;
buf[n] = file->shareable ? 0x40 : 0;
switch (file->type) {
case SC_FILE_TYPE_WORKING_EF:
break;
case SC_FILE_TYPE_DF:
buf[0] |= 0x38;
break;
default:
return SC_ERROR_NOT_SUPPORTED;
}
buf[n++] |= file->ef_structure & 7;
if ( (file->ef_structure & 7) > 1) {
/* record structured file */
buf[n++] = 0x41; /* indicate 3rd byte */
buf[n++] = file->record_length;
}
sc_asn1_put_tag(0x82, buf, n, p, 8, &p);
/* File identifier */
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, 16, &p);
/* Directory name */
if (file->type == SC_FILE_TYPE_DF) {
if (file->namelen) {
sc_asn1_put_tag(0x84, file->name, file->namelen,
p, 16, &p);
}
else {
/* TCOS needs one, so we use a faked one */
snprintf ((char *) buf, sizeof(buf)-1, "foo-%lu",
(unsigned long) time (NULL));
sc_asn1_put_tag(0x84, buf, strlen ((char *) buf), p, 16, &p);
}
}
/* File descriptor extension */
if (file->prop_attr_len && file->prop_attr) {
n = file->prop_attr_len;
memcpy(buf, file->prop_attr, n);
}
else {
n = 0;
buf[n++] = 0x01; /* not invalidated, permanent */
if (file->type == SC_FILE_TYPE_WORKING_EF)
buf[n++] = 0x00; /* generic data file */
}
sc_asn1_put_tag(0x85, buf, n, p, 16, &p);
/* Security attributes */
if (file->sec_attr_len && file->sec_attr) {
memcpy(buf, file->sec_attr, file->sec_attr_len);
n = file->sec_attr_len;
}
else {
/* no attributes given - fall back to default one */
memcpy (buf+ 0, "\xa4\x00\x00\x00\xff\xff", 6); /* select */
memcpy (buf+ 6, "\xb0\x00\x00\x00\xff\xff", 6); /* read bin */
memcpy (buf+12, "\xd6\x00\x00\x00\xff\xff", 6); /* upd bin */
memcpy (buf+18, "\x60\x00\x00\x00\xff\xff", 6); /* admin grp*/
n = 24;
}
sc_asn1_put_tag(0x86, buf, n, p, sizeof (buf), &p);
/* fixup length of FCI */
out[1] = p - out - 2;
*outlen = p - out;
return 0;
}
static int tcos_create_file(sc_card_t *card, sc_file_t *file)
{
int r;
size_t len;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_apdu_t apdu;
len = SC_MAX_APDU_BUFFER_SIZE;
r = tcos_construct_fci(file, sbuf, &len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "tcos_construct_fci() failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00);
apdu.cla |= 0x80; /* this is an proprietary extension */
apdu.lc = len;
apdu.datalen = len;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static unsigned int map_operations (int commandbyte )
{
unsigned int op = (unsigned int)-1;
switch ( (commandbyte & 0xfe) ) {
case 0xe2: /* append record */ op = SC_AC_OP_UPDATE; break;
case 0x24: /* change password */ op = SC_AC_OP_UPDATE; break;
case 0xe0: /* create */ op = SC_AC_OP_CREATE; break;
case 0xe4: /* delete */ op = SC_AC_OP_DELETE; break;
case 0xe8: /* exclude sfi */ op = SC_AC_OP_WRITE; break;
case 0x82: /* external auth */ op = SC_AC_OP_READ; break;
case 0xe6: /* include sfi */ op = SC_AC_OP_WRITE; break;
case 0x88: /* internal auth */ op = SC_AC_OP_READ; break;
case 0x04: /* invalidate */ op = SC_AC_OP_INVALIDATE; break;
case 0x2a: /* perform sec. op */ op = SC_AC_OP_SELECT; break;
case 0xb0: /* read binary */ op = SC_AC_OP_READ; break;
case 0xb2: /* read record */ op = SC_AC_OP_READ; break;
case 0x44: /* rehabilitate */ op = SC_AC_OP_REHABILITATE; break;
case 0xa4: /* select */ op = SC_AC_OP_SELECT; break;
case 0xee: /* set permanent */ op = SC_AC_OP_CREATE; break;
case 0x2c: /* unblock password */op = SC_AC_OP_WRITE; break;
case 0xd6: /* update binary */ op = SC_AC_OP_WRITE; break;
case 0xdc: /* update record */ op = SC_AC_OP_WRITE; break;
case 0x20: /* verify password */ op = SC_AC_OP_SELECT; break;
case 0x60: /* admin group */ op = SC_AC_OP_CREATE; break;
}
return op;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static void parse_sec_attr(sc_card_t *card,
sc_file_t *file, const u8 *buf, size_t len)
{
unsigned int op;
/* list directory is not covered by ACLs - so always add an entry */
sc_file_add_acl_entry (file, SC_AC_OP_LIST_FILES,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
/* FIXME: check for what LOCK is used */
sc_file_add_acl_entry (file, SC_AC_OP_LOCK,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
for (; len >= 6; len -= 6, buf += 6) {
/* FIXME: temporary hacks */
if (!memcmp(buf, "\xa4\x00\x00\x00\xff\xff", 6)) /* select */
sc_file_add_acl_entry (file, SC_AC_OP_SELECT,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\xb0\x00\x00\x00\xff\xff", 6)) /*read*/
sc_file_add_acl_entry (file, SC_AC_OP_READ,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\xd6\x00\x00\x00\xff\xff", 6)) /*upd*/
sc_file_add_acl_entry (file, SC_AC_OP_UPDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\x60\x00\x00\x00\xff\xff", 6)) {/*adm */
sc_file_add_acl_entry (file, SC_AC_OP_WRITE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_CREATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_INVALIDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_REHABILITATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
}
else {
/* the first byte tells use the command or the
command group. We have to mask bit 0
because this one distinguish between AND/OR
combination of PINs*/
op = map_operations (buf[0]);
if (op == (unsigned int)-1)
{
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Unknown security command byte %02x\n",
buf[0]);
continue;
}
if (!buf[1])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_CHV, buf[1]);
if (!buf[2] && !buf[3])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_TERM,
(buf[2]<<8)|buf[3]);
}
}
}
static int tcos_select_file(sc_card_t *card,
const sc_path_t *in_path,
sc_file_t **file_out)
{
sc_context_t *ctx;
sc_apdu_t apdu;
sc_file_t *file=NULL;
u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
unsigned int i;
int r, pathlen;
assert(card != NULL && in_path != NULL);
ctx=card->ctx;
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS;
/* fall through */
case SC_PATH_TYPE_FROM_CURRENT:
apdu.p1 = 9;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
case SC_PATH_TYPE_PATH:
apdu.p1 = 8;
if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2;
if (pathlen == 0) apdu.p1 = 0;
break;
case SC_PATH_TYPE_PARENT:
apdu.p1 = 3;
pathlen = 0;
break;
default:
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 256;
} else {
apdu.resplen = 0;
apdu.le = 0;
apdu.p2 = 0x0C;
apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r);
if (apdu.resplen < 1 || apdu.resp[0] != 0x62){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
file = sc_file_new();
if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
*file_out = file;
file->path = *in_path;
for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){
int j, len=apdu.resp[i+1];
unsigned char type=apdu.resp[i], *d=apdu.resp+i+2;
switch (type) {
case 0x80:
case 0x81:
file->size=0;
for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j];
break;
case 0x82:
file->shareable = (d[0] & 0x40) ? 1 : 0;
file->ef_structure = d[0] & 7;
switch ((d[0]>>3) & 7) {
case 0: file->type = SC_FILE_TYPE_WORKING_EF; break;
case 7: file->type = SC_FILE_TYPE_DF; break;
default:
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
break;
case 0x83:
file->id = (d[0]<<8) | d[1];
break;
case 0x84:
memcpy(file->name, d, len);
file->namelen = len;
break;
case 0x86:
sc_file_set_sec_attr(file, d, len);
break;
default:
if (len>0) sc_file_set_prop_attr(file, d, len);
}
}
file->magic = SC_FILE_MAGIC;
parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len);
return 0;
}
static int tcos_list_files(sc_card_t *card, u8 *buf, size_t buflen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE], p1;
int r, count = 0;
assert(card != NULL);
ctx = card->ctx;
for (p1=1; p1<=2; p1++) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, p1, 0);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1==0x6A && (apdu.sw2==0x82 || apdu.sw2==0x88)) continue;
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "List Dir failed");
if (apdu.resplen > buflen) return SC_ERROR_BUFFER_TOO_SMALL;
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"got %"SC_FORMAT_LEN_SIZE_T"u %s-FileIDs\n",
apdu.resplen / 2, p1 == 1 ? "DF" : "EF");
memcpy(buf, apdu.resp, apdu.resplen);
buf += apdu.resplen;
buflen -= apdu.resplen;
count += apdu.resplen;
}
return count;
}
static int tcos_delete_file(sc_card_t *card, const sc_path_t *path)
{
int r;
u8 sbuf[2];
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (path->type != SC_PATH_TYPE_FILE_ID && path->len != 2) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File type has to be SC_PATH_TYPE_FILE_ID\n");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
sbuf[0] = path->value[0];
sbuf[1] = path->value[1];
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p;
int r, default_key, tcos3;
tcos_data *data;
assert(card != NULL && env != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
if (se_num || (env->operation!=SC_SEC_OPERATION_DECIPHER && env->operation!=SC_SEC_OPERATION_SIGN)){
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
if(!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT))
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"No Key-Reference in SecEnvironment\n");
else
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Key-Reference %02X (len=%"SC_FORMAT_LEN_SIZE_T"u)\n",
env->key_ref[0], env->key_ref_len);
/* Key-Reference 0x80 ?? */
default_key= !(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len==1 && env->key_ref[0]==0x80);
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"TCOS3:%d PKCS1:%d\n", tcos3,
!!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
data->pad_flags = env->algorithm_flags;
data->next_sign = default_key;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, tcos3 ? 0x41 : 0xC1, 0xB8);
p = sbuf;
*p++=0x80; *p++=0x01; *p++=tcos3 ? 0x0A : 0x10;
if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) {
*p++ = (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) ? 0x83 : 0x84;
*p++ = env->key_ref_len;
memcpy(p, env->key_ref, env->key_ref_len);
p += env->key_ref_len;
}
apdu.data = sbuf;
apdu.lc = apdu.datalen = (p - sbuf);
r=sc_transmit_apdu(card, &apdu);
if (r) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"%s: APDU transmit failed", sc_strerror(r));
return r;
}
if (apdu.sw1==0x6A && (apdu.sw2==0x81 || apdu.sw2==0x88)) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Detected Signature-Only key\n");
if (env->operation==SC_SEC_OPERATION_SIGN && default_key) return SC_SUCCESS;
}
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_restore_security_env(sc_card_t *card, int se_num)
{
return 0;
}
static int tcos_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen)
{
size_t i, dlen=datalen;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
int tcos3, r;
assert(card != NULL && data != NULL && out != NULL);
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
if (datalen > 255) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
if(((tcos_data *)card->drv_data)->next_sign){
if(datalen>48){
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Data to be signed is too long (TCOS supports max. 48 bytes)\n");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A);
memcpy(sbuf, data, datalen);
dlen=datalen;
} else {
int keylen= tcos3 ? 256 : 128;
sc_format_apdu(card, &apdu, keylen>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
}
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = tcos3 ? 256 : 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (tcos3 && apdu.p1==0x80 && apdu.sw1==0x6A && apdu.sw2==0x87) {
int keylen=128;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
}
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len = apdu.resplen>outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
tcos_data *data;
int tcos3, r;
assert(card != NULL && crgram != NULL && out != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_NORMAL);
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"TCOS3:%d PKCS1:%d\n",tcos3,
!!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = crgram_len;
apdu.data = sbuf;
apdu.lc = apdu.datalen = crgram_len+1;
sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02);
memcpy(sbuf+1, crgram, crgram_len);
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen;
unsigned int offset=0;
if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2){
offset=2; while(offset<len && apdu.resp[offset]!=0) ++offset;
offset=(offset<len-1) ? offset+1 : 0;
}
memcpy(out, apdu.resp+offset, len-offset);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
/* Issue the SET PERMANENT command. With ENABLE_NULLPIN set the
NullPIN method will be activated, otherwise the permanent operation
will be done on the active file. */
static int tcos_setperm(sc_card_t *card, int enable_nullpin)
{
int r;
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xEE, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 0;
apdu.datalen = 0;
apdu.data = NULL;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial)
{
int r;
if (!serial)
return SC_ERROR_INVALID_ARGUMENTS;
/* see if we have cached serial number */
if (card->serialnr.len) {
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
card->serialnr.len = sizeof card->serialnr.value;
r = sc_parse_ef_gdo(card, card->serialnr.value, &card->serialnr.len, NULL, 0);
if (r < 0) {
card->serialnr.len = 0;
return r;
}
/* copy and return serial number */
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
static int tcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
switch (cmd) {
case SC_CARDCTL_TCOS_SETPERM:
return tcos_setperm(card, !!ptr);
case SC_CARDCTL_GET_SERIALNR:
return tcos_get_serialnr(card, (sc_serial_number_t *)ptr);
}
return SC_ERROR_NOT_SUPPORTED;
}
struct sc_card_driver * sc_get_tcos_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL) iso_ops = iso_drv->ops;
tcos_ops = *iso_drv->ops;
tcos_ops.match_card = tcos_match_card;
tcos_ops.init = tcos_init;
tcos_ops.finish = tcos_finish;
tcos_ops.create_file = tcos_create_file;
tcos_ops.set_security_env = tcos_set_security_env;
tcos_ops.select_file = tcos_select_file;
tcos_ops.list_files = tcos_list_files;
tcos_ops.delete_file = tcos_delete_file;
tcos_ops.set_security_env = tcos_set_security_env;
tcos_ops.compute_signature = tcos_compute_signature;
tcos_ops.decipher = tcos_decipher;
tcos_ops.restore_security_env = tcos_restore_security_env;
tcos_ops.card_ctl = tcos_card_ctl;
return &tcos_drv;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_342_3 |
crossvul-cpp_data_bad_1494_0 | /* crypto/x509/x509_vfy.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 <errno.h>
#include "internal/cryptlib.h"
#include <openssl/crypto.h>
#include <openssl/lhash.h>
#include <openssl/buffer.h>
#include <openssl/evp.h>
#include <openssl/asn1.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/objects.h>
#include "x509_lcl.h"
/* CRL score values */
/* No unhandled critical extensions */
#define CRL_SCORE_NOCRITICAL 0x100
/* certificate is within CRL scope */
#define CRL_SCORE_SCOPE 0x080
/* CRL times valid */
#define CRL_SCORE_TIME 0x040
/* Issuer name matches certificate */
#define CRL_SCORE_ISSUER_NAME 0x020
/* If this score or above CRL is probably valid */
#define CRL_SCORE_VALID (CRL_SCORE_NOCRITICAL|CRL_SCORE_TIME|CRL_SCORE_SCOPE)
/* CRL issuer is certificate issuer */
#define CRL_SCORE_ISSUER_CERT 0x018
/* CRL issuer is on certificate path */
#define CRL_SCORE_SAME_PATH 0x008
/* CRL issuer matches CRL AKID */
#define CRL_SCORE_AKID 0x004
/* Have a delta CRL with valid times */
#define CRL_SCORE_TIME_DELTA 0x002
static int null_callback(int ok, X509_STORE_CTX *e);
static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer);
static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x);
static int check_chain_extensions(X509_STORE_CTX *ctx);
static int check_name_constraints(X509_STORE_CTX *ctx);
static int check_id(X509_STORE_CTX *ctx);
static int check_trust(X509_STORE_CTX *ctx);
static int check_revocation(X509_STORE_CTX *ctx);
static int check_cert(X509_STORE_CTX *ctx);
static int check_policy(X509_STORE_CTX *ctx);
static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x);
static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
unsigned int *preasons, X509_CRL *crl, X509 *x);
static int get_crl_delta(X509_STORE_CTX *ctx,
X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x);
static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl,
int *pcrl_score, X509_CRL *base,
STACK_OF(X509_CRL) *crls);
static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer,
int *pcrl_score);
static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
unsigned int *preasons);
static int check_crl_path(X509_STORE_CTX *ctx, X509 *x);
static int check_crl_chain(X509_STORE_CTX *ctx,
STACK_OF(X509) *cert_path,
STACK_OF(X509) *crl_path);
static int internal_verify(X509_STORE_CTX *ctx);
const char X509_version[] = "X.509" OPENSSL_VERSION_PTEXT;
static int null_callback(int ok, X509_STORE_CTX *e)
{
return ok;
}
/* Return 1 is a certificate is self signed */
static int cert_self_signed(X509 *x)
{
X509_check_purpose(x, -1, 0);
if (x->ex_flags & EXFLAG_SS)
return 1;
else
return 0;
}
/* Given a certificate try and find an exact match in the store */
static X509 *lookup_cert_match(X509_STORE_CTX *ctx, X509 *x)
{
STACK_OF(X509) *certs;
X509 *xtmp = NULL;
int i;
/* Lookup all certs with matching subject name */
certs = ctx->lookup_certs(ctx, X509_get_subject_name(x));
if (certs == NULL)
return NULL;
/* Look for exact match */
for (i = 0; i < sk_X509_num(certs); i++) {
xtmp = sk_X509_value(certs, i);
if (!X509_cmp(xtmp, x))
break;
}
if (i < sk_X509_num(certs))
CRYPTO_add(&xtmp->references, 1, CRYPTO_LOCK_X509);
else
xtmp = NULL;
sk_X509_pop_free(certs, X509_free);
return xtmp;
}
int X509_verify_cert(X509_STORE_CTX *ctx)
{
X509 *x, *xtmp, *xtmp2, *chain_ss = NULL;
int bad_chain = 0;
X509_VERIFY_PARAM *param = ctx->param;
int depth, i, ok = 0;
int num, j, retry;
int (*cb) (int xok, X509_STORE_CTX *xctx);
STACK_OF(X509) *sktmp = NULL;
if (ctx->cert == NULL) {
X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
return -1;
}
cb = ctx->verify_cb;
/*
* first we make sure the chain we are going to build is present and that
* the first entry is in place
*/
if (ctx->chain == NULL) {
if (((ctx->chain = sk_X509_new_null()) == NULL) ||
(!sk_X509_push(ctx->chain, ctx->cert))) {
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
goto end;
}
CRYPTO_add(&ctx->cert->references, 1, CRYPTO_LOCK_X509);
ctx->last_untrusted = 1;
}
/* We use a temporary STACK so we can chop and hack at it */
if (ctx->untrusted != NULL
&& (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
goto end;
}
num = sk_X509_num(ctx->chain);
x = sk_X509_value(ctx->chain, num - 1);
depth = param->depth;
for (;;) {
/* If we have enough, we break */
if (depth < num)
break; /* FIXME: If this happens, we should take
* note of it and, if appropriate, use the
* X509_V_ERR_CERT_CHAIN_TOO_LONG error code
* later. */
/* If we are self signed, we break */
if (cert_self_signed(x))
break;
/*
* If asked see if we can find issuer in trusted store first
*/
if (ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST) {
ok = ctx->get_issuer(&xtmp, ctx, x);
if (ok < 0)
return ok;
/*
* If successful for now free up cert so it will be picked up
* again later.
*/
if (ok > 0) {
X509_free(xtmp);
break;
}
}
/* If we were passed a cert chain, use it first */
if (ctx->untrusted != NULL) {
xtmp = find_issuer(ctx, sktmp, x);
if (xtmp != NULL) {
if (!sk_X509_push(ctx->chain, xtmp)) {
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
goto end;
}
CRYPTO_add(&xtmp->references, 1, CRYPTO_LOCK_X509);
(void)sk_X509_delete_ptr(sktmp, xtmp);
ctx->last_untrusted++;
x = xtmp;
num++;
/*
* reparse the full chain for the next one
*/
continue;
}
}
break;
}
/* Remember how many untrusted certs we have */
j = num;
/*
* at this point, chain should contain a list of untrusted certificates.
* We now need to add at least one trusted one, if possible, otherwise we
* complain.
*/
do {
/*
* Examine last certificate in chain and see if it is self signed.
*/
i = sk_X509_num(ctx->chain);
x = sk_X509_value(ctx->chain, i - 1);
if (cert_self_signed(x)) {
/* we have a self signed certificate */
if (sk_X509_num(ctx->chain) == 1) {
/*
* We have a single self signed certificate: see if we can
* find it in the store. We must have an exact match to avoid
* possible impersonation.
*/
ok = ctx->get_issuer(&xtmp, ctx, x);
if ((ok <= 0) || X509_cmp(x, xtmp)) {
ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
ctx->current_cert = x;
ctx->error_depth = i - 1;
if (ok == 1)
X509_free(xtmp);
bad_chain = 1;
ok = cb(0, ctx);
if (!ok)
goto end;
} else {
/*
* We have a match: replace certificate with store
* version so we get any trust settings.
*/
X509_free(x);
x = xtmp;
(void)sk_X509_set(ctx->chain, i - 1, x);
ctx->last_untrusted = 0;
}
} else {
/*
* extract and save self signed certificate for later use
*/
chain_ss = sk_X509_pop(ctx->chain);
ctx->last_untrusted--;
num--;
j--;
x = sk_X509_value(ctx->chain, num - 1);
}
}
/* We now lookup certs from the certificate store */
for (;;) {
/* If we have enough, we break */
if (depth < num)
break;
/* If we are self signed, we break */
if (cert_self_signed(x))
break;
ok = ctx->get_issuer(&xtmp, ctx, x);
if (ok < 0)
return ok;
if (ok == 0)
break;
x = xtmp;
if (!sk_X509_push(ctx->chain, x)) {
X509_free(xtmp);
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
return 0;
}
num++;
}
/* we now have our chain, lets check it... */
i = check_trust(ctx);
/* If explicitly rejected error */
if (i == X509_TRUST_REJECTED)
goto end;
/*
* If it's not explicitly trusted then check if there is an alternative
* chain that could be used. We only do this if we haven't already
* checked via TRUSTED_FIRST and the user hasn't switched off alternate
* chain checking
*/
retry = 0;
if (i != X509_TRUST_TRUSTED
&& !(ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST)
&& !(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS)) {
while (j-- > 1) {
STACK_OF(X509) *chtmp = ctx->chain;
xtmp2 = sk_X509_value(ctx->chain, j - 1);
/*
* Temporarily set chain to NULL so we don't discount
* duplicates: the same certificate could be an untrusted
* CA found in the trusted store.
*/
ctx->chain = NULL;
ok = ctx->get_issuer(&xtmp, ctx, xtmp2);
ctx->chain = chtmp;
if (ok < 0)
goto end;
/* Check if we found an alternate chain */
if (ok > 0) {
/*
* Free up the found cert we'll add it again later
*/
X509_free(xtmp);
/*
* Dump all the certs above this point - we've found an
* alternate chain
*/
while (num > j) {
xtmp = sk_X509_pop(ctx->chain);
X509_free(xtmp);
num--;
ctx->last_untrusted--;
}
retry = 1;
break;
}
}
}
} while (retry);
/*
* If not explicitly trusted then indicate error unless it's a single
* self signed certificate in which case we've indicated an error already
* and set bad_chain == 1
*/
if (i != X509_TRUST_TRUSTED && !bad_chain) {
if ((chain_ss == NULL) || !ctx->check_issued(ctx, x, chain_ss)) {
if (ctx->last_untrusted >= num)
ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
else
ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
ctx->current_cert = x;
} else {
sk_X509_push(ctx->chain, chain_ss);
num++;
ctx->last_untrusted = num;
ctx->current_cert = chain_ss;
ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
chain_ss = NULL;
}
ctx->error_depth = num - 1;
bad_chain = 1;
ok = cb(0, ctx);
if (!ok)
goto end;
}
/* We have the chain complete: now we need to check its purpose */
ok = check_chain_extensions(ctx);
if (!ok)
goto end;
/* Check name constraints */
ok = check_name_constraints(ctx);
if (!ok)
goto end;
ok = check_id(ctx);
if (!ok)
goto end;
/* We may as well copy down any DSA parameters that are required */
X509_get_pubkey_parameters(NULL, ctx->chain);
/*
* Check revocation status: we do this after copying parameters because
* they may be needed for CRL signature verification.
*/
ok = ctx->check_revocation(ctx);
if (!ok)
goto end;
i = X509_chain_check_suiteb(&ctx->error_depth, NULL, ctx->chain,
ctx->param->flags);
if (i != X509_V_OK) {
ctx->error = i;
ctx->current_cert = sk_X509_value(ctx->chain, ctx->error_depth);
ok = cb(0, ctx);
if (!ok)
goto end;
}
/* At this point, we have a chain and need to verify it */
if (ctx->verify != NULL)
ok = ctx->verify(ctx);
else
ok = internal_verify(ctx);
if (!ok)
goto end;
/* RFC 3779 path validation, now that CRL check has been done */
ok = v3_asid_validate_path(ctx);
if (!ok)
goto end;
ok = v3_addr_validate_path(ctx);
if (!ok)
goto end;
/* If we get this far evaluate policies */
if (!bad_chain && (ctx->param->flags & X509_V_FLAG_POLICY_CHECK))
ok = ctx->check_policy(ctx);
if (ok)
goto done;
end:
X509_get_pubkey_parameters(NULL, ctx->chain);
done:
sk_X509_free(sktmp);
X509_free(chain_ss);
return ok;
}
/*
* Given a STACK_OF(X509) find the issuer of cert (if any)
*/
static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x)
{
int i;
X509 *issuer, *rv = NULL;;
for (i = 0; i < sk_X509_num(sk); i++) {
issuer = sk_X509_value(sk, i);
if (ctx->check_issued(ctx, x, issuer)) {
rv = issuer;
if (x509_check_cert_time(ctx, rv, 1))
break;
}
}
return rv;
}
/* Given a possible certificate and issuer check them */
static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer)
{
int ret;
if (x == issuer)
return cert_self_signed(x);
ret = X509_check_issued(issuer, x);
if (ret == X509_V_OK) {
int i;
X509 *ch;
/* Special case: single self signed certificate */
if (cert_self_signed(x) && sk_X509_num(ctx->chain) == 1)
return 1;
for (i = 0; i < sk_X509_num(ctx->chain); i++) {
ch = sk_X509_value(ctx->chain, i);
if (ch == issuer || !X509_cmp(ch, issuer)) {
ret = X509_V_ERR_PATH_LOOP;
break;
}
}
}
if (ret == X509_V_OK)
return 1;
/* If we haven't asked for issuer errors don't set ctx */
if (!(ctx->param->flags & X509_V_FLAG_CB_ISSUER_CHECK))
return 0;
ctx->error = ret;
ctx->current_cert = x;
ctx->current_issuer = issuer;
return ctx->verify_cb(0, ctx);
}
/* Alternative lookup method: look from a STACK stored in other_ctx */
static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x)
{
*issuer = find_issuer(ctx, ctx->other_ctx, x);
if (*issuer) {
CRYPTO_add(&(*issuer)->references, 1, CRYPTO_LOCK_X509);
return 1;
} else
return 0;
}
/*
* Check a certificate chains extensions for consistency with the supplied
* purpose
*/
static int check_chain_extensions(X509_STORE_CTX *ctx)
{
int i, ok = 0, must_be_ca, plen = 0;
X509 *x;
int (*cb) (int xok, X509_STORE_CTX *xctx);
int proxy_path_length = 0;
int purpose;
int allow_proxy_certs;
cb = ctx->verify_cb;
/*-
* must_be_ca can have 1 of 3 values:
* -1: we accept both CA and non-CA certificates, to allow direct
* use of self-signed certificates (which are marked as CA).
* 0: we only accept non-CA certificates. This is currently not
* used, but the possibility is present for future extensions.
* 1: we only accept CA certificates. This is currently used for
* all certificates in the chain except the leaf certificate.
*/
must_be_ca = -1;
/* CRL path validation */
if (ctx->parent) {
allow_proxy_certs = 0;
purpose = X509_PURPOSE_CRL_SIGN;
} else {
allow_proxy_certs =
! !(ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS);
/*
* A hack to keep people who don't want to modify their software
* happy
*/
if (getenv("OPENSSL_ALLOW_PROXY_CERTS"))
allow_proxy_certs = 1;
purpose = ctx->param->purpose;
}
/* Check all untrusted certificates */
for (i = 0; i < ctx->last_untrusted; i++) {
int ret;
x = sk_X509_value(ctx->chain, i);
if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
&& (x->ex_flags & EXFLAG_CRITICAL)) {
ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION;
ctx->error_depth = i;
ctx->current_cert = x;
ok = cb(0, ctx);
if (!ok)
goto end;
}
if (!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY)) {
ctx->error = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED;
ctx->error_depth = i;
ctx->current_cert = x;
ok = cb(0, ctx);
if (!ok)
goto end;
}
ret = X509_check_ca(x);
switch (must_be_ca) {
case -1:
if ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
&& (ret != 1) && (ret != 0)) {
ret = 0;
ctx->error = X509_V_ERR_INVALID_CA;
} else
ret = 1;
break;
case 0:
if (ret != 0) {
ret = 0;
ctx->error = X509_V_ERR_INVALID_NON_CA;
} else
ret = 1;
break;
default:
if ((ret == 0)
|| ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
&& (ret != 1))) {
ret = 0;
ctx->error = X509_V_ERR_INVALID_CA;
} else
ret = 1;
break;
}
if (ret == 0) {
ctx->error_depth = i;
ctx->current_cert = x;
ok = cb(0, ctx);
if (!ok)
goto end;
}
if (ctx->param->purpose > 0) {
ret = X509_check_purpose(x, purpose, must_be_ca > 0);
if ((ret == 0)
|| ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
&& (ret != 1))) {
ctx->error = X509_V_ERR_INVALID_PURPOSE;
ctx->error_depth = i;
ctx->current_cert = x;
ok = cb(0, ctx);
if (!ok)
goto end;
}
}
/* Check pathlen if not self issued */
if ((i > 1) && !(x->ex_flags & EXFLAG_SI)
&& (x->ex_pathlen != -1)
&& (plen > (x->ex_pathlen + proxy_path_length + 1))) {
ctx->error = X509_V_ERR_PATH_LENGTH_EXCEEDED;
ctx->error_depth = i;
ctx->current_cert = x;
ok = cb(0, ctx);
if (!ok)
goto end;
}
/* Increment path length if not self issued */
if (!(x->ex_flags & EXFLAG_SI))
plen++;
/*
* If this certificate is a proxy certificate, the next certificate
* must be another proxy certificate or a EE certificate. If not,
* the next certificate must be a CA certificate.
*/
if (x->ex_flags & EXFLAG_PROXY) {
if (x->ex_pcpathlen != -1 && i > x->ex_pcpathlen) {
ctx->error = X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED;
ctx->error_depth = i;
ctx->current_cert = x;
ok = cb(0, ctx);
if (!ok)
goto end;
}
proxy_path_length++;
must_be_ca = 0;
} else
must_be_ca = 1;
}
ok = 1;
end:
return ok;
}
static int check_name_constraints(X509_STORE_CTX *ctx)
{
X509 *x;
int i, j, rv;
/* Check name constraints for all certificates */
for (i = sk_X509_num(ctx->chain) - 1; i >= 0; i--) {
x = sk_X509_value(ctx->chain, i);
/* Ignore self issued certs unless last in chain */
if (i && (x->ex_flags & EXFLAG_SI))
continue;
/*
* Check against constraints for all certificates higher in chain
* including trust anchor. Trust anchor not strictly speaking needed
* but if it includes constraints it is to be assumed it expects them
* to be obeyed.
*/
for (j = sk_X509_num(ctx->chain) - 1; j > i; j--) {
NAME_CONSTRAINTS *nc = sk_X509_value(ctx->chain, j)->nc;
if (nc) {
rv = NAME_CONSTRAINTS_check(x, nc);
if (rv != X509_V_OK) {
ctx->error = rv;
ctx->error_depth = i;
ctx->current_cert = x;
if (!ctx->verify_cb(0, ctx))
return 0;
}
}
}
}
return 1;
}
static int check_id_error(X509_STORE_CTX *ctx, int errcode)
{
ctx->error = errcode;
ctx->current_cert = ctx->cert;
ctx->error_depth = 0;
return ctx->verify_cb(0, ctx);
}
static int check_hosts(X509 *x, X509_VERIFY_PARAM_ID *id)
{
int i;
int n = sk_OPENSSL_STRING_num(id->hosts);
char *name;
for (i = 0; i < n; ++i) {
name = sk_OPENSSL_STRING_value(id->hosts, i);
if (X509_check_host(x, name, 0, id->hostflags, &id->peername) > 0)
return 1;
}
return n == 0;
}
static int check_id(X509_STORE_CTX *ctx)
{
X509_VERIFY_PARAM *vpm = ctx->param;
X509_VERIFY_PARAM_ID *id = vpm->id;
X509 *x = ctx->cert;
if (id->hosts && check_hosts(x, id) <= 0) {
if (!check_id_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH))
return 0;
}
if (id->email && X509_check_email(x, id->email, id->emaillen, 0) <= 0) {
if (!check_id_error(ctx, X509_V_ERR_EMAIL_MISMATCH))
return 0;
}
if (id->ip && X509_check_ip(x, id->ip, id->iplen, 0) <= 0) {
if (!check_id_error(ctx, X509_V_ERR_IP_ADDRESS_MISMATCH))
return 0;
}
return 1;
}
static int check_trust(X509_STORE_CTX *ctx)
{
int i, ok;
X509 *x = NULL;
int (*cb) (int xok, X509_STORE_CTX *xctx);
cb = ctx->verify_cb;
/* Check all trusted certificates in chain */
for (i = ctx->last_untrusted; i < sk_X509_num(ctx->chain); i++) {
x = sk_X509_value(ctx->chain, i);
ok = X509_check_trust(x, ctx->param->trust, 0);
/* If explicitly trusted return trusted */
if (ok == X509_TRUST_TRUSTED)
return X509_TRUST_TRUSTED;
/*
* If explicitly rejected notify callback and reject if not
* overridden.
*/
if (ok == X509_TRUST_REJECTED) {
ctx->error_depth = i;
ctx->current_cert = x;
ctx->error = X509_V_ERR_CERT_REJECTED;
ok = cb(0, ctx);
if (!ok)
return X509_TRUST_REJECTED;
}
}
/*
* If we accept partial chains and have at least one trusted certificate
* return success.
*/
if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
X509 *mx;
if (ctx->last_untrusted < sk_X509_num(ctx->chain))
return X509_TRUST_TRUSTED;
x = sk_X509_value(ctx->chain, 0);
mx = lookup_cert_match(ctx, x);
if (mx) {
(void)sk_X509_set(ctx->chain, 0, mx);
X509_free(x);
ctx->last_untrusted = 0;
return X509_TRUST_TRUSTED;
}
}
/*
* If no trusted certs in chain at all return untrusted and allow
* standard (no issuer cert) etc errors to be indicated.
*/
return X509_TRUST_UNTRUSTED;
}
static int check_revocation(X509_STORE_CTX *ctx)
{
int i = 0, last = 0, ok = 0;
if (!(ctx->param->flags & X509_V_FLAG_CRL_CHECK))
return 1;
if (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL)
last = sk_X509_num(ctx->chain) - 1;
else {
/* If checking CRL paths this isn't the EE certificate */
if (ctx->parent)
return 1;
last = 0;
}
for (i = 0; i <= last; i++) {
ctx->error_depth = i;
ok = check_cert(ctx);
if (!ok)
return ok;
}
return 1;
}
static int check_cert(X509_STORE_CTX *ctx)
{
X509_CRL *crl = NULL, *dcrl = NULL;
X509 *x = NULL;
int ok = 0, cnum = 0;
unsigned int last_reasons = 0;
cnum = ctx->error_depth;
x = sk_X509_value(ctx->chain, cnum);
ctx->current_cert = x;
ctx->current_issuer = NULL;
ctx->current_crl_score = 0;
ctx->current_reasons = 0;
while (ctx->current_reasons != CRLDP_ALL_REASONS) {
last_reasons = ctx->current_reasons;
/* Try to retrieve relevant CRL */
if (ctx->get_crl)
ok = ctx->get_crl(ctx, &crl, x);
else
ok = get_crl_delta(ctx, &crl, &dcrl, x);
/*
* If error looking up CRL, nothing we can do except notify callback
*/
if (!ok) {
ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
ok = ctx->verify_cb(0, ctx);
goto err;
}
ctx->current_crl = crl;
ok = ctx->check_crl(ctx, crl);
if (!ok)
goto err;
if (dcrl) {
ok = ctx->check_crl(ctx, dcrl);
if (!ok)
goto err;
ok = ctx->cert_crl(ctx, dcrl, x);
if (!ok)
goto err;
} else
ok = 1;
/* Don't look in full CRL if delta reason is removefromCRL */
if (ok != 2) {
ok = ctx->cert_crl(ctx, crl, x);
if (!ok)
goto err;
}
X509_CRL_free(crl);
X509_CRL_free(dcrl);
crl = NULL;
dcrl = NULL;
/*
* If reasons not updated we wont get anywhere by another iteration,
* so exit loop.
*/
if (last_reasons == ctx->current_reasons) {
ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
ok = ctx->verify_cb(0, ctx);
goto err;
}
}
err:
X509_CRL_free(crl);
X509_CRL_free(dcrl);
ctx->current_crl = NULL;
return ok;
}
/* Check CRL times against values in X509_STORE_CTX */
static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify)
{
time_t *ptime;
int i;
if (notify)
ctx->current_crl = crl;
if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
ptime = &ctx->param->check_time;
else
ptime = NULL;
i = X509_cmp_time(X509_CRL_get_lastUpdate(crl), ptime);
if (i == 0) {
if (!notify)
return 0;
ctx->error = X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD;
if (!ctx->verify_cb(0, ctx))
return 0;
}
if (i > 0) {
if (!notify)
return 0;
ctx->error = X509_V_ERR_CRL_NOT_YET_VALID;
if (!ctx->verify_cb(0, ctx))
return 0;
}
if (X509_CRL_get_nextUpdate(crl)) {
i = X509_cmp_time(X509_CRL_get_nextUpdate(crl), ptime);
if (i == 0) {
if (!notify)
return 0;
ctx->error = X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD;
if (!ctx->verify_cb(0, ctx))
return 0;
}
/* Ignore expiry of base CRL is delta is valid */
if ((i < 0) && !(ctx->current_crl_score & CRL_SCORE_TIME_DELTA)) {
if (!notify)
return 0;
ctx->error = X509_V_ERR_CRL_HAS_EXPIRED;
if (!ctx->verify_cb(0, ctx))
return 0;
}
}
if (notify)
ctx->current_crl = NULL;
return 1;
}
static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
X509 **pissuer, int *pscore, unsigned int *preasons,
STACK_OF(X509_CRL) *crls)
{
int i, crl_score, best_score = *pscore;
unsigned int reasons, best_reasons = 0;
X509 *x = ctx->current_cert;
X509_CRL *crl, *best_crl = NULL;
X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
for (i = 0; i < sk_X509_CRL_num(crls); i++) {
crl = sk_X509_CRL_value(crls, i);
reasons = *preasons;
crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
if (crl_score > best_score) {
best_crl = crl;
best_crl_issuer = crl_issuer;
best_score = crl_score;
best_reasons = reasons;
}
}
if (best_crl) {
X509_CRL_free(*pcrl);
*pcrl = best_crl;
*pissuer = best_crl_issuer;
*pscore = best_score;
*preasons = best_reasons;
CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL);
X509_CRL_free(*pdcrl);
*pdcrl = NULL;
get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
}
if (best_score >= CRL_SCORE_VALID)
return 1;
return 0;
}
/*
* Compare two CRL extensions for delta checking purposes. They should be
* both present or both absent. If both present all fields must be identical.
*/
static int crl_extension_match(X509_CRL *a, X509_CRL *b, int nid)
{
ASN1_OCTET_STRING *exta, *extb;
int i;
i = X509_CRL_get_ext_by_NID(a, nid, -1);
if (i >= 0) {
/* Can't have multiple occurrences */
if (X509_CRL_get_ext_by_NID(a, nid, i) != -1)
return 0;
exta = X509_EXTENSION_get_data(X509_CRL_get_ext(a, i));
} else
exta = NULL;
i = X509_CRL_get_ext_by_NID(b, nid, -1);
if (i >= 0) {
if (X509_CRL_get_ext_by_NID(b, nid, i) != -1)
return 0;
extb = X509_EXTENSION_get_data(X509_CRL_get_ext(b, i));
} else
extb = NULL;
if (!exta && !extb)
return 1;
if (!exta || !extb)
return 0;
if (ASN1_OCTET_STRING_cmp(exta, extb))
return 0;
return 1;
}
/* See if a base and delta are compatible */
static int check_delta_base(X509_CRL *delta, X509_CRL *base)
{
/* Delta CRL must be a delta */
if (!delta->base_crl_number)
return 0;
/* Base must have a CRL number */
if (!base->crl_number)
return 0;
/* Issuer names must match */
if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(delta)))
return 0;
/* AKID and IDP must match */
if (!crl_extension_match(delta, base, NID_authority_key_identifier))
return 0;
if (!crl_extension_match(delta, base, NID_issuing_distribution_point))
return 0;
/* Delta CRL base number must not exceed Full CRL number. */
if (ASN1_INTEGER_cmp(delta->base_crl_number, base->crl_number) > 0)
return 0;
/* Delta CRL number must exceed full CRL number */
if (ASN1_INTEGER_cmp(delta->crl_number, base->crl_number) > 0)
return 1;
return 0;
}
/*
* For a given base CRL find a delta... maybe extend to delta scoring or
* retrieve a chain of deltas...
*/
static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pscore,
X509_CRL *base, STACK_OF(X509_CRL) *crls)
{
X509_CRL *delta;
int i;
if (!(ctx->param->flags & X509_V_FLAG_USE_DELTAS))
return;
if (!((ctx->current_cert->ex_flags | base->flags) & EXFLAG_FRESHEST))
return;
for (i = 0; i < sk_X509_CRL_num(crls); i++) {
delta = sk_X509_CRL_value(crls, i);
if (check_delta_base(delta, base)) {
if (check_crl_time(ctx, delta, 0))
*pscore |= CRL_SCORE_TIME_DELTA;
CRYPTO_add(&delta->references, 1, CRYPTO_LOCK_X509_CRL);
*dcrl = delta;
return;
}
}
*dcrl = NULL;
}
/*
* For a given CRL return how suitable it is for the supplied certificate
* 'x'. The return value is a mask of several criteria. If the issuer is not
* the certificate issuer this is returned in *pissuer. The reasons mask is
* also used to determine if the CRL is suitable: if no new reasons the CRL
* is rejected, otherwise reasons is updated.
*/
static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
unsigned int *preasons, X509_CRL *crl, X509 *x)
{
int crl_score = 0;
unsigned int tmp_reasons = *preasons, crl_reasons;
/* First see if we can reject CRL straight away */
/* Invalid IDP cannot be processed */
if (crl->idp_flags & IDP_INVALID)
return 0;
/* Reason codes or indirect CRLs need extended CRL support */
if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT)) {
if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS))
return 0;
} else if (crl->idp_flags & IDP_REASONS) {
/* If no new reasons reject */
if (!(crl->idp_reasons & ~tmp_reasons))
return 0;
}
/* Don't process deltas at this stage */
else if (crl->base_crl_number)
return 0;
/* If issuer name doesn't match certificate need indirect CRL */
if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl))) {
if (!(crl->idp_flags & IDP_INDIRECT))
return 0;
} else
crl_score |= CRL_SCORE_ISSUER_NAME;
if (!(crl->flags & EXFLAG_CRITICAL))
crl_score |= CRL_SCORE_NOCRITICAL;
/* Check expiry */
if (check_crl_time(ctx, crl, 0))
crl_score |= CRL_SCORE_TIME;
/* Check authority key ID and locate certificate issuer */
crl_akid_check(ctx, crl, pissuer, &crl_score);
/* If we can't locate certificate issuer at this point forget it */
if (!(crl_score & CRL_SCORE_AKID))
return 0;
/* Check cert for matching CRL distribution points */
if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) {
/* If no new reasons reject */
if (!(crl_reasons & ~tmp_reasons))
return 0;
tmp_reasons |= crl_reasons;
crl_score |= CRL_SCORE_SCOPE;
}
*preasons = tmp_reasons;
return crl_score;
}
static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl,
X509 **pissuer, int *pcrl_score)
{
X509 *crl_issuer = NULL;
X509_NAME *cnm = X509_CRL_get_issuer(crl);
int cidx = ctx->error_depth;
int i;
if (cidx != sk_X509_num(ctx->chain) - 1)
cidx++;
crl_issuer = sk_X509_value(ctx->chain, cidx);
if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
if (*pcrl_score & CRL_SCORE_ISSUER_NAME) {
*pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_ISSUER_CERT;
*pissuer = crl_issuer;
return;
}
}
for (cidx++; cidx < sk_X509_num(ctx->chain); cidx++) {
crl_issuer = sk_X509_value(ctx->chain, cidx);
if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
continue;
if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
*pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_SAME_PATH;
*pissuer = crl_issuer;
return;
}
}
/* Anything else needs extended CRL support */
if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT))
return;
/*
* Otherwise the CRL issuer is not on the path. Look for it in the set of
* untrusted certificates.
*/
for (i = 0; i < sk_X509_num(ctx->untrusted); i++) {
crl_issuer = sk_X509_value(ctx->untrusted, i);
if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
continue;
if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
*pissuer = crl_issuer;
*pcrl_score |= CRL_SCORE_AKID;
return;
}
}
}
/*
* Check the path of a CRL issuer certificate. This creates a new
* X509_STORE_CTX and populates it with most of the parameters from the
* parent. This could be optimised somewhat since a lot of path checking will
* be duplicated by the parent, but this will rarely be used in practice.
*/
static int check_crl_path(X509_STORE_CTX *ctx, X509 *x)
{
X509_STORE_CTX crl_ctx;
int ret;
/* Don't allow recursive CRL path validation */
if (ctx->parent)
return 0;
if (!X509_STORE_CTX_init(&crl_ctx, ctx->ctx, x, ctx->untrusted))
return -1;
crl_ctx.crls = ctx->crls;
/* Copy verify params across */
X509_STORE_CTX_set0_param(&crl_ctx, ctx->param);
crl_ctx.parent = ctx;
crl_ctx.verify_cb = ctx->verify_cb;
/* Verify CRL issuer */
ret = X509_verify_cert(&crl_ctx);
if (ret <= 0)
goto err;
/* Check chain is acceptable */
ret = check_crl_chain(ctx, ctx->chain, crl_ctx.chain);
err:
X509_STORE_CTX_cleanup(&crl_ctx);
return ret;
}
/*
* RFC3280 says nothing about the relationship between CRL path and
* certificate path, which could lead to situations where a certificate could
* be revoked or validated by a CA not authorised to do so. RFC5280 is more
* strict and states that the two paths must end in the same trust anchor,
* though some discussions remain... until this is resolved we use the
* RFC5280 version
*/
static int check_crl_chain(X509_STORE_CTX *ctx,
STACK_OF(X509) *cert_path,
STACK_OF(X509) *crl_path)
{
X509 *cert_ta, *crl_ta;
cert_ta = sk_X509_value(cert_path, sk_X509_num(cert_path) - 1);
crl_ta = sk_X509_value(crl_path, sk_X509_num(crl_path) - 1);
if (!X509_cmp(cert_ta, crl_ta))
return 1;
return 0;
}
/*-
* Check for match between two dist point names: three separate cases.
* 1. Both are relative names and compare X509_NAME types.
* 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES.
* 3. Both are full names and compare two GENERAL_NAMES.
* 4. One is NULL: automatic match.
*/
static int idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b)
{
X509_NAME *nm = NULL;
GENERAL_NAMES *gens = NULL;
GENERAL_NAME *gena, *genb;
int i, j;
if (!a || !b)
return 1;
if (a->type == 1) {
if (!a->dpname)
return 0;
/* Case 1: two X509_NAME */
if (b->type == 1) {
if (!b->dpname)
return 0;
if (!X509_NAME_cmp(a->dpname, b->dpname))
return 1;
else
return 0;
}
/* Case 2: set name and GENERAL_NAMES appropriately */
nm = a->dpname;
gens = b->name.fullname;
} else if (b->type == 1) {
if (!b->dpname)
return 0;
/* Case 2: set name and GENERAL_NAMES appropriately */
gens = a->name.fullname;
nm = b->dpname;
}
/* Handle case 2 with one GENERAL_NAMES and one X509_NAME */
if (nm) {
for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
gena = sk_GENERAL_NAME_value(gens, i);
if (gena->type != GEN_DIRNAME)
continue;
if (!X509_NAME_cmp(nm, gena->d.directoryName))
return 1;
}
return 0;
}
/* Else case 3: two GENERAL_NAMES */
for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) {
gena = sk_GENERAL_NAME_value(a->name.fullname, i);
for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) {
genb = sk_GENERAL_NAME_value(b->name.fullname, j);
if (!GENERAL_NAME_cmp(gena, genb))
return 1;
}
}
return 0;
}
static int crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score)
{
int i;
X509_NAME *nm = X509_CRL_get_issuer(crl);
/* If no CRLissuer return is successful iff don't need a match */
if (!dp->CRLissuer)
return ! !(crl_score & CRL_SCORE_ISSUER_NAME);
for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
if (gen->type != GEN_DIRNAME)
continue;
if (!X509_NAME_cmp(gen->d.directoryName, nm))
return 1;
}
return 0;
}
/* Check CRLDP and IDP */
static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
unsigned int *preasons)
{
int i;
if (crl->idp_flags & IDP_ONLYATTR)
return 0;
if (x->ex_flags & EXFLAG_CA) {
if (crl->idp_flags & IDP_ONLYUSER)
return 0;
} else {
if (crl->idp_flags & IDP_ONLYCA)
return 0;
}
*preasons = crl->idp_reasons;
for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i);
if (crldp_check_crlissuer(dp, crl, crl_score)) {
if (!crl->idp || idp_check_dp(dp->distpoint, crl->idp->distpoint)) {
*preasons &= dp->dp_reasons;
return 1;
}
}
}
if ((!crl->idp || !crl->idp->distpoint)
&& (crl_score & CRL_SCORE_ISSUER_NAME))
return 1;
return 0;
}
/*
* Retrieve CRL corresponding to current certificate. If deltas enabled try
* to find a delta CRL too
*/
static int get_crl_delta(X509_STORE_CTX *ctx,
X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x)
{
int ok;
X509 *issuer = NULL;
int crl_score = 0;
unsigned int reasons;
X509_CRL *crl = NULL, *dcrl = NULL;
STACK_OF(X509_CRL) *skcrl;
X509_NAME *nm = X509_get_issuer_name(x);
reasons = ctx->current_reasons;
ok = get_crl_sk(ctx, &crl, &dcrl,
&issuer, &crl_score, &reasons, ctx->crls);
if (ok)
goto done;
/* Lookup CRLs from store */
skcrl = ctx->lookup_crls(ctx, nm);
/* If no CRLs found and a near match from get_crl_sk use that */
if (!skcrl && crl)
goto done;
get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl);
sk_X509_CRL_pop_free(skcrl, X509_CRL_free);
done:
/* If we got any kind of CRL use it and return success */
if (crl) {
ctx->current_issuer = issuer;
ctx->current_crl_score = crl_score;
ctx->current_reasons = reasons;
*pcrl = crl;
*pdcrl = dcrl;
return 1;
}
return 0;
}
/* Check CRL validity */
static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl)
{
X509 *issuer = NULL;
EVP_PKEY *ikey = NULL;
int ok = 0, chnum, cnum;
cnum = ctx->error_depth;
chnum = sk_X509_num(ctx->chain) - 1;
/* if we have an alternative CRL issuer cert use that */
if (ctx->current_issuer)
issuer = ctx->current_issuer;
/*
* Else find CRL issuer: if not last certificate then issuer is next
* certificate in chain.
*/
else if (cnum < chnum)
issuer = sk_X509_value(ctx->chain, cnum + 1);
else {
issuer = sk_X509_value(ctx->chain, chnum);
/* If not self signed, can't check signature */
if (!ctx->check_issued(ctx, issuer, issuer)) {
ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER;
ok = ctx->verify_cb(0, ctx);
if (!ok)
goto err;
}
}
if (issuer) {
/*
* Skip most tests for deltas because they have already been done
*/
if (!crl->base_crl_number) {
/* Check for cRLSign bit if keyUsage present */
if ((issuer->ex_flags & EXFLAG_KUSAGE) &&
!(issuer->ex_kusage & KU_CRL_SIGN)) {
ctx->error = X509_V_ERR_KEYUSAGE_NO_CRL_SIGN;
ok = ctx->verify_cb(0, ctx);
if (!ok)
goto err;
}
if (!(ctx->current_crl_score & CRL_SCORE_SCOPE)) {
ctx->error = X509_V_ERR_DIFFERENT_CRL_SCOPE;
ok = ctx->verify_cb(0, ctx);
if (!ok)
goto err;
}
if (!(ctx->current_crl_score & CRL_SCORE_SAME_PATH)) {
if (check_crl_path(ctx, ctx->current_issuer) <= 0) {
ctx->error = X509_V_ERR_CRL_PATH_VALIDATION_ERROR;
ok = ctx->verify_cb(0, ctx);
if (!ok)
goto err;
}
}
if (crl->idp_flags & IDP_INVALID) {
ctx->error = X509_V_ERR_INVALID_EXTENSION;
ok = ctx->verify_cb(0, ctx);
if (!ok)
goto err;
}
}
if (!(ctx->current_crl_score & CRL_SCORE_TIME)) {
ok = check_crl_time(ctx, crl, 1);
if (!ok)
goto err;
}
/* Attempt to get issuer certificate public key */
ikey = X509_get_pubkey(issuer);
if (!ikey) {
ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
ok = ctx->verify_cb(0, ctx);
if (!ok)
goto err;
} else {
int rv;
rv = X509_CRL_check_suiteb(crl, ikey, ctx->param->flags);
if (rv != X509_V_OK) {
ctx->error = rv;
ok = ctx->verify_cb(0, ctx);
if (!ok)
goto err;
}
/* Verify CRL signature */
if (X509_CRL_verify(crl, ikey) <= 0) {
ctx->error = X509_V_ERR_CRL_SIGNATURE_FAILURE;
ok = ctx->verify_cb(0, ctx);
if (!ok)
goto err;
}
}
}
ok = 1;
err:
EVP_PKEY_free(ikey);
return ok;
}
/* Check certificate against CRL */
static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x)
{
int ok;
X509_REVOKED *rev;
/*
* The rules changed for this... previously if a CRL contained unhandled
* critical extensions it could still be used to indicate a certificate
* was revoked. This has since been changed since critical extension can
* change the meaning of CRL entries.
*/
if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
&& (crl->flags & EXFLAG_CRITICAL)) {
ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION;
ok = ctx->verify_cb(0, ctx);
if (!ok)
return 0;
}
/*
* Look for serial number of certificate in CRL If found make sure reason
* is not removeFromCRL.
*/
if (X509_CRL_get0_by_cert(crl, &rev, x)) {
if (rev->reason == CRL_REASON_REMOVE_FROM_CRL)
return 2;
ctx->error = X509_V_ERR_CERT_REVOKED;
ok = ctx->verify_cb(0, ctx);
if (!ok)
return 0;
}
return 1;
}
static int check_policy(X509_STORE_CTX *ctx)
{
int ret;
if (ctx->parent)
return 1;
ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain,
ctx->param->policies, ctx->param->flags);
if (ret == 0) {
X509err(X509_F_CHECK_POLICY, ERR_R_MALLOC_FAILURE);
return 0;
}
/* Invalid or inconsistent extensions */
if (ret == -1) {
/*
* Locate certificates with bad extensions and notify callback.
*/
X509 *x;
int i;
for (i = 1; i < sk_X509_num(ctx->chain); i++) {
x = sk_X509_value(ctx->chain, i);
if (!(x->ex_flags & EXFLAG_INVALID_POLICY))
continue;
ctx->current_cert = x;
ctx->error = X509_V_ERR_INVALID_POLICY_EXTENSION;
if (!ctx->verify_cb(0, ctx))
return 0;
}
return 1;
}
if (ret == -2) {
ctx->current_cert = NULL;
ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY;
return ctx->verify_cb(0, ctx);
}
if (ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) {
ctx->current_cert = NULL;
ctx->error = X509_V_OK;
if (!ctx->verify_cb(2, ctx))
return 0;
}
return 1;
}
int x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int quiet)
{
time_t *ptime;
int i;
if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
ptime = &ctx->param->check_time;
else
ptime = NULL;
i = X509_cmp_time(X509_get_notBefore(x), ptime);
if (i == 0) {
if (quiet)
return 0;
ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
ctx->current_cert = x;
if (!ctx->verify_cb(0, ctx))
return 0;
}
if (i > 0) {
if (quiet)
return 0;
ctx->error = X509_V_ERR_CERT_NOT_YET_VALID;
ctx->current_cert = x;
if (!ctx->verify_cb(0, ctx))
return 0;
}
i = X509_cmp_time(X509_get_notAfter(x), ptime);
if (i == 0) {
if (quiet)
return 0;
ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
ctx->current_cert = x;
if (!ctx->verify_cb(0, ctx))
return 0;
}
if (i < 0) {
if (quiet)
return 0;
ctx->error = X509_V_ERR_CERT_HAS_EXPIRED;
ctx->current_cert = x;
if (!ctx->verify_cb(0, ctx))
return 0;
}
return 1;
}
static int internal_verify(X509_STORE_CTX *ctx)
{
int ok = 0, n;
X509 *xs, *xi;
EVP_PKEY *pkey = NULL;
int (*cb) (int xok, X509_STORE_CTX *xctx);
cb = ctx->verify_cb;
n = sk_X509_num(ctx->chain);
ctx->error_depth = n - 1;
n--;
xi = sk_X509_value(ctx->chain, n);
if (ctx->check_issued(ctx, xi, xi))
xs = xi;
else {
if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
xs = xi;
goto check_cert;
}
if (n <= 0) {
ctx->error = X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE;
ctx->current_cert = xi;
ok = cb(0, ctx);
goto end;
} else {
n--;
ctx->error_depth = n;
xs = sk_X509_value(ctx->chain, n);
}
}
/* ctx->error=0; not needed */
while (n >= 0) {
ctx->error_depth = n;
/*
* Skip signature check for self signed certificates unless
* explicitly asked for. It doesn't add any security and just wastes
* time.
*/
if (!xs->valid
&& (xs != xi
|| (ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE))) {
if ((pkey = X509_get_pubkey(xi)) == NULL) {
ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
ctx->current_cert = xi;
ok = (*cb) (0, ctx);
if (!ok)
goto end;
} else if (X509_verify(xs, pkey) <= 0) {
ctx->error = X509_V_ERR_CERT_SIGNATURE_FAILURE;
ctx->current_cert = xs;
ok = (*cb) (0, ctx);
if (!ok) {
EVP_PKEY_free(pkey);
goto end;
}
}
EVP_PKEY_free(pkey);
pkey = NULL;
}
xs->valid = 1;
check_cert:
ok = x509_check_cert_time(ctx, xs, 0);
if (!ok)
goto end;
/* The last error (if any) is still in the error value */
ctx->current_issuer = xi;
ctx->current_cert = xs;
ok = (*cb) (1, ctx);
if (!ok)
goto end;
n--;
if (n >= 0) {
xi = xs;
xs = sk_X509_value(ctx->chain, n);
}
}
ok = 1;
end:
return ok;
}
int X509_cmp_current_time(const ASN1_TIME *ctm)
{
return X509_cmp_time(ctm, NULL);
}
int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
{
char *str;
ASN1_TIME atm;
long offset;
char buff1[24], buff2[24], *p;
int i, j;
p = buff1;
i = ctm->length;
str = (char *)ctm->data;
if (ctm->type == V_ASN1_UTCTIME) {
if ((i < 11) || (i > 17))
return 0;
memcpy(p, str, 10);
p += 10;
str += 10;
} else {
if (i < 13)
return 0;
memcpy(p, str, 12);
p += 12;
str += 12;
}
if ((*str == 'Z') || (*str == '-') || (*str == '+')) {
*(p++) = '0';
*(p++) = '0';
} else {
*(p++) = *(str++);
*(p++) = *(str++);
/* Skip any fractional seconds... */
if (*str == '.') {
str++;
while ((*str >= '0') && (*str <= '9'))
str++;
}
}
*(p++) = 'Z';
*(p++) = '\0';
if (*str == 'Z')
offset = 0;
else {
if ((*str != '+') && (*str != '-'))
return 0;
offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60;
offset += (str[3] - '0') * 10 + (str[4] - '0');
if (*str == '-')
offset = -offset;
}
atm.type = ctm->type;
atm.flags = 0;
atm.length = sizeof(buff2);
atm.data = (unsigned char *)buff2;
if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL)
return 0;
if (ctm->type == V_ASN1_UTCTIME) {
i = (buff1[0] - '0') * 10 + (buff1[1] - '0');
if (i < 50)
i += 100; /* cf. RFC 2459 */
j = (buff2[0] - '0') * 10 + (buff2[1] - '0');
if (j < 50)
j += 100;
if (i < j)
return -1;
if (i > j)
return 1;
}
i = strcmp(buff1, buff2);
if (i == 0) /* wait a second then return younger :-) */
return -1;
else
return i;
}
ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj)
{
return X509_time_adj(s, adj, NULL);
}
ASN1_TIME *X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_tm)
{
return X509_time_adj_ex(s, 0, offset_sec, in_tm);
}
ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
int offset_day, long offset_sec, time_t *in_tm)
{
time_t t;
if (in_tm)
t = *in_tm;
else
time(&t);
if (s && !(s->flags & ASN1_STRING_FLAG_MSTRING)) {
if (s->type == V_ASN1_UTCTIME)
return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
if (s->type == V_ASN1_GENERALIZEDTIME)
return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
}
return ASN1_TIME_adj(s, t, offset_day, offset_sec);
}
int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain)
{
EVP_PKEY *ktmp = NULL, *ktmp2;
int i, j;
if ((pkey != NULL) && !EVP_PKEY_missing_parameters(pkey))
return 1;
for (i = 0; i < sk_X509_num(chain); i++) {
ktmp = X509_get_pubkey(sk_X509_value(chain, i));
if (ktmp == NULL) {
X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
return 0;
}
if (!EVP_PKEY_missing_parameters(ktmp))
break;
EVP_PKEY_free(ktmp);
ktmp = NULL;
}
if (ktmp == NULL) {
X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
return 0;
}
/* first, populate the other certs */
for (j = i - 1; j >= 0; j--) {
ktmp2 = X509_get_pubkey(sk_X509_value(chain, j));
EVP_PKEY_copy_parameters(ktmp2, ktmp);
EVP_PKEY_free(ktmp2);
}
if (pkey != NULL)
EVP_PKEY_copy_parameters(pkey, ktmp);
EVP_PKEY_free(ktmp);
return 1;
}
/* Make a delta CRL as the diff between two full CRLs */
X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
EVP_PKEY *skey, const EVP_MD *md, unsigned int flags)
{
X509_CRL *crl = NULL;
int i;
STACK_OF(X509_REVOKED) *revs = NULL;
/* CRLs can't be delta already */
if (base->base_crl_number || newer->base_crl_number) {
X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_ALREADY_DELTA);
return NULL;
}
/* Base and new CRL must have a CRL number */
if (!base->crl_number || !newer->crl_number) {
X509err(X509_F_X509_CRL_DIFF, X509_R_NO_CRL_NUMBER);
return NULL;
}
/* Issuer names must match */
if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(newer))) {
X509err(X509_F_X509_CRL_DIFF, X509_R_ISSUER_MISMATCH);
return NULL;
}
/* AKID and IDP must match */
if (!crl_extension_match(base, newer, NID_authority_key_identifier)) {
X509err(X509_F_X509_CRL_DIFF, X509_R_AKID_MISMATCH);
return NULL;
}
if (!crl_extension_match(base, newer, NID_issuing_distribution_point)) {
X509err(X509_F_X509_CRL_DIFF, X509_R_IDP_MISMATCH);
return NULL;
}
/* Newer CRL number must exceed full CRL number */
if (ASN1_INTEGER_cmp(newer->crl_number, base->crl_number) <= 0) {
X509err(X509_F_X509_CRL_DIFF, X509_R_NEWER_CRL_NOT_NEWER);
return NULL;
}
/* CRLs must verify */
if (skey && (X509_CRL_verify(base, skey) <= 0 ||
X509_CRL_verify(newer, skey) <= 0)) {
X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_VERIFY_FAILURE);
return NULL;
}
/* Create new CRL */
crl = X509_CRL_new();
if (!crl || !X509_CRL_set_version(crl, 1))
goto memerr;
/* Set issuer name */
if (!X509_CRL_set_issuer_name(crl, X509_CRL_get_issuer(newer)))
goto memerr;
if (!X509_CRL_set_lastUpdate(crl, X509_CRL_get_lastUpdate(newer)))
goto memerr;
if (!X509_CRL_set_nextUpdate(crl, X509_CRL_get_nextUpdate(newer)))
goto memerr;
/* Set base CRL number: must be critical */
if (!X509_CRL_add1_ext_i2d(crl, NID_delta_crl, base->crl_number, 1, 0))
goto memerr;
/*
* Copy extensions across from newest CRL to delta: this will set CRL
* number to correct value too.
*/
for (i = 0; i < X509_CRL_get_ext_count(newer); i++) {
X509_EXTENSION *ext;
ext = X509_CRL_get_ext(newer, i);
if (!X509_CRL_add_ext(crl, ext, -1))
goto memerr;
}
/* Go through revoked entries, copying as needed */
revs = X509_CRL_get_REVOKED(newer);
for (i = 0; i < sk_X509_REVOKED_num(revs); i++) {
X509_REVOKED *rvn, *rvtmp;
rvn = sk_X509_REVOKED_value(revs, i);
/*
* Add only if not also in base. TODO: need something cleverer here
* for some more complex CRLs covering multiple CAs.
*/
if (!X509_CRL_get0_by_serial(base, &rvtmp, rvn->serialNumber)) {
rvtmp = X509_REVOKED_dup(rvn);
if (!rvtmp)
goto memerr;
if (!X509_CRL_add0_revoked(crl, rvtmp)) {
X509_REVOKED_free(rvtmp);
goto memerr;
}
}
}
/* TODO: optionally prune deleted entries */
if (skey && md && !X509_CRL_sign(crl, skey, md))
goto memerr;
return crl;
memerr:
X509err(X509_F_X509_CRL_DIFF, ERR_R_MALLOC_FAILURE);
X509_CRL_free(crl);
return NULL;
}
int X509_STORE_CTX_get_ex_new_index(long argl, void *argp,
CRYPTO_EX_new *new_func,
CRYPTO_EX_dup *dup_func,
CRYPTO_EX_free *free_func)
{
/*
* This function is (usually) called only once, by
* SSL_get_ex_data_X509_STORE_CTX_idx (ssl/ssl_cert.c).
*/
return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509_STORE_CTX, argl, argp,
new_func, dup_func, free_func);
}
int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
{
return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
}
void *X509_STORE_CTX_get_ex_data(X509_STORE_CTX *ctx, int idx)
{
return CRYPTO_get_ex_data(&ctx->ex_data, idx);
}
int X509_STORE_CTX_get_error(X509_STORE_CTX *ctx)
{
return ctx->error;
}
void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
{
ctx->error = err;
}
int X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx)
{
return ctx->error_depth;
}
X509 *X509_STORE_CTX_get_current_cert(X509_STORE_CTX *ctx)
{
return ctx->current_cert;
}
STACK_OF(X509) *X509_STORE_CTX_get_chain(X509_STORE_CTX *ctx)
{
return ctx->chain;
}
STACK_OF(X509) *X509_STORE_CTX_get1_chain(X509_STORE_CTX *ctx)
{
if (!ctx->chain)
return NULL;
return X509_chain_up_ref(ctx->chain);
}
X509 *X509_STORE_CTX_get0_current_issuer(X509_STORE_CTX *ctx)
{
return ctx->current_issuer;
}
X509_CRL *X509_STORE_CTX_get0_current_crl(X509_STORE_CTX *ctx)
{
return ctx->current_crl;
}
X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(X509_STORE_CTX *ctx)
{
return ctx->parent;
}
void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
{
ctx->cert = x;
}
void X509_STORE_CTX_set_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
{
ctx->untrusted = sk;
}
void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
{
ctx->crls = sk;
}
int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
{
return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
}
int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
{
return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
}
/*
* This function is used to set the X509_STORE_CTX purpose and trust values.
* This is intended to be used when another structure has its own trust and
* purpose values which (if set) will be inherited by the ctx. If they aren't
* set then we will usually have a default purpose in mind which should then
* be used to set the trust value. An example of this is SSL use: an SSL
* structure will have its own purpose and trust settings which the
* application can set: if they aren't set then we use the default of SSL
* client/server.
*/
int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
int purpose, int trust)
{
int idx;
/* If purpose not set use default */
if (!purpose)
purpose = def_purpose;
/* If we have a purpose then check it is valid */
if (purpose) {
X509_PURPOSE *ptmp;
idx = X509_PURPOSE_get_by_id(purpose);
if (idx == -1) {
X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
X509_R_UNKNOWN_PURPOSE_ID);
return 0;
}
ptmp = X509_PURPOSE_get0(idx);
if (ptmp->trust == X509_TRUST_DEFAULT) {
idx = X509_PURPOSE_get_by_id(def_purpose);
if (idx == -1) {
X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
X509_R_UNKNOWN_PURPOSE_ID);
return 0;
}
ptmp = X509_PURPOSE_get0(idx);
}
/* If trust not set then get from purpose default */
if (!trust)
trust = ptmp->trust;
}
if (trust) {
idx = X509_TRUST_get_by_id(trust);
if (idx == -1) {
X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
X509_R_UNKNOWN_TRUST_ID);
return 0;
}
}
if (purpose && !ctx->param->purpose)
ctx->param->purpose = purpose;
if (trust && !ctx->param->trust)
ctx->param->trust = trust;
return 1;
}
X509_STORE_CTX *X509_STORE_CTX_new(void)
{
X509_STORE_CTX *ctx = OPENSSL_malloc(sizeof(*ctx));
if (!ctx) {
X509err(X509_F_X509_STORE_CTX_NEW, ERR_R_MALLOC_FAILURE);
return NULL;
}
memset(ctx, 0, sizeof(*ctx));
return ctx;
}
void X509_STORE_CTX_free(X509_STORE_CTX *ctx)
{
if (!ctx)
return;
X509_STORE_CTX_cleanup(ctx);
OPENSSL_free(ctx);
}
int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509,
STACK_OF(X509) *chain)
{
int ret = 1;
ctx->ctx = store;
ctx->current_method = 0;
ctx->cert = x509;
ctx->untrusted = chain;
ctx->crls = NULL;
ctx->last_untrusted = 0;
ctx->other_ctx = NULL;
ctx->valid = 0;
ctx->chain = NULL;
ctx->error = 0;
ctx->explicit_policy = 0;
ctx->error_depth = 0;
ctx->current_cert = NULL;
ctx->current_issuer = NULL;
ctx->current_crl = NULL;
ctx->current_crl_score = 0;
ctx->current_reasons = 0;
ctx->tree = NULL;
ctx->parent = NULL;
ctx->param = X509_VERIFY_PARAM_new();
if (!ctx->param) {
X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
return 0;
}
/*
* Inherit callbacks and flags from X509_STORE if not set use defaults.
*/
if (store)
ret = X509_VERIFY_PARAM_inherit(ctx->param, store->param);
else
ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT | X509_VP_FLAG_ONCE;
if (store) {
ctx->verify_cb = store->verify_cb;
ctx->cleanup = store->cleanup;
} else
ctx->cleanup = 0;
if (ret)
ret = X509_VERIFY_PARAM_inherit(ctx->param,
X509_VERIFY_PARAM_lookup("default"));
if (ret == 0) {
X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
return 0;
}
if (store && store->check_issued)
ctx->check_issued = store->check_issued;
else
ctx->check_issued = check_issued;
if (store && store->get_issuer)
ctx->get_issuer = store->get_issuer;
else
ctx->get_issuer = X509_STORE_CTX_get1_issuer;
if (store && store->verify_cb)
ctx->verify_cb = store->verify_cb;
else
ctx->verify_cb = null_callback;
if (store && store->verify)
ctx->verify = store->verify;
else
ctx->verify = internal_verify;
if (store && store->check_revocation)
ctx->check_revocation = store->check_revocation;
else
ctx->check_revocation = check_revocation;
if (store && store->get_crl)
ctx->get_crl = store->get_crl;
else
ctx->get_crl = NULL;
if (store && store->check_crl)
ctx->check_crl = store->check_crl;
else
ctx->check_crl = check_crl;
if (store && store->cert_crl)
ctx->cert_crl = store->cert_crl;
else
ctx->cert_crl = cert_crl;
if (store && store->lookup_certs)
ctx->lookup_certs = store->lookup_certs;
else
ctx->lookup_certs = X509_STORE_get1_certs;
if (store && store->lookup_crls)
ctx->lookup_crls = store->lookup_crls;
else
ctx->lookup_crls = X509_STORE_get1_crls;
ctx->check_policy = check_policy;
/*
* Since X509_STORE_CTX_cleanup does a proper "free" on the ex_data, we
* put a corresponding "new" here.
*/
if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
&(ctx->ex_data))) {
OPENSSL_free(ctx);
X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
return 0;
}
return 1;
}
/*
* Set alternative lookup method: just a STACK of trusted certificates. This
* avoids X509_STORE nastiness where it isn't needed.
*/
void X509_STORE_CTX_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
{
ctx->other_ctx = sk;
ctx->get_issuer = get_issuer_sk;
}
void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
{
if (ctx->cleanup)
ctx->cleanup(ctx);
if (ctx->param != NULL) {
if (ctx->parent == NULL)
X509_VERIFY_PARAM_free(ctx->param);
ctx->param = NULL;
}
X509_policy_tree_free(ctx->tree);
ctx->tree = NULL;
sk_X509_pop_free(ctx->chain, X509_free);
ctx->chain = NULL;
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data));
memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
}
void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
{
X509_VERIFY_PARAM_set_depth(ctx->param, depth);
}
void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
{
X509_VERIFY_PARAM_set_flags(ctx->param, flags);
}
void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags,
time_t t)
{
X509_VERIFY_PARAM_set_time(ctx->param, t);
}
void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
int (*verify_cb) (int, X509_STORE_CTX *))
{
ctx->verify_cb = verify_cb;
}
X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(X509_STORE_CTX *ctx)
{
return ctx->tree;
}
int X509_STORE_CTX_get_explicit_policy(X509_STORE_CTX *ctx)
{
return ctx->explicit_policy;
}
int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
{
const X509_VERIFY_PARAM *param;
param = X509_VERIFY_PARAM_lookup(name);
if (!param)
return 0;
return X509_VERIFY_PARAM_inherit(ctx->param, param);
}
X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(X509_STORE_CTX *ctx)
{
return ctx->param;
}
void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
{
X509_VERIFY_PARAM_free(ctx->param);
ctx->param = param;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1494_0 |
crossvul-cpp_data_good_4946_5 | #include "cache.h"
#include "commit.h"
#include "tag.h"
#include "diff.h"
#include "revision.h"
#include "progress.h"
#include "list-objects.h"
#include "pack.h"
#include "pack-bitmap.h"
#include "pack-revindex.h"
#include "pack-objects.h"
/*
* An entry on the bitmap index, representing the bitmap for a given
* commit.
*/
struct stored_bitmap {
unsigned char sha1[20];
struct ewah_bitmap *root;
struct stored_bitmap *xor;
int flags;
};
/*
* The currently active bitmap index. By design, repositories only have
* a single bitmap index available (the index for the biggest packfile in
* the repository), since bitmap indexes need full closure.
*
* If there is more than one bitmap index available (e.g. because of alternates),
* the active bitmap index is the largest one.
*/
static struct bitmap_index {
/* Packfile to which this bitmap index belongs to */
struct packed_git *pack;
/*
* Mark the first `reuse_objects` in the packfile as reused:
* they will be sent as-is without using them for repacking
* calculations
*/
uint32_t reuse_objects;
/* mmapped buffer of the whole bitmap index */
unsigned char *map;
size_t map_size; /* size of the mmaped buffer */
size_t map_pos; /* current position when loading the index */
/*
* Type indexes.
*
* Each bitmap marks which objects in the packfile are of the given
* type. This provides type information when yielding the objects from
* the packfile during a walk, which allows for better delta bases.
*/
struct ewah_bitmap *commits;
struct ewah_bitmap *trees;
struct ewah_bitmap *blobs;
struct ewah_bitmap *tags;
/* Map from SHA1 -> `stored_bitmap` for all the bitmapped commits */
khash_sha1 *bitmaps;
/* Number of bitmapped commits */
uint32_t entry_count;
/* Name-hash cache (or NULL if not present). */
uint32_t *hashes;
/*
* Extended index.
*
* When trying to perform bitmap operations with objects that are not
* packed in `pack`, these objects are added to this "fake index" and
* are assumed to appear at the end of the packfile for all operations
*/
struct eindex {
struct object **objects;
uint32_t *hashes;
uint32_t count, alloc;
khash_sha1_pos *positions;
} ext_index;
/* Bitmap result of the last performed walk */
struct bitmap *result;
/* Version of the bitmap index */
unsigned int version;
unsigned loaded : 1;
} bitmap_git;
static struct ewah_bitmap *lookup_stored_bitmap(struct stored_bitmap *st)
{
struct ewah_bitmap *parent;
struct ewah_bitmap *composed;
if (st->xor == NULL)
return st->root;
composed = ewah_pool_new();
parent = lookup_stored_bitmap(st->xor);
ewah_xor(st->root, parent, composed);
ewah_pool_free(st->root);
st->root = composed;
st->xor = NULL;
return composed;
}
/*
* Read a bitmap from the current read position on the mmaped
* index, and increase the read position accordingly
*/
static struct ewah_bitmap *read_bitmap_1(struct bitmap_index *index)
{
struct ewah_bitmap *b = ewah_pool_new();
int bitmap_size = ewah_read_mmap(b,
index->map + index->map_pos,
index->map_size - index->map_pos);
if (bitmap_size < 0) {
error("Failed to load bitmap index (corrupted?)");
ewah_pool_free(b);
return NULL;
}
index->map_pos += bitmap_size;
return b;
}
static int load_bitmap_header(struct bitmap_index *index)
{
struct bitmap_disk_header *header = (void *)index->map;
if (index->map_size < sizeof(*header) + 20)
return error("Corrupted bitmap index (missing header data)");
if (memcmp(header->magic, BITMAP_IDX_SIGNATURE, sizeof(BITMAP_IDX_SIGNATURE)) != 0)
return error("Corrupted bitmap index file (wrong header)");
index->version = ntohs(header->version);
if (index->version != 1)
return error("Unsupported version for bitmap index file (%d)", index->version);
/* Parse known bitmap format options */
{
uint32_t flags = ntohs(header->options);
if ((flags & BITMAP_OPT_FULL_DAG) == 0)
return error("Unsupported options for bitmap index file "
"(Git requires BITMAP_OPT_FULL_DAG)");
if (flags & BITMAP_OPT_HASH_CACHE) {
unsigned char *end = index->map + index->map_size - 20;
index->hashes = ((uint32_t *)end) - index->pack->num_objects;
}
}
index->entry_count = ntohl(header->entry_count);
index->map_pos += sizeof(*header);
return 0;
}
static struct stored_bitmap *store_bitmap(struct bitmap_index *index,
struct ewah_bitmap *root,
const unsigned char *sha1,
struct stored_bitmap *xor_with,
int flags)
{
struct stored_bitmap *stored;
khiter_t hash_pos;
int ret;
stored = xmalloc(sizeof(struct stored_bitmap));
stored->root = root;
stored->xor = xor_with;
stored->flags = flags;
hashcpy(stored->sha1, sha1);
hash_pos = kh_put_sha1(index->bitmaps, stored->sha1, &ret);
/* a 0 return code means the insertion succeeded with no changes,
* because the SHA1 already existed on the map. this is bad, there
* shouldn't be duplicated commits in the index */
if (ret == 0) {
error("Duplicate entry in bitmap index: %s", sha1_to_hex(sha1));
return NULL;
}
kh_value(index->bitmaps, hash_pos) = stored;
return stored;
}
static inline uint32_t read_be32(const unsigned char *buffer, size_t *pos)
{
uint32_t result = get_be32(buffer + *pos);
(*pos) += sizeof(result);
return result;
}
static inline uint8_t read_u8(const unsigned char *buffer, size_t *pos)
{
return buffer[(*pos)++];
}
#define MAX_XOR_OFFSET 160
static int load_bitmap_entries_v1(struct bitmap_index *index)
{
uint32_t i;
struct stored_bitmap *recent_bitmaps[MAX_XOR_OFFSET] = { NULL };
for (i = 0; i < index->entry_count; ++i) {
int xor_offset, flags;
struct ewah_bitmap *bitmap = NULL;
struct stored_bitmap *xor_bitmap = NULL;
uint32_t commit_idx_pos;
const unsigned char *sha1;
commit_idx_pos = read_be32(index->map, &index->map_pos);
xor_offset = read_u8(index->map, &index->map_pos);
flags = read_u8(index->map, &index->map_pos);
sha1 = nth_packed_object_sha1(index->pack, commit_idx_pos);
bitmap = read_bitmap_1(index);
if (!bitmap)
return -1;
if (xor_offset > MAX_XOR_OFFSET || xor_offset > i)
return error("Corrupted bitmap pack index");
if (xor_offset > 0) {
xor_bitmap = recent_bitmaps[(i - xor_offset) % MAX_XOR_OFFSET];
if (xor_bitmap == NULL)
return error("Invalid XOR offset in bitmap pack index");
}
recent_bitmaps[i % MAX_XOR_OFFSET] = store_bitmap(
index, bitmap, sha1, xor_bitmap, flags);
}
return 0;
}
static char *pack_bitmap_filename(struct packed_git *p)
{
size_t len;
if (!strip_suffix(p->pack_name, ".pack", &len))
die("BUG: pack_name does not end in .pack");
return xstrfmt("%.*s.bitmap", (int)len, p->pack_name);
}
static int open_pack_bitmap_1(struct packed_git *packfile)
{
int fd;
struct stat st;
char *idx_name;
if (open_pack_index(packfile))
return -1;
idx_name = pack_bitmap_filename(packfile);
fd = git_open_noatime(idx_name);
free(idx_name);
if (fd < 0)
return -1;
if (fstat(fd, &st)) {
close(fd);
return -1;
}
if (bitmap_git.pack) {
warning("ignoring extra bitmap file: %s", packfile->pack_name);
close(fd);
return -1;
}
bitmap_git.pack = packfile;
bitmap_git.map_size = xsize_t(st.st_size);
bitmap_git.map = xmmap(NULL, bitmap_git.map_size, PROT_READ, MAP_PRIVATE, fd, 0);
bitmap_git.map_pos = 0;
close(fd);
if (load_bitmap_header(&bitmap_git) < 0) {
munmap(bitmap_git.map, bitmap_git.map_size);
bitmap_git.map = NULL;
bitmap_git.map_size = 0;
return -1;
}
return 0;
}
static int load_pack_bitmap(void)
{
assert(bitmap_git.map && !bitmap_git.loaded);
bitmap_git.bitmaps = kh_init_sha1();
bitmap_git.ext_index.positions = kh_init_sha1_pos();
load_pack_revindex(bitmap_git.pack);
if (!(bitmap_git.commits = read_bitmap_1(&bitmap_git)) ||
!(bitmap_git.trees = read_bitmap_1(&bitmap_git)) ||
!(bitmap_git.blobs = read_bitmap_1(&bitmap_git)) ||
!(bitmap_git.tags = read_bitmap_1(&bitmap_git)))
goto failed;
if (load_bitmap_entries_v1(&bitmap_git) < 0)
goto failed;
bitmap_git.loaded = 1;
return 0;
failed:
munmap(bitmap_git.map, bitmap_git.map_size);
bitmap_git.map = NULL;
bitmap_git.map_size = 0;
return -1;
}
static int open_pack_bitmap(void)
{
struct packed_git *p;
int ret = -1;
assert(!bitmap_git.map && !bitmap_git.loaded);
prepare_packed_git();
for (p = packed_git; p; p = p->next) {
if (open_pack_bitmap_1(p) == 0)
ret = 0;
}
return ret;
}
int prepare_bitmap_git(void)
{
if (bitmap_git.loaded)
return 0;
if (!open_pack_bitmap())
return load_pack_bitmap();
return -1;
}
struct include_data {
struct bitmap *base;
struct bitmap *seen;
};
static inline int bitmap_position_extended(const unsigned char *sha1)
{
khash_sha1_pos *positions = bitmap_git.ext_index.positions;
khiter_t pos = kh_get_sha1_pos(positions, sha1);
if (pos < kh_end(positions)) {
int bitmap_pos = kh_value(positions, pos);
return bitmap_pos + bitmap_git.pack->num_objects;
}
return -1;
}
static inline int bitmap_position_packfile(const unsigned char *sha1)
{
off_t offset = find_pack_entry_one(sha1, bitmap_git.pack);
if (!offset)
return -1;
return find_revindex_position(bitmap_git.pack, offset);
}
static int bitmap_position(const unsigned char *sha1)
{
int pos = bitmap_position_packfile(sha1);
return (pos >= 0) ? pos : bitmap_position_extended(sha1);
}
static int ext_index_add_object(struct object *object, const char *name)
{
struct eindex *eindex = &bitmap_git.ext_index;
khiter_t hash_pos;
int hash_ret;
int bitmap_pos;
hash_pos = kh_put_sha1_pos(eindex->positions, object->oid.hash, &hash_ret);
if (hash_ret > 0) {
if (eindex->count >= eindex->alloc) {
eindex->alloc = (eindex->alloc + 16) * 3 / 2;
REALLOC_ARRAY(eindex->objects, eindex->alloc);
REALLOC_ARRAY(eindex->hashes, eindex->alloc);
}
bitmap_pos = eindex->count;
eindex->objects[eindex->count] = object;
eindex->hashes[eindex->count] = pack_name_hash(name);
kh_value(eindex->positions, hash_pos) = bitmap_pos;
eindex->count++;
} else {
bitmap_pos = kh_value(eindex->positions, hash_pos);
}
return bitmap_pos + bitmap_git.pack->num_objects;
}
static void show_object(struct object *object, const char *name, void *data)
{
struct bitmap *base = data;
int bitmap_pos;
bitmap_pos = bitmap_position(object->oid.hash);
if (bitmap_pos < 0)
bitmap_pos = ext_index_add_object(object, name);
bitmap_set(base, bitmap_pos);
}
static void show_commit(struct commit *commit, void *data)
{
}
static int add_to_include_set(struct include_data *data,
const unsigned char *sha1,
int bitmap_pos)
{
khiter_t hash_pos;
if (data->seen && bitmap_get(data->seen, bitmap_pos))
return 0;
if (bitmap_get(data->base, bitmap_pos))
return 0;
hash_pos = kh_get_sha1(bitmap_git.bitmaps, sha1);
if (hash_pos < kh_end(bitmap_git.bitmaps)) {
struct stored_bitmap *st = kh_value(bitmap_git.bitmaps, hash_pos);
bitmap_or_ewah(data->base, lookup_stored_bitmap(st));
return 0;
}
bitmap_set(data->base, bitmap_pos);
return 1;
}
static int should_include(struct commit *commit, void *_data)
{
struct include_data *data = _data;
int bitmap_pos;
bitmap_pos = bitmap_position(commit->object.oid.hash);
if (bitmap_pos < 0)
bitmap_pos = ext_index_add_object((struct object *)commit, NULL);
if (!add_to_include_set(data, commit->object.oid.hash, bitmap_pos)) {
struct commit_list *parent = commit->parents;
while (parent) {
parent->item->object.flags |= SEEN;
parent = parent->next;
}
return 0;
}
return 1;
}
static struct bitmap *find_objects(struct rev_info *revs,
struct object_list *roots,
struct bitmap *seen)
{
struct bitmap *base = NULL;
int needs_walk = 0;
struct object_list *not_mapped = NULL;
/*
* Go through all the roots for the walk. The ones that have bitmaps
* on the bitmap index will be `or`ed together to form an initial
* global reachability analysis.
*
* The ones without bitmaps in the index will be stored in the
* `not_mapped_list` for further processing.
*/
while (roots) {
struct object *object = roots->item;
roots = roots->next;
if (object->type == OBJ_COMMIT) {
khiter_t pos = kh_get_sha1(bitmap_git.bitmaps, object->oid.hash);
if (pos < kh_end(bitmap_git.bitmaps)) {
struct stored_bitmap *st = kh_value(bitmap_git.bitmaps, pos);
struct ewah_bitmap *or_with = lookup_stored_bitmap(st);
if (base == NULL)
base = ewah_to_bitmap(or_with);
else
bitmap_or_ewah(base, or_with);
object->flags |= SEEN;
continue;
}
}
object_list_insert(object, ¬_mapped);
}
/*
* Best case scenario: We found bitmaps for all the roots,
* so the resulting `or` bitmap has the full reachability analysis
*/
if (not_mapped == NULL)
return base;
roots = not_mapped;
/*
* Let's iterate through all the roots that don't have bitmaps to
* check if we can determine them to be reachable from the existing
* global bitmap.
*
* If we cannot find them in the existing global bitmap, we'll need
* to push them to an actual walk and run it until we can confirm
* they are reachable
*/
while (roots) {
struct object *object = roots->item;
int pos;
roots = roots->next;
pos = bitmap_position(object->oid.hash);
if (pos < 0 || base == NULL || !bitmap_get(base, pos)) {
object->flags &= ~UNINTERESTING;
add_pending_object(revs, object, "");
needs_walk = 1;
} else {
object->flags |= SEEN;
}
}
if (needs_walk) {
struct include_data incdata;
if (base == NULL)
base = bitmap_new();
incdata.base = base;
incdata.seen = seen;
revs->include_check = should_include;
revs->include_check_data = &incdata;
if (prepare_revision_walk(revs))
die("revision walk setup failed");
traverse_commit_list(revs, show_commit, show_object, base);
}
return base;
}
static void show_extended_objects(struct bitmap *objects,
show_reachable_fn show_reach)
{
struct eindex *eindex = &bitmap_git.ext_index;
uint32_t i;
for (i = 0; i < eindex->count; ++i) {
struct object *obj;
if (!bitmap_get(objects, bitmap_git.pack->num_objects + i))
continue;
obj = eindex->objects[i];
show_reach(obj->oid.hash, obj->type, 0, eindex->hashes[i], NULL, 0);
}
}
static void show_objects_for_type(
struct bitmap *objects,
struct ewah_bitmap *type_filter,
enum object_type object_type,
show_reachable_fn show_reach)
{
size_t pos = 0, i = 0;
uint32_t offset;
struct ewah_iterator it;
eword_t filter;
if (bitmap_git.reuse_objects == bitmap_git.pack->num_objects)
return;
ewah_iterator_init(&it, type_filter);
while (i < objects->word_alloc && ewah_iterator_next(&filter, &it)) {
eword_t word = objects->words[i] & filter;
for (offset = 0; offset < BITS_IN_EWORD; ++offset) {
const unsigned char *sha1;
struct revindex_entry *entry;
uint32_t hash = 0;
if ((word >> offset) == 0)
break;
offset += ewah_bit_ctz64(word >> offset);
if (pos + offset < bitmap_git.reuse_objects)
continue;
entry = &bitmap_git.pack->revindex[pos + offset];
sha1 = nth_packed_object_sha1(bitmap_git.pack, entry->nr);
if (bitmap_git.hashes)
hash = ntohl(bitmap_git.hashes[entry->nr]);
show_reach(sha1, object_type, 0, hash, bitmap_git.pack, entry->offset);
}
pos += BITS_IN_EWORD;
i++;
}
}
static int in_bitmapped_pack(struct object_list *roots)
{
while (roots) {
struct object *object = roots->item;
roots = roots->next;
if (find_pack_entry_one(object->oid.hash, bitmap_git.pack) > 0)
return 1;
}
return 0;
}
int prepare_bitmap_walk(struct rev_info *revs)
{
unsigned int i;
unsigned int pending_nr = revs->pending.nr;
struct object_array_entry *pending_e = revs->pending.objects;
struct object_list *wants = NULL;
struct object_list *haves = NULL;
struct bitmap *wants_bitmap = NULL;
struct bitmap *haves_bitmap = NULL;
if (!bitmap_git.loaded) {
/* try to open a bitmapped pack, but don't parse it yet
* because we may not need to use it */
if (open_pack_bitmap() < 0)
return -1;
}
for (i = 0; i < pending_nr; ++i) {
struct object *object = pending_e[i].item;
if (object->type == OBJ_NONE)
parse_object_or_die(object->oid.hash, NULL);
while (object->type == OBJ_TAG) {
struct tag *tag = (struct tag *) object;
if (object->flags & UNINTERESTING)
object_list_insert(object, &haves);
else
object_list_insert(object, &wants);
if (!tag->tagged)
die("bad tag");
object = parse_object_or_die(tag->tagged->oid.hash, NULL);
}
if (object->flags & UNINTERESTING)
object_list_insert(object, &haves);
else
object_list_insert(object, &wants);
}
/*
* if we have a HAVES list, but none of those haves is contained
* in the packfile that has a bitmap, we don't have anything to
* optimize here
*/
if (haves && !in_bitmapped_pack(haves))
return -1;
/* if we don't want anything, we're done here */
if (!wants)
return -1;
/*
* now we're going to use bitmaps, so load the actual bitmap entries
* from disk. this is the point of no return; after this the rev_list
* becomes invalidated and we must perform the revwalk through bitmaps
*/
if (!bitmap_git.loaded && load_pack_bitmap() < 0)
return -1;
revs->pending.nr = 0;
revs->pending.alloc = 0;
revs->pending.objects = NULL;
if (haves) {
revs->ignore_missing_links = 1;
haves_bitmap = find_objects(revs, haves, NULL);
reset_revision_walk();
revs->ignore_missing_links = 0;
if (haves_bitmap == NULL)
die("BUG: failed to perform bitmap walk");
}
wants_bitmap = find_objects(revs, wants, haves_bitmap);
if (!wants_bitmap)
die("BUG: failed to perform bitmap walk");
if (haves_bitmap)
bitmap_and_not(wants_bitmap, haves_bitmap);
bitmap_git.result = wants_bitmap;
bitmap_free(haves_bitmap);
return 0;
}
int reuse_partial_packfile_from_bitmap(struct packed_git **packfile,
uint32_t *entries,
off_t *up_to)
{
/*
* Reuse the packfile content if we need more than
* 90% of its objects
*/
static const double REUSE_PERCENT = 0.9;
struct bitmap *result = bitmap_git.result;
uint32_t reuse_threshold;
uint32_t i, reuse_objects = 0;
assert(result);
for (i = 0; i < result->word_alloc; ++i) {
if (result->words[i] != (eword_t)~0) {
reuse_objects += ewah_bit_ctz64(~result->words[i]);
break;
}
reuse_objects += BITS_IN_EWORD;
}
#ifdef GIT_BITMAP_DEBUG
{
const unsigned char *sha1;
struct revindex_entry *entry;
entry = &bitmap_git.reverse_index->revindex[reuse_objects];
sha1 = nth_packed_object_sha1(bitmap_git.pack, entry->nr);
fprintf(stderr, "Failed to reuse at %d (%016llx)\n",
reuse_objects, result->words[i]);
fprintf(stderr, " %s\n", sha1_to_hex(sha1));
}
#endif
if (!reuse_objects)
return -1;
if (reuse_objects >= bitmap_git.pack->num_objects) {
bitmap_git.reuse_objects = *entries = bitmap_git.pack->num_objects;
*up_to = -1; /* reuse the full pack */
*packfile = bitmap_git.pack;
return 0;
}
reuse_threshold = bitmap_popcount(bitmap_git.result) * REUSE_PERCENT;
if (reuse_objects < reuse_threshold)
return -1;
bitmap_git.reuse_objects = *entries = reuse_objects;
*up_to = bitmap_git.pack->revindex[reuse_objects].offset;
*packfile = bitmap_git.pack;
return 0;
}
void traverse_bitmap_commit_list(show_reachable_fn show_reachable)
{
assert(bitmap_git.result);
show_objects_for_type(bitmap_git.result, bitmap_git.commits,
OBJ_COMMIT, show_reachable);
show_objects_for_type(bitmap_git.result, bitmap_git.trees,
OBJ_TREE, show_reachable);
show_objects_for_type(bitmap_git.result, bitmap_git.blobs,
OBJ_BLOB, show_reachable);
show_objects_for_type(bitmap_git.result, bitmap_git.tags,
OBJ_TAG, show_reachable);
show_extended_objects(bitmap_git.result, show_reachable);
bitmap_free(bitmap_git.result);
bitmap_git.result = NULL;
}
static uint32_t count_object_type(struct bitmap *objects,
enum object_type type)
{
struct eindex *eindex = &bitmap_git.ext_index;
uint32_t i = 0, count = 0;
struct ewah_iterator it;
eword_t filter;
switch (type) {
case OBJ_COMMIT:
ewah_iterator_init(&it, bitmap_git.commits);
break;
case OBJ_TREE:
ewah_iterator_init(&it, bitmap_git.trees);
break;
case OBJ_BLOB:
ewah_iterator_init(&it, bitmap_git.blobs);
break;
case OBJ_TAG:
ewah_iterator_init(&it, bitmap_git.tags);
break;
default:
return 0;
}
while (i < objects->word_alloc && ewah_iterator_next(&filter, &it)) {
eword_t word = objects->words[i++] & filter;
count += ewah_bit_popcount64(word);
}
for (i = 0; i < eindex->count; ++i) {
if (eindex->objects[i]->type == type &&
bitmap_get(objects, bitmap_git.pack->num_objects + i))
count++;
}
return count;
}
void count_bitmap_commit_list(uint32_t *commits, uint32_t *trees,
uint32_t *blobs, uint32_t *tags)
{
assert(bitmap_git.result);
if (commits)
*commits = count_object_type(bitmap_git.result, OBJ_COMMIT);
if (trees)
*trees = count_object_type(bitmap_git.result, OBJ_TREE);
if (blobs)
*blobs = count_object_type(bitmap_git.result, OBJ_BLOB);
if (tags)
*tags = count_object_type(bitmap_git.result, OBJ_TAG);
}
struct bitmap_test_data {
struct bitmap *base;
struct progress *prg;
size_t seen;
};
static void test_show_object(struct object *object, const char *name,
void *data)
{
struct bitmap_test_data *tdata = data;
int bitmap_pos;
bitmap_pos = bitmap_position(object->oid.hash);
if (bitmap_pos < 0)
die("Object not in bitmap: %s\n", oid_to_hex(&object->oid));
bitmap_set(tdata->base, bitmap_pos);
display_progress(tdata->prg, ++tdata->seen);
}
static void test_show_commit(struct commit *commit, void *data)
{
struct bitmap_test_data *tdata = data;
int bitmap_pos;
bitmap_pos = bitmap_position(commit->object.oid.hash);
if (bitmap_pos < 0)
die("Object not in bitmap: %s\n", oid_to_hex(&commit->object.oid));
bitmap_set(tdata->base, bitmap_pos);
display_progress(tdata->prg, ++tdata->seen);
}
void test_bitmap_walk(struct rev_info *revs)
{
struct object *root;
struct bitmap *result = NULL;
khiter_t pos;
size_t result_popcnt;
struct bitmap_test_data tdata;
if (prepare_bitmap_git())
die("failed to load bitmap indexes");
if (revs->pending.nr != 1)
die("you must specify exactly one commit to test");
fprintf(stderr, "Bitmap v%d test (%d entries loaded)\n",
bitmap_git.version, bitmap_git.entry_count);
root = revs->pending.objects[0].item;
pos = kh_get_sha1(bitmap_git.bitmaps, root->oid.hash);
if (pos < kh_end(bitmap_git.bitmaps)) {
struct stored_bitmap *st = kh_value(bitmap_git.bitmaps, pos);
struct ewah_bitmap *bm = lookup_stored_bitmap(st);
fprintf(stderr, "Found bitmap for %s. %d bits / %08x checksum\n",
oid_to_hex(&root->oid), (int)bm->bit_size, ewah_checksum(bm));
result = ewah_to_bitmap(bm);
}
if (result == NULL)
die("Commit %s doesn't have an indexed bitmap", oid_to_hex(&root->oid));
revs->tag_objects = 1;
revs->tree_objects = 1;
revs->blob_objects = 1;
result_popcnt = bitmap_popcount(result);
if (prepare_revision_walk(revs))
die("revision walk setup failed");
tdata.base = bitmap_new();
tdata.prg = start_progress("Verifying bitmap entries", result_popcnt);
tdata.seen = 0;
traverse_commit_list(revs, &test_show_commit, &test_show_object, &tdata);
stop_progress(&tdata.prg);
if (bitmap_equals(result, tdata.base))
fprintf(stderr, "OK!\n");
else
fprintf(stderr, "Mismatch!\n");
bitmap_free(result);
}
static int rebuild_bitmap(uint32_t *reposition,
struct ewah_bitmap *source,
struct bitmap *dest)
{
uint32_t pos = 0;
struct ewah_iterator it;
eword_t word;
ewah_iterator_init(&it, source);
while (ewah_iterator_next(&word, &it)) {
uint32_t offset, bit_pos;
for (offset = 0; offset < BITS_IN_EWORD; ++offset) {
if ((word >> offset) == 0)
break;
offset += ewah_bit_ctz64(word >> offset);
bit_pos = reposition[pos + offset];
if (bit_pos > 0)
bitmap_set(dest, bit_pos - 1);
else /* can't reuse, we don't have the object */
return -1;
}
pos += BITS_IN_EWORD;
}
return 0;
}
int rebuild_existing_bitmaps(struct packing_data *mapping,
khash_sha1 *reused_bitmaps,
int show_progress)
{
uint32_t i, num_objects;
uint32_t *reposition;
struct bitmap *rebuild;
struct stored_bitmap *stored;
struct progress *progress = NULL;
khiter_t hash_pos;
int hash_ret;
if (prepare_bitmap_git() < 0)
return -1;
num_objects = bitmap_git.pack->num_objects;
reposition = xcalloc(num_objects, sizeof(uint32_t));
for (i = 0; i < num_objects; ++i) {
const unsigned char *sha1;
struct revindex_entry *entry;
struct object_entry *oe;
entry = &bitmap_git.pack->revindex[i];
sha1 = nth_packed_object_sha1(bitmap_git.pack, entry->nr);
oe = packlist_find(mapping, sha1, NULL);
if (oe)
reposition[i] = oe->in_pack_pos + 1;
}
rebuild = bitmap_new();
i = 0;
if (show_progress)
progress = start_progress("Reusing bitmaps", 0);
kh_foreach_value(bitmap_git.bitmaps, stored, {
if (stored->flags & BITMAP_FLAG_REUSE) {
if (!rebuild_bitmap(reposition,
lookup_stored_bitmap(stored),
rebuild)) {
hash_pos = kh_put_sha1(reused_bitmaps,
stored->sha1,
&hash_ret);
kh_value(reused_bitmaps, hash_pos) =
bitmap_to_ewah(rebuild);
}
bitmap_reset(rebuild);
display_progress(progress, ++i);
}
});
stop_progress(&progress);
free(reposition);
bitmap_free(rebuild);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4946_5 |
crossvul-cpp_data_good_5142_0 | /*
* Intel MIC Platform Software Stack (MPSS)
*
* Copyright(c) 2016 Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*
* 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.
*
* The full GNU General Public License is included in this distribution in
* the file called "COPYING".
*
* Intel Virtio Over PCIe (VOP) driver.
*
*/
#include <linux/sched.h>
#include <linux/poll.h>
#include <linux/dma-mapping.h>
#include <linux/mic_common.h>
#include "../common/mic_dev.h"
#include <linux/mic_ioctl.h>
#include "vop_main.h"
/* Helper API to obtain the VOP PCIe device */
static inline struct device *vop_dev(struct vop_vdev *vdev)
{
return vdev->vpdev->dev.parent;
}
/* Helper API to check if a virtio device is initialized */
static inline int vop_vdev_inited(struct vop_vdev *vdev)
{
if (!vdev)
return -EINVAL;
/* Device has not been created yet */
if (!vdev->dd || !vdev->dd->type) {
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, -EINVAL);
return -EINVAL;
}
/* Device has been removed/deleted */
if (vdev->dd->type == -1) {
dev_dbg(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, -ENODEV);
return -ENODEV;
}
return 0;
}
static void _vop_notify(struct vringh *vrh)
{
struct vop_vringh *vvrh = container_of(vrh, struct vop_vringh, vrh);
struct vop_vdev *vdev = vvrh->vdev;
struct vop_device *vpdev = vdev->vpdev;
s8 db = vdev->dc->h2c_vdev_db;
if (db != -1)
vpdev->hw_ops->send_intr(vpdev, db);
}
static void vop_virtio_init_post(struct vop_vdev *vdev)
{
struct mic_vqconfig *vqconfig = mic_vq_config(vdev->dd);
struct vop_device *vpdev = vdev->vpdev;
int i, used_size;
for (i = 0; i < vdev->dd->num_vq; i++) {
used_size = PAGE_ALIGN(sizeof(u16) * 3 +
sizeof(struct vring_used_elem) *
le16_to_cpu(vqconfig->num));
if (!le64_to_cpu(vqconfig[i].used_address)) {
dev_warn(vop_dev(vdev), "used_address zero??\n");
continue;
}
vdev->vvr[i].vrh.vring.used =
(void __force *)vpdev->hw_ops->ioremap(
vpdev,
le64_to_cpu(vqconfig[i].used_address),
used_size);
}
vdev->dc->used_address_updated = 0;
dev_info(vop_dev(vdev), "%s: device type %d LINKUP\n",
__func__, vdev->virtio_id);
}
static inline void vop_virtio_device_reset(struct vop_vdev *vdev)
{
int i;
dev_dbg(vop_dev(vdev), "%s: status %d device type %d RESET\n",
__func__, vdev->dd->status, vdev->virtio_id);
for (i = 0; i < vdev->dd->num_vq; i++)
/*
* Avoid lockdep false positive. The + 1 is for the vop
* mutex which is held in the reset devices code path.
*/
mutex_lock_nested(&vdev->vvr[i].vr_mutex, i + 1);
/* 0 status means "reset" */
vdev->dd->status = 0;
vdev->dc->vdev_reset = 0;
vdev->dc->host_ack = 1;
for (i = 0; i < vdev->dd->num_vq; i++) {
struct vringh *vrh = &vdev->vvr[i].vrh;
vdev->vvr[i].vring.info->avail_idx = 0;
vrh->completed = 0;
vrh->last_avail_idx = 0;
vrh->last_used_idx = 0;
}
for (i = 0; i < vdev->dd->num_vq; i++)
mutex_unlock(&vdev->vvr[i].vr_mutex);
}
static void vop_virtio_reset_devices(struct vop_info *vi)
{
struct list_head *pos, *tmp;
struct vop_vdev *vdev;
list_for_each_safe(pos, tmp, &vi->vdev_list) {
vdev = list_entry(pos, struct vop_vdev, list);
vop_virtio_device_reset(vdev);
vdev->poll_wake = 1;
wake_up(&vdev->waitq);
}
}
static void vop_bh_handler(struct work_struct *work)
{
struct vop_vdev *vdev = container_of(work, struct vop_vdev,
virtio_bh_work);
if (vdev->dc->used_address_updated)
vop_virtio_init_post(vdev);
if (vdev->dc->vdev_reset)
vop_virtio_device_reset(vdev);
vdev->poll_wake = 1;
wake_up(&vdev->waitq);
}
static irqreturn_t _vop_virtio_intr_handler(int irq, void *data)
{
struct vop_vdev *vdev = data;
struct vop_device *vpdev = vdev->vpdev;
vpdev->hw_ops->ack_interrupt(vpdev, vdev->virtio_db);
schedule_work(&vdev->virtio_bh_work);
return IRQ_HANDLED;
}
static int vop_virtio_config_change(struct vop_vdev *vdev, void *argp)
{
DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wake);
int ret = 0, retry, i;
struct vop_device *vpdev = vdev->vpdev;
struct vop_info *vi = dev_get_drvdata(&vpdev->dev);
struct mic_bootparam *bootparam = vpdev->hw_ops->get_dp(vpdev);
s8 db = bootparam->h2c_config_db;
mutex_lock(&vi->vop_mutex);
for (i = 0; i < vdev->dd->num_vq; i++)
mutex_lock_nested(&vdev->vvr[i].vr_mutex, i + 1);
if (db == -1 || vdev->dd->type == -1) {
ret = -EIO;
goto exit;
}
memcpy(mic_vq_configspace(vdev->dd), argp, vdev->dd->config_len);
vdev->dc->config_change = MIC_VIRTIO_PARAM_CONFIG_CHANGED;
vpdev->hw_ops->send_intr(vpdev, db);
for (retry = 100; retry--;) {
ret = wait_event_timeout(wake, vdev->dc->guest_ack,
msecs_to_jiffies(100));
if (ret)
break;
}
dev_dbg(vop_dev(vdev),
"%s %d retry: %d\n", __func__, __LINE__, retry);
vdev->dc->config_change = 0;
vdev->dc->guest_ack = 0;
exit:
for (i = 0; i < vdev->dd->num_vq; i++)
mutex_unlock(&vdev->vvr[i].vr_mutex);
mutex_unlock(&vi->vop_mutex);
return ret;
}
static int vop_copy_dp_entry(struct vop_vdev *vdev,
struct mic_device_desc *argp, __u8 *type,
struct mic_device_desc **devpage)
{
struct vop_device *vpdev = vdev->vpdev;
struct mic_device_desc *devp;
struct mic_vqconfig *vqconfig;
int ret = 0, i;
bool slot_found = false;
vqconfig = mic_vq_config(argp);
for (i = 0; i < argp->num_vq; i++) {
if (le16_to_cpu(vqconfig[i].num) > MIC_MAX_VRING_ENTRIES) {
ret = -EINVAL;
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, ret);
goto exit;
}
}
/* Find the first free device page entry */
for (i = sizeof(struct mic_bootparam);
i < MIC_DP_SIZE - mic_total_desc_size(argp);
i += mic_total_desc_size(devp)) {
devp = vpdev->hw_ops->get_dp(vpdev) + i;
if (devp->type == 0 || devp->type == -1) {
slot_found = true;
break;
}
}
if (!slot_found) {
ret = -EINVAL;
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, ret);
goto exit;
}
/*
* Save off the type before doing the memcpy. Type will be set in the
* end after completing all initialization for the new device.
*/
*type = argp->type;
argp->type = 0;
memcpy(devp, argp, mic_desc_size(argp));
*devpage = devp;
exit:
return ret;
}
static void vop_init_device_ctrl(struct vop_vdev *vdev,
struct mic_device_desc *devpage)
{
struct mic_device_ctrl *dc;
dc = (void *)devpage + mic_aligned_desc_size(devpage);
dc->config_change = 0;
dc->guest_ack = 0;
dc->vdev_reset = 0;
dc->host_ack = 0;
dc->used_address_updated = 0;
dc->c2h_vdev_db = -1;
dc->h2c_vdev_db = -1;
vdev->dc = dc;
}
static int vop_virtio_add_device(struct vop_vdev *vdev,
struct mic_device_desc *argp)
{
struct vop_info *vi = vdev->vi;
struct vop_device *vpdev = vi->vpdev;
struct mic_device_desc *dd = NULL;
struct mic_vqconfig *vqconfig;
int vr_size, i, j, ret;
u8 type = 0;
s8 db = -1;
char irqname[16];
struct mic_bootparam *bootparam;
u16 num;
dma_addr_t vr_addr;
bootparam = vpdev->hw_ops->get_dp(vpdev);
init_waitqueue_head(&vdev->waitq);
INIT_LIST_HEAD(&vdev->list);
vdev->vpdev = vpdev;
ret = vop_copy_dp_entry(vdev, argp, &type, &dd);
if (ret) {
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, ret);
kfree(vdev);
return ret;
}
vop_init_device_ctrl(vdev, dd);
vdev->dd = dd;
vdev->virtio_id = type;
vqconfig = mic_vq_config(dd);
INIT_WORK(&vdev->virtio_bh_work, vop_bh_handler);
for (i = 0; i < dd->num_vq; i++) {
struct vop_vringh *vvr = &vdev->vvr[i];
struct mic_vring *vr = &vdev->vvr[i].vring;
num = le16_to_cpu(vqconfig[i].num);
mutex_init(&vvr->vr_mutex);
vr_size = PAGE_ALIGN(vring_size(num, MIC_VIRTIO_RING_ALIGN) +
sizeof(struct _mic_vring_info));
vr->va = (void *)
__get_free_pages(GFP_KERNEL | __GFP_ZERO,
get_order(vr_size));
if (!vr->va) {
ret = -ENOMEM;
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, ret);
goto err;
}
vr->len = vr_size;
vr->info = vr->va + vring_size(num, MIC_VIRTIO_RING_ALIGN);
vr->info->magic = cpu_to_le32(MIC_MAGIC + vdev->virtio_id + i);
vr_addr = dma_map_single(&vpdev->dev, vr->va, vr_size,
DMA_BIDIRECTIONAL);
if (dma_mapping_error(&vpdev->dev, vr_addr)) {
free_pages((unsigned long)vr->va, get_order(vr_size));
ret = -ENOMEM;
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, ret);
goto err;
}
vqconfig[i].address = cpu_to_le64(vr_addr);
vring_init(&vr->vr, num, vr->va, MIC_VIRTIO_RING_ALIGN);
ret = vringh_init_kern(&vvr->vrh,
*(u32 *)mic_vq_features(vdev->dd),
num, false, vr->vr.desc, vr->vr.avail,
vr->vr.used);
if (ret) {
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, ret);
goto err;
}
vringh_kiov_init(&vvr->riov, NULL, 0);
vringh_kiov_init(&vvr->wiov, NULL, 0);
vvr->head = USHRT_MAX;
vvr->vdev = vdev;
vvr->vrh.notify = _vop_notify;
dev_dbg(&vpdev->dev,
"%s %d index %d va %p info %p vr_size 0x%x\n",
__func__, __LINE__, i, vr->va, vr->info, vr_size);
vvr->buf = (void *)__get_free_pages(GFP_KERNEL,
get_order(VOP_INT_DMA_BUF_SIZE));
vvr->buf_da = dma_map_single(&vpdev->dev,
vvr->buf, VOP_INT_DMA_BUF_SIZE,
DMA_BIDIRECTIONAL);
}
snprintf(irqname, sizeof(irqname), "vop%dvirtio%d", vpdev->index,
vdev->virtio_id);
vdev->virtio_db = vpdev->hw_ops->next_db(vpdev);
vdev->virtio_cookie = vpdev->hw_ops->request_irq(vpdev,
_vop_virtio_intr_handler, irqname, vdev,
vdev->virtio_db);
if (IS_ERR(vdev->virtio_cookie)) {
ret = PTR_ERR(vdev->virtio_cookie);
dev_dbg(&vpdev->dev, "request irq failed\n");
goto err;
}
vdev->dc->c2h_vdev_db = vdev->virtio_db;
/*
* Order the type update with previous stores. This write barrier
* is paired with the corresponding read barrier before the uncached
* system memory read of the type, on the card while scanning the
* device page.
*/
smp_wmb();
dd->type = type;
argp->type = type;
if (bootparam) {
db = bootparam->h2c_config_db;
if (db != -1)
vpdev->hw_ops->send_intr(vpdev, db);
}
dev_dbg(&vpdev->dev, "Added virtio id %d db %d\n", dd->type, db);
return 0;
err:
vqconfig = mic_vq_config(dd);
for (j = 0; j < i; j++) {
struct vop_vringh *vvr = &vdev->vvr[j];
dma_unmap_single(&vpdev->dev, le64_to_cpu(vqconfig[j].address),
vvr->vring.len, DMA_BIDIRECTIONAL);
free_pages((unsigned long)vvr->vring.va,
get_order(vvr->vring.len));
}
return ret;
}
static void vop_dev_remove(struct vop_info *pvi, struct mic_device_ctrl *devp,
struct vop_device *vpdev)
{
struct mic_bootparam *bootparam = vpdev->hw_ops->get_dp(vpdev);
s8 db;
int ret, retry;
DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wake);
devp->config_change = MIC_VIRTIO_PARAM_DEV_REMOVE;
db = bootparam->h2c_config_db;
if (db != -1)
vpdev->hw_ops->send_intr(vpdev, db);
else
goto done;
for (retry = 15; retry--;) {
ret = wait_event_timeout(wake, devp->guest_ack,
msecs_to_jiffies(1000));
if (ret)
break;
}
done:
devp->config_change = 0;
devp->guest_ack = 0;
}
static void vop_virtio_del_device(struct vop_vdev *vdev)
{
struct vop_info *vi = vdev->vi;
struct vop_device *vpdev = vdev->vpdev;
int i;
struct mic_vqconfig *vqconfig;
struct mic_bootparam *bootparam = vpdev->hw_ops->get_dp(vpdev);
if (!bootparam)
goto skip_hot_remove;
vop_dev_remove(vi, vdev->dc, vpdev);
skip_hot_remove:
vpdev->hw_ops->free_irq(vpdev, vdev->virtio_cookie, vdev);
flush_work(&vdev->virtio_bh_work);
vqconfig = mic_vq_config(vdev->dd);
for (i = 0; i < vdev->dd->num_vq; i++) {
struct vop_vringh *vvr = &vdev->vvr[i];
dma_unmap_single(&vpdev->dev,
vvr->buf_da, VOP_INT_DMA_BUF_SIZE,
DMA_BIDIRECTIONAL);
free_pages((unsigned long)vvr->buf,
get_order(VOP_INT_DMA_BUF_SIZE));
vringh_kiov_cleanup(&vvr->riov);
vringh_kiov_cleanup(&vvr->wiov);
dma_unmap_single(&vpdev->dev, le64_to_cpu(vqconfig[i].address),
vvr->vring.len, DMA_BIDIRECTIONAL);
free_pages((unsigned long)vvr->vring.va,
get_order(vvr->vring.len));
}
/*
* Order the type update with previous stores. This write barrier
* is paired with the corresponding read barrier before the uncached
* system memory read of the type, on the card while scanning the
* device page.
*/
smp_wmb();
vdev->dd->type = -1;
}
/*
* vop_sync_dma - Wrapper for synchronous DMAs.
*
* @dev - The address of the pointer to the device instance used
* for DMA registration.
* @dst - destination DMA address.
* @src - source DMA address.
* @len - size of the transfer.
*
* Return DMA_SUCCESS on success
*/
static int vop_sync_dma(struct vop_vdev *vdev, dma_addr_t dst, dma_addr_t src,
size_t len)
{
int err = 0;
struct dma_device *ddev;
struct dma_async_tx_descriptor *tx;
struct vop_info *vi = dev_get_drvdata(&vdev->vpdev->dev);
struct dma_chan *vop_ch = vi->dma_ch;
if (!vop_ch) {
err = -EBUSY;
goto error;
}
ddev = vop_ch->device;
tx = ddev->device_prep_dma_memcpy(vop_ch, dst, src, len,
DMA_PREP_FENCE);
if (!tx) {
err = -ENOMEM;
goto error;
} else {
dma_cookie_t cookie;
cookie = tx->tx_submit(tx);
if (dma_submit_error(cookie)) {
err = -ENOMEM;
goto error;
}
dma_async_issue_pending(vop_ch);
err = dma_sync_wait(vop_ch, cookie);
}
error:
if (err)
dev_err(&vi->vpdev->dev, "%s %d err %d\n",
__func__, __LINE__, err);
return err;
}
#define VOP_USE_DMA true
/*
* Initiates the copies across the PCIe bus from card memory to a user
* space buffer. When transfers are done using DMA, source/destination
* addresses and transfer length must follow the alignment requirements of
* the MIC DMA engine.
*/
static int vop_virtio_copy_to_user(struct vop_vdev *vdev, void __user *ubuf,
size_t len, u64 daddr, size_t dlen,
int vr_idx)
{
struct vop_device *vpdev = vdev->vpdev;
void __iomem *dbuf = vpdev->hw_ops->ioremap(vpdev, daddr, len);
struct vop_vringh *vvr = &vdev->vvr[vr_idx];
struct vop_info *vi = dev_get_drvdata(&vpdev->dev);
size_t dma_alignment = 1 << vi->dma_ch->device->copy_align;
bool x200 = is_dma_copy_aligned(vi->dma_ch->device, 1, 1, 1);
size_t dma_offset, partlen;
int err;
if (!VOP_USE_DMA) {
if (copy_to_user(ubuf, (void __force *)dbuf, len)) {
err = -EFAULT;
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, err);
goto err;
}
vdev->in_bytes += len;
err = 0;
goto err;
}
dma_offset = daddr - round_down(daddr, dma_alignment);
daddr -= dma_offset;
len += dma_offset;
/*
* X100 uses DMA addresses as seen by the card so adding
* the aperture base is not required for DMA. However x200
* requires DMA addresses to be an offset into the bar so
* add the aperture base for x200.
*/
if (x200)
daddr += vpdev->aper->pa;
while (len) {
partlen = min_t(size_t, len, VOP_INT_DMA_BUF_SIZE);
err = vop_sync_dma(vdev, vvr->buf_da, daddr,
ALIGN(partlen, dma_alignment));
if (err) {
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, err);
goto err;
}
if (copy_to_user(ubuf, vvr->buf + dma_offset,
partlen - dma_offset)) {
err = -EFAULT;
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, err);
goto err;
}
daddr += partlen;
ubuf += partlen;
dbuf += partlen;
vdev->in_bytes_dma += partlen;
vdev->in_bytes += partlen;
len -= partlen;
dma_offset = 0;
}
err = 0;
err:
vpdev->hw_ops->iounmap(vpdev, dbuf);
dev_dbg(vop_dev(vdev),
"%s: ubuf %p dbuf %p len 0x%lx vr_idx 0x%x\n",
__func__, ubuf, dbuf, len, vr_idx);
return err;
}
/*
* Initiates copies across the PCIe bus from a user space buffer to card
* memory. When transfers are done using DMA, source/destination addresses
* and transfer length must follow the alignment requirements of the MIC
* DMA engine.
*/
static int vop_virtio_copy_from_user(struct vop_vdev *vdev, void __user *ubuf,
size_t len, u64 daddr, size_t dlen,
int vr_idx)
{
struct vop_device *vpdev = vdev->vpdev;
void __iomem *dbuf = vpdev->hw_ops->ioremap(vpdev, daddr, len);
struct vop_vringh *vvr = &vdev->vvr[vr_idx];
struct vop_info *vi = dev_get_drvdata(&vdev->vpdev->dev);
size_t dma_alignment = 1 << vi->dma_ch->device->copy_align;
bool x200 = is_dma_copy_aligned(vi->dma_ch->device, 1, 1, 1);
size_t partlen;
bool dma = VOP_USE_DMA;
int err = 0;
if (daddr & (dma_alignment - 1)) {
vdev->tx_dst_unaligned += len;
dma = false;
} else if (ALIGN(len, dma_alignment) > dlen) {
vdev->tx_len_unaligned += len;
dma = false;
}
if (!dma)
goto memcpy;
/*
* X100 uses DMA addresses as seen by the card so adding
* the aperture base is not required for DMA. However x200
* requires DMA addresses to be an offset into the bar so
* add the aperture base for x200.
*/
if (x200)
daddr += vpdev->aper->pa;
while (len) {
partlen = min_t(size_t, len, VOP_INT_DMA_BUF_SIZE);
if (copy_from_user(vvr->buf, ubuf, partlen)) {
err = -EFAULT;
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, err);
goto err;
}
err = vop_sync_dma(vdev, daddr, vvr->buf_da,
ALIGN(partlen, dma_alignment));
if (err) {
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, err);
goto err;
}
daddr += partlen;
ubuf += partlen;
dbuf += partlen;
vdev->out_bytes_dma += partlen;
vdev->out_bytes += partlen;
len -= partlen;
}
memcpy:
/*
* We are copying to IO below and should ideally use something
* like copy_from_user_toio(..) if it existed.
*/
if (copy_from_user((void __force *)dbuf, ubuf, len)) {
err = -EFAULT;
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, err);
goto err;
}
vdev->out_bytes += len;
err = 0;
err:
vpdev->hw_ops->iounmap(vpdev, dbuf);
dev_dbg(vop_dev(vdev),
"%s: ubuf %p dbuf %p len 0x%lx vr_idx 0x%x\n",
__func__, ubuf, dbuf, len, vr_idx);
return err;
}
#define MIC_VRINGH_READ true
/* Determine the total number of bytes consumed in a VRINGH KIOV */
static inline u32 vop_vringh_iov_consumed(struct vringh_kiov *iov)
{
int i;
u32 total = iov->consumed;
for (i = 0; i < iov->i; i++)
total += iov->iov[i].iov_len;
return total;
}
/*
* Traverse the VRINGH KIOV and issue the APIs to trigger the copies.
* This API is heavily based on the vringh_iov_xfer(..) implementation
* in vringh.c. The reason we cannot reuse vringh_iov_pull_kern(..)
* and vringh_iov_push_kern(..) directly is because there is no
* way to override the VRINGH xfer(..) routines as of v3.10.
*/
static int vop_vringh_copy(struct vop_vdev *vdev, struct vringh_kiov *iov,
void __user *ubuf, size_t len, bool read, int vr_idx,
size_t *out_len)
{
int ret = 0;
size_t partlen, tot_len = 0;
while (len && iov->i < iov->used) {
struct kvec *kiov = &iov->iov[iov->i];
partlen = min(kiov->iov_len, len);
if (read)
ret = vop_virtio_copy_to_user(vdev, ubuf, partlen,
(u64)kiov->iov_base,
kiov->iov_len,
vr_idx);
else
ret = vop_virtio_copy_from_user(vdev, ubuf, partlen,
(u64)kiov->iov_base,
kiov->iov_len,
vr_idx);
if (ret) {
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, ret);
break;
}
len -= partlen;
ubuf += partlen;
tot_len += partlen;
iov->consumed += partlen;
kiov->iov_len -= partlen;
kiov->iov_base += partlen;
if (!kiov->iov_len) {
/* Fix up old iov element then increment. */
kiov->iov_len = iov->consumed;
kiov->iov_base -= iov->consumed;
iov->consumed = 0;
iov->i++;
}
}
*out_len = tot_len;
return ret;
}
/*
* Use the standard VRINGH infrastructure in the kernel to fetch new
* descriptors, initiate the copies and update the used ring.
*/
static int _vop_virtio_copy(struct vop_vdev *vdev, struct mic_copy_desc *copy)
{
int ret = 0;
u32 iovcnt = copy->iovcnt;
struct iovec iov;
struct iovec __user *u_iov = copy->iov;
void __user *ubuf = NULL;
struct vop_vringh *vvr = &vdev->vvr[copy->vr_idx];
struct vringh_kiov *riov = &vvr->riov;
struct vringh_kiov *wiov = &vvr->wiov;
struct vringh *vrh = &vvr->vrh;
u16 *head = &vvr->head;
struct mic_vring *vr = &vvr->vring;
size_t len = 0, out_len;
copy->out_len = 0;
/* Fetch a new IOVEC if all previous elements have been processed */
if (riov->i == riov->used && wiov->i == wiov->used) {
ret = vringh_getdesc_kern(vrh, riov, wiov,
head, GFP_KERNEL);
/* Check if there are available descriptors */
if (ret <= 0)
return ret;
}
while (iovcnt) {
if (!len) {
/* Copy over a new iovec from user space. */
ret = copy_from_user(&iov, u_iov, sizeof(*u_iov));
if (ret) {
ret = -EINVAL;
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, ret);
break;
}
len = iov.iov_len;
ubuf = iov.iov_base;
}
/* Issue all the read descriptors first */
ret = vop_vringh_copy(vdev, riov, ubuf, len,
MIC_VRINGH_READ, copy->vr_idx, &out_len);
if (ret) {
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, ret);
break;
}
len -= out_len;
ubuf += out_len;
copy->out_len += out_len;
/* Issue the write descriptors next */
ret = vop_vringh_copy(vdev, wiov, ubuf, len,
!MIC_VRINGH_READ, copy->vr_idx, &out_len);
if (ret) {
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, ret);
break;
}
len -= out_len;
ubuf += out_len;
copy->out_len += out_len;
if (!len) {
/* One user space iovec is now completed */
iovcnt--;
u_iov++;
}
/* Exit loop if all elements in KIOVs have been processed. */
if (riov->i == riov->used && wiov->i == wiov->used)
break;
}
/*
* Update the used ring if a descriptor was available and some data was
* copied in/out and the user asked for a used ring update.
*/
if (*head != USHRT_MAX && copy->out_len && copy->update_used) {
u32 total = 0;
/* Determine the total data consumed */
total += vop_vringh_iov_consumed(riov);
total += vop_vringh_iov_consumed(wiov);
vringh_complete_kern(vrh, *head, total);
*head = USHRT_MAX;
if (vringh_need_notify_kern(vrh) > 0)
vringh_notify(vrh);
vringh_kiov_cleanup(riov);
vringh_kiov_cleanup(wiov);
/* Update avail idx for user space */
vr->info->avail_idx = vrh->last_avail_idx;
}
return ret;
}
static inline int vop_verify_copy_args(struct vop_vdev *vdev,
struct mic_copy_desc *copy)
{
if (!vdev || copy->vr_idx >= vdev->dd->num_vq)
return -EINVAL;
return 0;
}
/* Copy a specified number of virtio descriptors in a chain */
static int vop_virtio_copy_desc(struct vop_vdev *vdev,
struct mic_copy_desc *copy)
{
int err;
struct vop_vringh *vvr;
err = vop_verify_copy_args(vdev, copy);
if (err)
return err;
vvr = &vdev->vvr[copy->vr_idx];
mutex_lock(&vvr->vr_mutex);
if (!vop_vdevup(vdev)) {
err = -ENODEV;
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, err);
goto err;
}
err = _vop_virtio_copy(vdev, copy);
if (err) {
dev_err(vop_dev(vdev), "%s %d err %d\n",
__func__, __LINE__, err);
}
err:
mutex_unlock(&vvr->vr_mutex);
return err;
}
static int vop_open(struct inode *inode, struct file *f)
{
struct vop_vdev *vdev;
struct vop_info *vi = container_of(f->private_data,
struct vop_info, miscdev);
vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
if (!vdev)
return -ENOMEM;
vdev->vi = vi;
mutex_init(&vdev->vdev_mutex);
f->private_data = vdev;
init_completion(&vdev->destroy);
complete(&vdev->destroy);
return 0;
}
static int vop_release(struct inode *inode, struct file *f)
{
struct vop_vdev *vdev = f->private_data, *vdev_tmp;
struct vop_info *vi = vdev->vi;
struct list_head *pos, *tmp;
bool found = false;
mutex_lock(&vdev->vdev_mutex);
if (vdev->deleted)
goto unlock;
mutex_lock(&vi->vop_mutex);
list_for_each_safe(pos, tmp, &vi->vdev_list) {
vdev_tmp = list_entry(pos, struct vop_vdev, list);
if (vdev == vdev_tmp) {
vop_virtio_del_device(vdev);
list_del(pos);
found = true;
break;
}
}
mutex_unlock(&vi->vop_mutex);
unlock:
mutex_unlock(&vdev->vdev_mutex);
if (!found)
wait_for_completion(&vdev->destroy);
f->private_data = NULL;
kfree(vdev);
return 0;
}
static long vop_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
{
struct vop_vdev *vdev = f->private_data;
struct vop_info *vi = vdev->vi;
void __user *argp = (void __user *)arg;
int ret;
switch (cmd) {
case MIC_VIRTIO_ADD_DEVICE:
{
struct mic_device_desc dd, *dd_config;
if (copy_from_user(&dd, argp, sizeof(dd)))
return -EFAULT;
if (mic_aligned_desc_size(&dd) > MIC_MAX_DESC_BLK_SIZE ||
dd.num_vq > MIC_MAX_VRINGS)
return -EINVAL;
dd_config = kzalloc(mic_desc_size(&dd), GFP_KERNEL);
if (!dd_config)
return -ENOMEM;
if (copy_from_user(dd_config, argp, mic_desc_size(&dd))) {
ret = -EFAULT;
goto free_ret;
}
/* Ensure desc has not changed between the two reads */
if (memcmp(&dd, dd_config, sizeof(dd))) {
ret = -EINVAL;
goto free_ret;
}
mutex_lock(&vdev->vdev_mutex);
mutex_lock(&vi->vop_mutex);
ret = vop_virtio_add_device(vdev, dd_config);
if (ret)
goto unlock_ret;
list_add_tail(&vdev->list, &vi->vdev_list);
unlock_ret:
mutex_unlock(&vi->vop_mutex);
mutex_unlock(&vdev->vdev_mutex);
free_ret:
kfree(dd_config);
return ret;
}
case MIC_VIRTIO_COPY_DESC:
{
struct mic_copy_desc copy;
mutex_lock(&vdev->vdev_mutex);
ret = vop_vdev_inited(vdev);
if (ret)
goto _unlock_ret;
if (copy_from_user(©, argp, sizeof(copy))) {
ret = -EFAULT;
goto _unlock_ret;
}
ret = vop_virtio_copy_desc(vdev, ©);
if (ret < 0)
goto _unlock_ret;
if (copy_to_user(
&((struct mic_copy_desc __user *)argp)->out_len,
©.out_len, sizeof(copy.out_len)))
ret = -EFAULT;
_unlock_ret:
mutex_unlock(&vdev->vdev_mutex);
return ret;
}
case MIC_VIRTIO_CONFIG_CHANGE:
{
void *buf;
mutex_lock(&vdev->vdev_mutex);
ret = vop_vdev_inited(vdev);
if (ret)
goto __unlock_ret;
buf = kzalloc(vdev->dd->config_len, GFP_KERNEL);
if (!buf) {
ret = -ENOMEM;
goto __unlock_ret;
}
if (copy_from_user(buf, argp, vdev->dd->config_len)) {
ret = -EFAULT;
goto done;
}
ret = vop_virtio_config_change(vdev, buf);
done:
kfree(buf);
__unlock_ret:
mutex_unlock(&vdev->vdev_mutex);
return ret;
}
default:
return -ENOIOCTLCMD;
};
return 0;
}
/*
* We return POLLIN | POLLOUT from poll when new buffers are enqueued, and
* not when previously enqueued buffers may be available. This means that
* in the card->host (TX) path, when userspace is unblocked by poll it
* must drain all available descriptors or it can stall.
*/
static unsigned int vop_poll(struct file *f, poll_table *wait)
{
struct vop_vdev *vdev = f->private_data;
int mask = 0;
mutex_lock(&vdev->vdev_mutex);
if (vop_vdev_inited(vdev)) {
mask = POLLERR;
goto done;
}
poll_wait(f, &vdev->waitq, wait);
if (vop_vdev_inited(vdev)) {
mask = POLLERR;
} else if (vdev->poll_wake) {
vdev->poll_wake = 0;
mask = POLLIN | POLLOUT;
}
done:
mutex_unlock(&vdev->vdev_mutex);
return mask;
}
static inline int
vop_query_offset(struct vop_vdev *vdev, unsigned long offset,
unsigned long *size, unsigned long *pa)
{
struct vop_device *vpdev = vdev->vpdev;
unsigned long start = MIC_DP_SIZE;
int i;
/*
* MMAP interface is as follows:
* offset region
* 0x0 virtio device_page
* 0x1000 first vring
* 0x1000 + size of 1st vring second vring
* ....
*/
if (!offset) {
*pa = virt_to_phys(vpdev->hw_ops->get_dp(vpdev));
*size = MIC_DP_SIZE;
return 0;
}
for (i = 0; i < vdev->dd->num_vq; i++) {
struct vop_vringh *vvr = &vdev->vvr[i];
if (offset == start) {
*pa = virt_to_phys(vvr->vring.va);
*size = vvr->vring.len;
return 0;
}
start += vvr->vring.len;
}
return -1;
}
/*
* Maps the device page and virtio rings to user space for readonly access.
*/
static int vop_mmap(struct file *f, struct vm_area_struct *vma)
{
struct vop_vdev *vdev = f->private_data;
unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
unsigned long pa, size = vma->vm_end - vma->vm_start, size_rem = size;
int i, err;
err = vop_vdev_inited(vdev);
if (err)
goto ret;
if (vma->vm_flags & VM_WRITE) {
err = -EACCES;
goto ret;
}
while (size_rem) {
i = vop_query_offset(vdev, offset, &size, &pa);
if (i < 0) {
err = -EINVAL;
goto ret;
}
err = remap_pfn_range(vma, vma->vm_start + offset,
pa >> PAGE_SHIFT, size,
vma->vm_page_prot);
if (err)
goto ret;
size_rem -= size;
offset += size;
}
ret:
return err;
}
static const struct file_operations vop_fops = {
.open = vop_open,
.release = vop_release,
.unlocked_ioctl = vop_ioctl,
.poll = vop_poll,
.mmap = vop_mmap,
.owner = THIS_MODULE,
};
int vop_host_init(struct vop_info *vi)
{
int rc;
struct miscdevice *mdev;
struct vop_device *vpdev = vi->vpdev;
INIT_LIST_HEAD(&vi->vdev_list);
vi->dma_ch = vpdev->dma_ch;
mdev = &vi->miscdev;
mdev->minor = MISC_DYNAMIC_MINOR;
snprintf(vi->name, sizeof(vi->name), "vop_virtio%d", vpdev->index);
mdev->name = vi->name;
mdev->fops = &vop_fops;
mdev->parent = &vpdev->dev;
rc = misc_register(mdev);
if (rc)
dev_err(&vpdev->dev, "%s failed rc %d\n", __func__, rc);
return rc;
}
void vop_host_uninit(struct vop_info *vi)
{
struct list_head *pos, *tmp;
struct vop_vdev *vdev;
mutex_lock(&vi->vop_mutex);
vop_virtio_reset_devices(vi);
list_for_each_safe(pos, tmp, &vi->vdev_list) {
vdev = list_entry(pos, struct vop_vdev, list);
list_del(pos);
reinit_completion(&vdev->destroy);
mutex_unlock(&vi->vop_mutex);
mutex_lock(&vdev->vdev_mutex);
vop_virtio_del_device(vdev);
vdev->deleted = true;
mutex_unlock(&vdev->vdev_mutex);
complete(&vdev->destroy);
mutex_lock(&vi->vop_mutex);
}
mutex_unlock(&vi->vop_mutex);
misc_deregister(&vi->miscdev);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5142_0 |
crossvul-cpp_data_bad_4787_7 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC L IIIII PPPP BBBB OOO AAA RRRR DDDD %
% C L I P P B B O O A A R R D D %
% C L I PPP BBBB O O AAAAA RRRR D D %
% C L I P B B O O A A R R D D %
% CCCC LLLLL IIIII P BBBB OOO A A R R DDDD %
% %
% %
% Read/Write Windows Clipboard. %
% %
% Software Design %
% Leonard Rosenthol %
% May 2002 %
% %
% %
% 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"
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
# if defined(__CYGWIN__)
# include <windows.h>
# else
/* All MinGW needs ... */
# include "magick/nt-base-private.h"
# include <wingdi.h>
# endif
#endif
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.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/nt-feature.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Forward declarations.
*/
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
static MagickBooleanType
WriteCLIPBOARDImage(const ImageInfo *,Image *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d C L I P B O A R D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadCLIPBOARDImage() reads an image from the system clipboard 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 ReadCLIPBOARDImage method is:
%
% Image *ReadCLIPBOARDImage(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.
%
*/
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
static Image *ReadCLIPBOARDImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
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);
{
HBITMAP
bitmapH;
HPALETTE
hPal;
OpenClipboard(NULL);
bitmapH=(HBITMAP) GetClipboardData(CF_BITMAP);
hPal=(HPALETTE) GetClipboardData(CF_PALETTE);
CloseClipboard();
if ( bitmapH == NULL )
ThrowReaderException(CoderError,"NoBitmapOnClipboard");
{
BITMAPINFO
DIBinfo;
BITMAP
bitmap;
HBITMAP
hBitmap,
hOldBitmap;
HDC
hDC,
hMemDC;
RGBQUAD
*pBits,
*ppBits;
/* create an offscreen DC for the source */
hMemDC=CreateCompatibleDC(NULL);
hOldBitmap=(HBITMAP) SelectObject(hMemDC,bitmapH);
GetObject(bitmapH,sizeof(BITMAP),(LPSTR) &bitmap);
if ((image->columns == 0) || (image->rows == 0))
{
image->rows=bitmap.bmHeight;
image->columns=bitmap.bmWidth;
}
/*
Initialize the bitmap header info.
*/
(void) ResetMagickMemory(&DIBinfo,0,sizeof(BITMAPINFO));
DIBinfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
DIBinfo.bmiHeader.biWidth=(LONG) image->columns;
DIBinfo.bmiHeader.biHeight=(-1)*(LONG) image->rows;
DIBinfo.bmiHeader.biPlanes=1;
DIBinfo.bmiHeader.biBitCount=32;
DIBinfo.bmiHeader.biCompression=BI_RGB;
hDC=GetDC(NULL);
if (hDC == 0)
ThrowReaderException(CoderError,"UnableToCreateADC");
hBitmap=CreateDIBSection(hDC,&DIBinfo,DIB_RGB_COLORS,(void **) &ppBits,
NULL,0);
ReleaseDC(NULL,hDC);
if (hBitmap == 0)
ThrowReaderException(CoderError,"UnableToCreateBitmap");
/* create an offscreen DC */
hDC=CreateCompatibleDC(NULL);
if (hDC == 0)
{
DeleteObject(hBitmap);
ThrowReaderException(CoderError,"UnableToCreateADC");
}
hOldBitmap=(HBITMAP) SelectObject(hDC,hBitmap);
if (hOldBitmap == 0)
{
DeleteDC(hDC);
DeleteObject(hBitmap);
ThrowReaderException(CoderError,"UnableToCreateBitmap");
}
if (hPal != NULL)
{
/* Kenichi Masuko says this needed */
SelectPalette(hDC, hPal, FALSE);
RealizePalette(hDC);
}
/* bitblt from the memory to the DIB-based one */
BitBlt(hDC,0,0,(int) image->columns,(int) image->rows,hMemDC,0,0,SRCCOPY);
/* finally copy the pixels! */
pBits=ppBits;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(pBits->rgbRed));
SetPixelGreen(q,ScaleCharToQuantum(pBits->rgbGreen));
SetPixelBlue(q,ScaleCharToQuantum(pBits->rgbBlue));
SetPixelOpacity(q,OpaqueOpacity);
pBits++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
DeleteDC(hDC);
DeleteObject(hBitmap);
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
#endif /* MAGICKCORE_WINGDI32_DELEGATE */
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r C L I P B O A R D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterCLIPBOARDImage() adds attributes for the clipboard "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 RegisterCLIPBOARDImage method is:
%
% size_t RegisterCLIPBOARDImage(void)
%
*/
ModuleExport size_t RegisterCLIPBOARDImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CLIPBOARD");
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadCLIPBOARDImage;
entry->encoder=(EncodeImageHandler *) WriteCLIPBOARDImage;
#endif
entry->adjoin=MagickFalse;
entry->format_type=ImplicitFormatType;
entry->description=ConstantString("The system clipboard");
entry->module=ConstantString("CLIPBOARD");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r C L I P B O A R D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterCLIPBOARDImage() removes format registrations made by the
% RGB module from the list of supported formats.
%
% The format of the UnregisterCLIPBOARDImage method is:
%
% UnregisterCLIPBOARDImage(void)
%
*/
ModuleExport void UnregisterCLIPBOARDImage(void)
{
(void) UnregisterMagickInfo("CLIPBOARD");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e C L I P B O A R D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteCLIPBOARDImage() writes an image to the system clipboard.
%
% The format of the WriteCLIPBOARDImage method is:
%
% MagickBooleanType WriteCLIPBOARDImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
static MagickBooleanType WriteCLIPBOARDImage(const ImageInfo *image_info,
Image *image)
{
/*
Allocate memory for pixels.
*/
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);
{
HBITMAP
bitmapH;
OpenClipboard(NULL);
EmptyClipboard();
bitmapH=(HBITMAP) ImageToHBITMAP(image,&image->exception);
SetClipboardData(CF_BITMAP,bitmapH);
CloseClipboard();
}
return(MagickTrue);
}
#endif /* MAGICKCORE_WINGDI32_DELEGATE */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4787_7 |
crossvul-cpp_data_bad_935_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP N N M M %
% P P NN N MM MM %
% PPPP N N N M M M %
% P N NN M M %
% P N N M M %
% %
% %
% Read/Write PBMPlus Portable Anymap Image 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 "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
/*
Typedef declarations.
*/
typedef struct _CommentInfo
{
char
*comment;
size_t
extent;
} CommentInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePNMImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P N M %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPNM() returns MagickTrue if the image format type, identified by the
% magick string, is PNM.
%
% The format of the IsPNM method is:
%
% MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o extent: Specifies the extent of the magick string.
%
*/
static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent)
{
if (extent < 2)
return(MagickFalse);
if ((*magick == (unsigned char) 'P') &&
((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') ||
(magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') ||
(magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f')))
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPNMImage() reads a Portable Anymap 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 ReadPNMImage method is:
%
% Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static int PNMComment(Image *image,CommentInfo *comment_info)
{
int
c;
register char
*p;
/*
Read comment.
*/
p=comment_info->comment+strlen(comment_info->comment);
for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++)
{
if ((size_t) (p-comment_info->comment+1) >= comment_info->extent)
{
comment_info->extent<<=1;
comment_info->comment=(char *) ResizeQuantumMemory(
comment_info->comment,comment_info->extent,
sizeof(*comment_info->comment));
if (comment_info->comment == (char *) NULL)
return(-1);
p=comment_info->comment+strlen(comment_info->comment);
}
c=ReadBlobByte(image);
if (c != EOF)
{
*p=(char) c;
*(p+1)='\0';
}
}
return(c);
}
static unsigned int PNMInteger(Image *image,CommentInfo *comment_info,
const unsigned int base)
{
int
c;
unsigned int
value;
/*
Skip any leading whitespace.
*/
do
{
c=ReadBlobByte(image);
if (c == EOF)
return(0);
if (c == (int) '#')
c=PNMComment(image,comment_info);
} while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'));
if (base == 2)
return((unsigned int) (c-(int) '0'));
/*
Evaluate number.
*/
value=0;
while (isdigit(c) != 0)
{
if (value <= (unsigned int) (INT_MAX/10))
{
value*=10;
if (value <= (unsigned int) (INT_MAX-(c-(int) '0')))
value+=c-(int) '0';
}
c=ReadBlobByte(image);
if (c == EOF)
return(0);
}
if (c == (int) '#')
c=PNMComment(image,comment_info);
return(value);
}
static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowPNMException(exception,message) \
{ \
if (comment_info.comment != (char *) NULL) \
comment_info.comment=DestroyString(comment_info.comment); \
ThrowReaderException((exception),(message)); \
}
char
format;
CommentInfo
comment_info;
double
quantum_scale;
Image
*image;
MagickBooleanType
status;
QuantumAny
max_value;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
size_t
depth,
extent,
packet_size;
ssize_t
count,
row,
y;
/*
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);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read PNM image.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
do
{
/*
Initialize image structure.
*/
comment_info.comment=AcquireString(NULL);
comment_info.extent=MagickPathExtent;
if ((count != 1) || (format != 'P'))
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
max_value=1;
quantum_type=RGBQuantum;
quantum_scale=1.0;
format=(char) ReadBlobByte(image);
if (format != '7')
{
/*
PBM, PGM, PPM, and PNM.
*/
image->columns=PNMInteger(image,&comment_info,10);
image->rows=PNMInteger(image,&comment_info,10);
if ((format == 'f') || (format == 'F'))
{
char
scale[MaxTextExtent];
if (ReadBlobString(image,scale) != (char *) NULL)
quantum_scale=StringToDouble(scale,(char **) NULL);
}
else
{
if ((format == '1') || (format == '4'))
max_value=1; /* bitmap */
else
max_value=PNMInteger(image,&comment_info,10);
}
}
else
{
char
keyword[MaxTextExtent],
value[MaxTextExtent];
int
c;
register char
*p;
/*
PAM.
*/
for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
{
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
if (c == '#')
{
/*
Comment.
*/
c=PNMComment(image,&comment_info);
c=ReadBlobByte(image);
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
p=keyword;
do
{
if ((size_t) (p-keyword) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
} while (isalnum(c));
*p='\0';
if (LocaleCompare(keyword,"endhdr") == 0)
break;
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
p=value;
while (isalnum(c) || (c == '_'))
{
if ((size_t) (p-value) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
if (LocaleCompare(keyword,"depth") == 0)
packet_size=StringToUnsignedLong(value);
(void) packet_size;
if (LocaleCompare(keyword,"height") == 0)
image->rows=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"maxval") == 0)
max_value=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"TUPLTYPE") == 0)
{
if (LocaleCompare(value,"BLACKANDWHITE") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
}
if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
image->matte=MagickTrue;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"GRAYSCALE") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
}
if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace);
image->matte=MagickTrue;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"RGB_ALPHA") == 0)
{
quantum_type=RGBAQuantum;
image->matte=MagickTrue;
}
if (LocaleCompare(value,"CMYK") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace);
quantum_type=CMYKQuantum;
}
if (LocaleCompare(value,"CMYK_ALPHA") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace);
image->matte=MagickTrue;
quantum_type=CMYKAQuantum;
}
}
if (LocaleCompare(keyword,"width") == 0)
image->columns=StringToUnsignedLong(value);
}
}
if ((image->columns == 0) || (image->rows == 0))
ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize");
if ((max_value == 0) || (max_value > 4294967295U))
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
for (depth=1; GetQuantumRange(depth) < max_value; depth++) ;
image->depth=depth;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image))
ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile");
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
(void) ResetImagePixels(image,exception);
/*
Convert PNM pixels.
*/
row=0;
switch (format)
{
case '1':
{
/*
Convert PBM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,PNMInteger(image,&comment_info,2) == 0 ?
QuantumRange : 0);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
image->type=BilevelType;
break;
}
case '2':
{
size_t
intensity;
/*
Convert PGM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelRed(q,intensity);
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
image->type=GrayscaleType;
break;
}
case '3':
{
/*
Convert PNM image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
QuantumAny
pixel;
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelRed(q,pixel);
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
SetPixelGreen(q,pixel);
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10),
max_value);
SetPixelBlue(q,pixel);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
break;
}
case '4':
{
/*
Convert PBM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
if (image->storage_class == PseudoClass)
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumMinIsWhite(quantum_info,MagickTrue);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register PixelPacket
*magick_restrict q;
ssize_t
count,
offset;
size_t
length;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (length != extent)
break;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case '5':
{
/*
Convert PGM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
count,
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case '6':
{
/*
Convert PNM raster image to pixel packets.
*/
quantum_type=RGBQuantum;
extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
count,
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
p=pixels;
switch (image->depth)
{
case 8:
{
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
q->opacity=OpaqueOpacity;
q++;
}
break;
}
case 16:
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleShortToQuantum(pixel));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleShortToQuantum(pixel));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleShortToQuantum(pixel));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
case 32:
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleLongToQuantum(pixel));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleLongToQuantum(pixel));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleLongToQuantum(pixel));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
break;
}
break;
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
register IndexPacket
*indexes;
size_t
channels;
/*
Convert PAM raster image to pixel packets.
*/
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
channels=1;
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
channels=4;
break;
}
default:
{
channels=3;
break;
}
}
if (image->matte != MagickFalse)
channels++;
extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
ssize_t
count,
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushCharPixel(p,&pixel);
if (image->depth != 1)
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
else
SetPixelOpacity(q,QuantumRange-ScaleAnyToQuantum(
pixel,max_value));
}
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value));
}
q++;
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,
max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushCharPixel(p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,
max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value));
}
q++;
}
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushCharPixel(p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushCharPixel(p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,
max_value));
}
q++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value));
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value));
}
q++;
}
break;
}
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case 'F':
case 'f':
{
/*
Convert PFM raster image to pixel packets.
*/
if (format == 'f')
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian;
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumDepth(image,quantum_info,32);
if (status == MagickFalse)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumScale(quantum_info,(MagickRealType) QuantumRange*
fabs(quantum_scale));
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register PixelPacket
*magick_restrict q;
ssize_t
count,
offset;
size_t
length;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if ((size_t) count != extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1),
image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (length != extent)
break;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
default:
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
}
if (*comment_info.comment != '\0')
(void) SetImageProperty(image,"comment",comment_info.comment);
comment_info.comment=DestroyString(comment_info.comment);
if (y < (ssize_t) image->rows)
ThrowPNMException(CorruptImageError,"UnableToReadImageData");
if (EOFBlob(image) != MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"UnexpectedEndOfFile","`%s'",image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((format == '1') || (format == '2') || (format == '3'))
do
{
/*
Skip to end of line.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
if (count != 1)
break;
if (format == 'P')
break;
} while (format != '\n');
count=ReadBlob(image,1,(unsigned char *) &format);
if ((count == 1) && (format == 'P'))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count == 1) && (format == 'P'));
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPNMImage() adds properties for the PNM 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 RegisterPNMImage method is:
%
% size_t RegisterPNMImage(void)
%
*/
ModuleExport size_t RegisterPNMImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("PAM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Common 2-dimensional bitmap format");
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PBM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Portable bitmap format (black and white)");
entry->mime_type=ConstantString("image/x-portable-bitmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PFM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Portable float format");
entry->module=ConstantString("PFM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PGM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Portable graymap format (gray scale)");
entry->mime_type=ConstantString("image/x-portable-greymap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->magick=(IsImageFormatHandler *) IsPNM;
entry->description=ConstantString("Portable anymap");
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PPM");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->description=ConstantString("Portable pixmap format (color)");
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->module=ConstantString("PNM");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPNMImage() removes format registrations made by the
% PNM module from the list of supported formats.
%
% The format of the UnregisterPNMImage method is:
%
% UnregisterPNMImage(void)
%
*/
ModuleExport void UnregisterPNMImage(void)
{
(void) UnregisterMagickInfo("PAM");
(void) UnregisterMagickInfo("PBM");
(void) UnregisterMagickInfo("PGM");
(void) UnregisterMagickInfo("PNM");
(void) UnregisterMagickInfo("PPM");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePNMImage() writes an image to a file in the PNM rasterfile format.
%
% The format of the WritePNMImage method is:
%
% MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
format,
magick[MaxTextExtent];
const char
*value;
IndexPacket
index;
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*pixels,
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
max_value=GetQuantumRange(image->depth);
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MaxTextExtent);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,&image->exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,&image->exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MaxTextExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MaxTextExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MaxTextExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,&image->exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MaxTextExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MaxTextExtent);
if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MaxTextExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MaxTextExtent);
break;
}
}
if (image->matte != MagickFalse)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MaxTextExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"TUPLTYPE %s\nENDHDR\n",
type);
(void) WriteBlobString(image,buffer);
}
/*
Convert to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToLong(index));
extent=(size_t) count;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
(void) strncpy((char *) q,buffer,extent);
q+=extent;
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(p)),
ScaleQuantumToChar(GetPixelGreen(p)),
ScaleQuantumToChar(GetPixelBlue(p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(p)),
ScaleQuantumToShort(GetPixelGreen(p)),
ScaleQuantumToShort(GetPixelBlue(p)));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(p)),
ScaleQuantumToLong(GetPixelGreen(p)),
ScaleQuantumToLong(GetPixelBlue(p)));
extent=(size_t) count;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
(void) strncpy((char *) q,buffer,extent);
q+=extent;
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 32)
pixel=ScaleQuantumToLong(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
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-119/c/bad_935_0 |
crossvul-cpp_data_bad_4787_17 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% EEEEE X X RRRR %
% E X X R R %
% EEE X RRRR %
% E X X R R %
% EEEEE X X R R %
% %
% %
% Read/Write High Dynamic-Range (HDR) Image File Format %
% %
% Software Design %
% Cristy %
% April 2007 %
% %
% %
% 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/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.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/pixel-accessor.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/resource_.h"
#include "magick/utility.h"
#if defined(MAGICKCORE_OPENEXR_DELEGATE)
#include <ImfCRgbaFile.h>
/*
Forward declarations.
*/
static MagickBooleanType
WriteEXRImage(const ImageInfo *,Image *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s E X R %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsEXR() returns MagickTrue if the image format type, identified by the
% magick string, is EXR.
%
% The format of the IsEXR method is:
%
% MagickBooleanType IsEXR(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 IsEXR(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\166\057\061\001",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
#if defined(MAGICKCORE_OPENEXR_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d E X R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadEXRImage reads an image in the high dynamic-range (HDR) file format
% developed by Industrial Light & Magic. It allocates the memory necessary
% for the new Image structure and returns a pointer to the new image.
%
% The format of the ReadEXRImage method is:
%
% Image *ReadEXRImage(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 *ReadEXRImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
const ImfHeader
*hdr_info;
Image
*image;
ImageInfo
*read_info;
ImfInputFile
*file;
ImfRgba
*scanline;
int
max_x,
max_y,
min_x,
min_y;
MagickBooleanType
status;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
/*
Open image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
read_info=CloneImageInfo(image_info);
if (IsPathAccessible(read_info->filename) == MagickFalse)
{
(void) AcquireUniqueFilename(read_info->filename);
(void) ImageToFile(image,read_info->filename,exception);
}
file=ImfOpenInputFile(read_info->filename);
if (file == (ImfInputFile *) NULL)
{
ThrowFileException(exception,BlobError,"UnableToOpenBlob",
ImfErrorMessage());
if (LocaleCompare(image_info->filename,read_info->filename) != 0)
(void) RelinquishUniqueFileResource(read_info->filename);
read_info=DestroyImageInfo(read_info);
return((Image *) NULL);
}
hdr_info=ImfInputHeader(file);
ImfHeaderDisplayWindow(hdr_info,&min_x,&min_y,&max_x,&max_y);
image->columns=max_x-min_x+1UL;
image->rows=max_y-min_y+1UL;
image->matte=MagickTrue;
SetImageColorspace(image,RGBColorspace);
if (image_info->ping != MagickFalse)
{
(void) ImfCloseInputFile(file);
if (LocaleCompare(image_info->filename,read_info->filename) != 0)
(void) RelinquishUniqueFileResource(read_info->filename);
read_info=DestroyImageInfo(read_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
scanline=(ImfRgba *) AcquireQuantumMemory(image->columns,sizeof(*scanline));
if (scanline == (ImfRgba *) NULL)
{
(void) ImfCloseInputFile(file);
if (LocaleCompare(image_info->filename,read_info->filename) != 0)
(void) RelinquishUniqueFileResource(read_info->filename);
read_info=DestroyImageInfo(read_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
ResetMagickMemory(scanline,0,image->columns*sizeof(*scanline));
ImfInputSetFrameBuffer(file,scanline-min_x-image->columns*(min_y+y),1,
image->columns);
ImfInputReadPixels(file,min_y+y,min_y+y);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ClampToQuantum((MagickRealType) QuantumRange*
ImfHalfToFloat(scanline[x].r)));
SetPixelGreen(q,ClampToQuantum((MagickRealType) QuantumRange*
ImfHalfToFloat(scanline[x].g)));
SetPixelBlue(q,ClampToQuantum((MagickRealType) QuantumRange*
ImfHalfToFloat(scanline[x].b)));
SetPixelAlpha(q,ClampToQuantum((MagickRealType) QuantumRange*
ImfHalfToFloat(scanline[x].a)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
scanline=(ImfRgba *) RelinquishMagickMemory(scanline);
(void) ImfCloseInputFile(file);
if (LocaleCompare(image_info->filename,read_info->filename) != 0)
(void) RelinquishUniqueFileResource(read_info->filename);
read_info=DestroyImageInfo(read_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r E X R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterEXRImage() adds properties for the EXR 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 RegisterEXRImage method is:
%
% size_t RegisterEXRImage(void)
%
*/
ModuleExport size_t RegisterEXRImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("EXR");
#if defined(MAGICKCORE_OPENEXR_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadEXRImage;
entry->encoder=(EncodeImageHandler *) WriteEXRImage;
#endif
entry->magick=(IsImageFormatHandler *) IsEXR;
entry->adjoin=MagickFalse;
entry->description=ConstantString("High Dynamic-range (HDR)");
entry->blob_support=MagickFalse;
entry->module=ConstantString("EXR");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r E X R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterEXRImage() removes format registrations made by the
% EXR module from the list of supported formats.
%
% The format of the UnregisterEXRImage method is:
%
% UnregisterEXRImage(void)
%
*/
ModuleExport void UnregisterEXRImage(void)
{
(void) UnregisterMagickInfo("EXR");
}
#if defined(MAGICKCORE_OPENEXR_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e E X R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteEXRImage() writes an image to a file the in the high dynamic-range
% (HDR) file format developed by Industrial Light & Magic.
%
% The format of the WriteEXRImage method is:
%
% MagickBooleanType WriteEXRImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteEXRImage(const ImageInfo *image_info,Image *image)
{
ImageInfo
*write_info;
ImfHalf
half_quantum;
ImfHeader
*hdr_info;
ImfOutputFile
*file;
ImfRgba
*scanline;
int
compression;
MagickBooleanType
status;
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) SetImageColorspace(image,RGBColorspace);
write_info=CloneImageInfo(image_info);
(void) AcquireUniqueFilename(write_info->filename);
hdr_info=ImfNewHeader();
ImfHeaderSetDataWindow(hdr_info,0,0,(int) image->columns-1,(int)
image->rows-1);
ImfHeaderSetDisplayWindow(hdr_info,0,0,(int) image->columns-1,(int)
image->rows-1);
compression=IMF_NO_COMPRESSION;
if (write_info->compression == ZipSCompression)
compression=IMF_ZIPS_COMPRESSION;
if (write_info->compression == ZipCompression)
compression=IMF_ZIP_COMPRESSION;
if (write_info->compression == PizCompression)
compression=IMF_PIZ_COMPRESSION;
if (write_info->compression == Pxr24Compression)
compression=IMF_PXR24_COMPRESSION;
#if defined(B44Compression)
if (write_info->compression == B44Compression)
compression=IMF_B44_COMPRESSION;
#endif
#if defined(B44ACompression)
if (write_info->compression == B44ACompression)
compression=IMF_B44A_COMPRESSION;
#endif
ImfHeaderSetCompression(hdr_info,compression);
ImfHeaderSetLineOrder(hdr_info,IMF_INCREASING_Y);
file=ImfOpenOutputFile(write_info->filename,hdr_info,IMF_WRITE_RGBA);
ImfDeleteHeader(hdr_info);
if (file == (ImfOutputFile *) NULL)
{
(void) RelinquishUniqueFileResource(write_info->filename);
write_info=DestroyImageInfo(write_info);
ThrowFileException(&image->exception,BlobError,"UnableToOpenBlob",
ImfErrorMessage());
return(MagickFalse);
}
scanline=(ImfRgba *) AcquireQuantumMemory(image->columns,sizeof(*scanline));
if (scanline == (ImfRgba *) NULL)
{
(void) ImfCloseOutputFile(file);
(void) RelinquishUniqueFileResource(write_info->filename);
write_info=DestroyImageInfo(write_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
ResetMagickMemory(scanline,0,image->columns*sizeof(*scanline));
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
ImfFloatToHalf(QuantumScale*GetPixelRed(p),&half_quantum);
scanline[x].r=half_quantum;
ImfFloatToHalf(QuantumScale*GetPixelGreen(p),&half_quantum);
scanline[x].g=half_quantum;
ImfFloatToHalf(QuantumScale*GetPixelBlue(p),&half_quantum);
scanline[x].b=half_quantum;
if (image->matte == MagickFalse)
ImfFloatToHalf(1.0,&half_quantum);
else
ImfFloatToHalf(1.0-QuantumScale*GetPixelOpacity(p),
&half_quantum);
scanline[x].a=half_quantum;
p++;
}
ImfOutputSetFrameBuffer(file,scanline-(y*image->columns),1,image->columns);
ImfOutputWritePixels(file,1);
}
(void) ImfCloseOutputFile(file);
scanline=(ImfRgba *) RelinquishMagickMemory(scanline);
(void) FileToImage(image,write_info->filename);
(void) RelinquishUniqueFileResource(write_info->filename);
write_info=DestroyImageInfo(write_info);
(void) CloseBlob(image);
return(MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4787_17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.